1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511"""Unit tests for API key authentication middleware."""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import Request, Response
from fastapi.responses import JSONResponse
from src.middleware.api_key_auth import APIKeyAuthMiddleware, _fingerprint
@pytest.fixture
def mock_app():
"""Create mock FastAPI app."""
return MagicMock()
@pytest.fixture
def mock_settings_with_keys():
"""Mock settings with API keys configured."""
with patch("src.middleware.api_key_auth.settings") as mock_settings:
mock_settings.api_key_header_name = "X-API-Key"
mock_settings.environment = "production"
mock_settings.api_keys = MagicMock()
mock_settings.api_keys.get_secret_value.return_value = "test-key-1,test-key-2"
yield mock_settings
@pytest.fixture
def mock_settings_no_keys():
"""Mock settings with no API keys."""
with patch("src.middleware.api_key_auth.settings") as mock_settings:
mock_settings.api_key_header_name = "X-API-Key"
mock_settings.environment = "production"
mock_settings.api_keys = None
yield mock_settings
@pytest.fixture
def middleware_with_keys(mock_app, mock_settings_with_keys):
"""Create middleware instance with API keys."""
return APIKeyAuthMiddleware(mock_app)
@pytest.fixture
def middleware_no_keys(mock_app, mock_settings_no_keys):
"""Create middleware instance without API keys."""
return APIKeyAuthMiddleware(mock_app)
def create_mock_request(path: str, headers: dict = None, client_host: str = "127.0.0.1"):
"""Create mock request."""
request = MagicMock(spec=Request)
request.url.path = path
request.method = "GET"
request.client = MagicMock()
request.client.host = client_host
request.state = MagicMock()
# Mock headers object with get method
mock_headers = MagicMock()
headers_dict = headers or {}
mock_headers.get = MagicMock(side_effect=lambda key, default=None: headers_dict.get(key, default))
request.headers = mock_headers
return request
@pytest.mark.unit
@pytest.mark.asyncio
async def test_valid_api_key_allows_request(middleware_with_keys):
"""Test that valid API key allows request through."""
# Setup
request = create_mock_request("/api/v1/documents/submit", {"X-API-Key": "test-key-1"})
call_next = AsyncMock(return_value=Response(status_code=200))
# Execute
response = await middleware_with_keys.dispatch(request, call_next)
# Assert
assert call_next.called
assert response.status_code == 200
assert request.state.api_key == "test-key-1"
@pytest.mark.unit
@pytest.mark.asyncio
async def test_second_valid_api_key_allows_request(middleware_with_keys):
"""Test that second valid API key also works."""
# Setup
request = create_mock_request("/api/v1/documents/submit", {"X-API-Key": "test-key-2"})
call_next = AsyncMock(return_value=Response(status_code=200))
# Execute
response = await middleware_with_keys.dispatch(request, call_next)
# Assert
assert call_next.called
assert response.status_code == 200
@pytest.mark.unit
@pytest.mark.asyncio
async def test_invalid_api_key_rejects_request(middleware_with_keys):
"""Test that invalid API key rejects request."""
# Setup
request = create_mock_request("/api/v1/documents/submit", {"X-API-Key": "invalid-key"})
call_next = AsyncMock()
# Execute
response = await middleware_with_keys.dispatch(request, call_next)
# Assert
assert not call_next.called
assert isinstance(response, JSONResponse)
assert response.status_code == 401
@pytest.mark.unit
@pytest.mark.asyncio
async def test_missing_api_key_rejects_request(middleware_with_keys):
"""Test that missing API key rejects request."""
# Setup
request = create_mock_request("/api/v1/documents/submit", {})
call_next = AsyncMock()
# Execute
response = await middleware_with_keys.dispatch(request, call_next)
# Assert
assert not call_next.called
assert isinstance(response, JSONResponse)
assert response.status_code == 401
assert "Missing API key" in str(response.body)
@pytest.mark.unit
@pytest.mark.asyncio
async def test_no_configured_keys_rejects_all_requests(middleware_no_keys):
"""Test that middleware without configured keys rejects all requests."""
# Setup
request = create_mock_request("/api/v1/documents/submit", {"X-API-Key": "any-key"})
call_next = AsyncMock()
# Execute
response = await middleware_no_keys.dispatch(request, call_next)
# Assert
assert not call_next.called
assert isinstance(response, JSONResponse)
assert response.status_code == 401
@pytest.mark.unit
@pytest.mark.asyncio
async def test_health_endpoint_bypasses_auth(middleware_with_keys):
"""Test that /health endpoint bypasses authentication."""
# Setup
request = create_mock_request("/health", {})
call_next = AsyncMock(return_value=Response(status_code=200))
# Execute
response = await middleware_with_keys.dispatch(request, call_next)
# Assert
assert call_next.called
assert response.status_code == 200
@pytest.mark.unit
@pytest.mark.asyncio
async def test_metrics_endpoint_bypasses_auth(middleware_with_keys):
"""Test that /metrics endpoint bypasses authentication."""
# Setup
request = create_mock_request("/metrics", {})
call_next = AsyncMock(return_value=Response(status_code=200))
# Execute
response = await middleware_with_keys.dispatch(request, call_next)
# Assert
assert call_next.called
assert response.status_code == 200
@pytest.mark.unit
@pytest.mark.asyncio
async def test_dev_monitoring_bypasses_auth_in_dev(mock_app):
"""Test that dev monitoring endpoints bypass auth in dev environment."""
# Setup - dev environment
with patch("src.middleware.api_key_auth.settings") as mock_settings:
mock_settings.api_key_header_name = "X-API-Key"
mock_settings.environment = "dev"
mock_settings.api_keys = MagicMock()
mock_settings.api_keys.get_secret_value.return_value = "test-key-1"
middleware = APIKeyAuthMiddleware(mock_app)
request = create_mock_request("/api/dev/monitoring/queues", {})
call_next = AsyncMock(return_value=Response(status_code=200))
# Execute
response = await middleware.dispatch(request, call_next)
# Assert
assert call_next.called
assert response.status_code == 200
@pytest.mark.unit
@pytest.mark.asyncio
async def test_dev_monitoring_requires_auth_in_production(middleware_with_keys):
"""Test that dev monitoring endpoints require auth in production."""
# Setup - production environment (middleware_with_keys is production)
request = create_mock_request("/api/dev/monitoring/queues", {})
call_next = AsyncMock()
# Execute
response = await middleware_with_keys.dispatch(request, call_next)
# Assert
assert not call_next.called
assert response.status_code == 401
@pytest.mark.unit
@pytest.mark.asyncio
async def test_case_sensitive_api_key(middleware_with_keys):
"""Test that API key validation is case-sensitive."""
# Setup - try uppercase version of valid key
request = create_mock_request("/api/v1/documents/submit", {"X-API-Key": "TEST-KEY-1"})
call_next = AsyncMock()
# Execute
response = await middleware_with_keys.dispatch(request, call_next)
# Assert
assert not call_next.called
assert response.status_code == 401
@pytest.mark.unit
@pytest.mark.asyncio
async def test_whitespace_stripped_from_keys():
"""Test that whitespace is stripped from configured keys."""
# Setup - keys with whitespace in configuration
mock_app = MagicMock()
with patch("src.middleware.api_key_auth.settings") as mock_settings:
mock_settings.api_key_header_name = "X-API-Key"
mock_settings.environment = "production"
mock_settings.api_keys = MagicMock()
mock_settings.api_keys.get_secret_value.return_value = " key-1 , key-2 , key-3 "
middleware = APIKeyAuthMiddleware(mock_app)
request = create_mock_request("/api/v1/documents/submit", {"X-API-Key": "key-1"})
call_next = AsyncMock(return_value=Response(status_code=200))
# Execute
response = await middleware.dispatch(request, call_next)
# Assert
assert call_next.called
assert response.status_code == 200
@pytest.mark.unit
@pytest.mark.asyncio
async def test_custom_header_name():
"""Test that custom header name works."""
# Setup - custom header name
mock_app = MagicMock()
with patch("src.middleware.api_key_auth.settings") as mock_settings:
mock_settings.api_key_header_name = "Authorization"
mock_settings.environment = "production"
mock_settings.api_keys = MagicMock()
mock_settings.api_keys.get_secret_value.return_value = "custom-key"
middleware = APIKeyAuthMiddleware(mock_app)
request = create_mock_request("/api/v1/documents/submit", {"Authorization": "custom-key"})
call_next = AsyncMock(return_value=Response(status_code=200))
# Execute
response = await middleware.dispatch(request, call_next)
# Assert
assert call_next.called
assert response.status_code == 200
@pytest.mark.unit
@pytest.mark.asyncio
async def test_client_ip_extraction_from_x_forwarded_for(middleware_with_keys):
"""Test client IP extraction from X-Forwarded-For header."""
# Setup
request = create_mock_request(
"/api/v1/documents/submit",
{
"X-Forwarded-For": "1.2.3.4, 5.6.7.8",
"X-API-Key": "invalid-key"
}
)
call_next = AsyncMock()
# Execute
response = await middleware_with_keys.dispatch(request, call_next)
# Assert - just verify it doesn't crash with forwarded header
assert response.status_code == 401
@pytest.mark.unit
@pytest.mark.asyncio
async def test_www_authenticate_header_in_response(middleware_with_keys):
"""Test that 401 response includes WWW-Authenticate header."""
# Setup
request = create_mock_request("/api/v1/documents/submit", {})
call_next = AsyncMock()
# Execute
response = await middleware_with_keys.dispatch(request, call_next)
# Assert
assert response.status_code == 401
assert "WWW-Authenticate" in response.headers
assert "ApiKey" in response.headers["WWW-Authenticate"]
@pytest.mark.unit
def test_load_api_keys_empty_string():
"""Test loading API keys from empty string."""
# Setup
mock_app = MagicMock()
with patch("src.middleware.api_key_auth.settings") as mock_settings:
mock_settings.api_key_header_name = "X-API-Key"
mock_settings.environment = "production"
mock_settings.api_keys = MagicMock()
mock_settings.api_keys.get_secret_value.return_value = " , , "
# Execute
middleware = APIKeyAuthMiddleware(mock_app)
loaded_keys = middleware._load_api_keys()
# Assert - empty strings and whitespace should result in no keys
assert len(loaded_keys) == 0
@pytest.mark.unit
def test_multiple_keys_loaded_correctly():
"""Test that multiple keys are loaded correctly."""
# Setup
mock_app = MagicMock()
with patch("src.middleware.api_key_auth.settings") as mock_settings:
mock_settings.api_key_header_name = "X-API-Key"
mock_settings.environment = "production"
mock_settings.api_keys = MagicMock()
mock_settings.api_keys.get_secret_value.return_value = "key1,key2,key3"
# Execute
middleware = APIKeyAuthMiddleware(mock_app)
loaded_keys = middleware._load_api_keys()
# Assert - keys loaded dynamically
assert len(loaded_keys) == 3
assert "key1" in loaded_keys
assert "key2" in loaded_keys
assert "key3" in loaded_keys
@pytest.mark.unit
def test_keys_loaded_once_at_initialization():
"""Test that API keys are loaded only once at initialization."""
# Setup
mock_app = MagicMock()
with patch("src.middleware.api_key_auth.settings") as mock_settings:
mock_settings.api_key_header_name = "X-API-Key"
mock_settings.environment = "production"
mock_settings.api_keys = MagicMock()
mock_settings.api_keys.get_secret_value.return_value = "test-key-1,test-key-2"
# Track _load_api_keys calls by patching at module level
original_load = APIKeyAuthMiddleware._load_api_keys
load_calls = []
def tracked_load(self):
load_calls.append(1)
return original_load(self)
with patch.object(APIKeyAuthMiddleware, '_load_api_keys', tracked_load):
# Execute - create middleware instance
middleware = APIKeyAuthMiddleware(mock_app)
# Assert - _load_api_keys called exactly once during __init__
assert len(load_calls) == 1
# Verify keys are cached
assert len(middleware._cached_keys) == 2
assert "test-key-1" in middleware._cached_keys
assert "test-key-2" in middleware._cached_keys
@pytest.mark.unit
@pytest.mark.asyncio
async def test_cached_keys_used_on_multiple_requests():
"""Test that cached keys are used for multiple requests without reloading."""
# Setup
mock_app = MagicMock()
with patch("src.middleware.api_key_auth.settings") as mock_settings:
mock_settings.api_key_header_name = "X-API-Key"
mock_settings.environment = "production"
mock_settings.api_keys = MagicMock()
mock_settings.api_keys.get_secret_value.return_value = "test-key-1"
# Track _load_api_keys calls
original_load = APIKeyAuthMiddleware._load_api_keys
call_count = 0
def tracked_load(self):
nonlocal call_count
call_count += 1
return original_load(self)
with patch.object(APIKeyAuthMiddleware, '_load_api_keys', tracked_load):
# Create middleware (loads keys once)
middleware = APIKeyAuthMiddleware(mock_app)
initial_call_count = call_count
# Execute - make multiple requests
call_next = AsyncMock(return_value=Response(status_code=200))
for _ in range(5):
request = create_mock_request("/api/v1/documents/submit", {"X-API-Key": "test-key-1"})
await middleware.dispatch(request, call_next)
# Assert - _load_api_keys only called once during initialization
assert call_count == initial_call_count
assert call_count == 1
assert call_next.call_count == 5
# ---------- labelled API keys (usage attribution) ----------
def _middleware_with(raw_keys: str) -> APIKeyAuthMiddleware:
"""Build a middleware instance whose API_KEYS is `raw_keys`."""
mock_app = MagicMock()
with patch("src.middleware.api_key_auth.settings") as mock_settings:
mock_settings.api_key_header_name = "X-API-Key"
mock_settings.environment = "production"
mock_settings.api_keys = MagicMock()
mock_settings.api_keys.get_secret_value.return_value = raw_keys
return APIKeyAuthMiddleware(mock_app)
@pytest.mark.unit
def test_fingerprint_is_stable_and_does_not_leak_key():
fp = _fingerprint("super-secret-key")
assert fp == _fingerprint("super-secret-key") # deterministic
assert fp.startswith("key-")
assert "super-secret-key" not in fp
@pytest.mark.unit
def test_labelled_keys_parsed_into_key_to_label_map():
mw = _middleware_with("zach:key-zzz,daisy:key-ddd")
assert mw._cached_keys == {"key-zzz": "zach", "key-ddd": "daisy"}
@pytest.mark.unit
def test_bare_key_gets_fingerprint_label():
mw = _middleware_with("plainkey")
assert mw._cached_keys["plainkey"] == _fingerprint("plainkey")
@pytest.mark.unit
def test_mixed_labelled_and_bare_keys():
mw = _middleware_with("zach:key-a,key-b")
assert mw._cached_keys["key-a"] == "zach"
assert mw._cached_keys["key-b"] == _fingerprint("key-b")
@pytest.mark.unit
def test_label_split_on_first_colon_only():
# A key that itself contains colons works when explicitly labelled:
# everything after the first colon is the key.
mw = _middleware_with("svc:weird:key:with:colons")
assert mw._cached_keys == {"weird:key:with:colons": "svc"}
@pytest.mark.unit
@pytest.mark.asyncio
async def test_valid_labelled_key_sets_label_on_request_state():
mw = _middleware_with("zach:key-zzz,daisy:key-ddd")
request = create_mock_request("/api/v1/documents/submit", {"X-API-Key": "key-ddd"})
call_next = AsyncMock(return_value=Response(status_code=200))
response = await mw.dispatch(request, call_next)
assert response.status_code == 200
assert request.state.api_key == "key-ddd"
assert request.state.api_key_label == "daisy"
@pytest.mark.unit
@pytest.mark.asyncio
async def test_bare_key_sets_fingerprint_label_on_request_state():
mw = _middleware_with("plainkey")
request = create_mock_request("/api/v1/documents/submit", {"X-API-Key": "plainkey"})
call_next = AsyncMock(return_value=Response(status_code=200))
await mw.dispatch(request, call_next)
assert request.state.api_key_label == _fingerprint("plainkey")