-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathtest_jwk_token.py
More file actions
583 lines (443 loc) · 17.6 KB
/
Copy pathtest_jwk_token.py
File metadata and controls
583 lines (443 loc) · 17.6 KB
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# pylint: disable=redefined-outer-name
"""Unit tests for functions defined in authentication/jwk_token.py"""
import time
from typing import Any, Generator
from pytest_mock import MockerFixture
import pytest
from fastapi import HTTPException, Request
from pydantic import AnyHttpUrl
from authlib.jose import JsonWebKey, JsonWebToken
from authentication.jwk_token import JwkTokenAuthDependency, _jwk_cache
from constants import DEFAULT_USER_NAME, DEFAULT_USER_UID, NO_USER_TOKEN
from models.config import JwkConfiguration, JwtConfiguration
TEST_USER_ID = "test-user-123"
TEST_USER_NAME = "testuser"
@pytest.fixture
def token_header(single_key_set: list[dict[str, Any]]) -> dict[str, Any]:
"""A sample token header."""
return {"alg": "RS256", "typ": "JWT", "kid": single_key_set[0]["kid"]}
@pytest.fixture
def token_payload() -> dict[str, Any]:
"""A sample token payload with the default user_id and username claims."""
return {
"user_id": TEST_USER_ID,
"username": TEST_USER_NAME,
"exp": int(time.time()) + 3600,
"iat": int(time.time()),
}
def make_key() -> dict[str, Any]:
"""Generate a key pair for testing purposes."""
key = JsonWebKey.generate_key("RSA", 2048, is_private=True)
return {
"private_key": key,
"public_key": key.get_public_key(),
"kid": key.thumbprint(),
}
@pytest.fixture
def single_key_set() -> list[dict[str, Any]]:
"""Default single-key set for signing tokens."""
return [make_key()]
@pytest.fixture
def another_single_key_set() -> list[dict[str, Any]]:
"""Same as single_key_set, but generates a different key pair by being its own fixture."""
return [make_key()]
@pytest.fixture
def valid_token(
single_key_set: list[dict[str, Any]],
token_header: dict[str, Any],
token_payload: dict[str, Any],
) -> str:
"""A token that is valid and signed with the signing keys."""
jwt_instance = JsonWebToken(algorithms=["RS256"])
return jwt_instance.encode(
token_header, token_payload, single_key_set[0]["private_key"]
).decode()
@pytest.fixture(autouse=True)
def clear_jwk_cache() -> Generator:
"""Clear the global JWK cache before each test."""
_jwk_cache.clear()
yield
_jwk_cache.clear()
def make_signing_server(
mocker: MockerFixture, key_set: list[dict[str, Any]], algorithms: list[str]
) -> Any:
"""A fake server to serve our signing keys as JWKs."""
mock_session_class = mocker.patch("aiohttp.ClientSession")
mock_response = mocker.AsyncMock()
# Create JWK dict from private key as public key
keys = [
{
**key["private_key"].as_dict(private=False),
"kid": key["kid"],
"alg": alg,
}
for alg, key in zip(algorithms, key_set)
]
mock_response.json.return_value = {
"keys": keys,
}
mock_response.raise_for_status = mocker.MagicMock(return_value=None)
# Create mock session instance that acts as async context manager
mock_session_instance = mocker.AsyncMock()
mock_session_instance.__aenter__ = mocker.AsyncMock(
return_value=mock_session_instance
)
mock_session_instance.__aexit__ = mocker.AsyncMock(return_value=None)
# Mock the get method to return a context manager
mock_get_context = mocker.AsyncMock()
mock_get_context.__aenter__ = mocker.AsyncMock(return_value=mock_response)
mock_get_context.__aexit__ = mocker.AsyncMock(return_value=None)
mock_session_instance.get = mocker.MagicMock(return_value=mock_get_context)
mock_session_class.return_value = mock_session_instance
return mock_session_class
@pytest.fixture
def mocked_signing_keys_server(
mocker: MockerFixture, single_key_set: list[dict[str, Any]]
) -> None:
"""Single-key signing server."""
return make_signing_server(mocker, single_key_set, ["RS256"])
@pytest.fixture
def default_jwk_configuration() -> JwkConfiguration:
"""Default JwkConfiguration for testing."""
return JwkConfiguration(
url=AnyHttpUrl("https://this#isgonnabemocked.com/jwks.json"),
jwt_configuration=JwtConfiguration(
# Should default to:
# user_id_claim="user_id", username_claim="username"
),
)
def dummy_request(token: str) -> Request:
"""Generate a dummy request with a given token."""
return Request(
scope={
"type": "http",
"query_string": b"",
"headers": [(b"authorization", f"Bearer {token}".encode())],
},
)
@pytest.fixture
def no_token_request() -> Request:
"""Dummy request with no token."""
return Request(
scope={
"type": "http",
"query_string": b"",
"headers": [],
},
)
@pytest.fixture
def not_bearer_token_request() -> Request:
"""Dummy request with no token."""
return Request(
scope={
"type": "http",
"query_string": b"",
"headers": [(b"authorization", b"NotBearer anything")],
},
)
def set_auth_header(request: Request, token: str) -> None:
"""Helper function to set the Authorization header in a request."""
new_headers = [
(k, v) for k, v in request.scope["headers"] if k.lower() != b"authorization"
]
new_headers.append((b"authorization", token.encode()))
request.scope["headers"] = new_headers
def ensure_test_user_id_and_name(auth_tuple: tuple, expected_token: str) -> None:
"""Utility to ensure that the values in the auth tuple match the test values."""
user_id, username, skip_userid_check, token = auth_tuple
assert user_id == TEST_USER_ID
assert username == TEST_USER_NAME
assert skip_userid_check is False
assert token == expected_token
async def test_valid(
default_jwk_configuration: JwkConfiguration,
mocked_signing_keys_server: Any,
valid_token: str,
) -> None:
"""Test with a valid token."""
_ = mocked_signing_keys_server
dependency = JwkTokenAuthDependency(default_jwk_configuration)
auth_tuple = await dependency(dummy_request(valid_token))
# Assert the expected values
ensure_test_user_id_and_name(auth_tuple, valid_token)
@pytest.fixture
def expired_token(
single_key_set: list[dict[str, Any]],
token_header: dict[str, Any],
token_payload: dict[str, Any],
) -> str:
"""An well-signed yet expired token."""
jwt_instance = JsonWebToken(algorithms=["RS256"])
token_payload["exp"] = int(time.time()) - 3600 # Set expiration in the past
return jwt_instance.encode(
token_header, token_payload, single_key_set[0]["private_key"]
).decode()
async def test_expired(
default_jwk_configuration: JwkConfiguration,
mocked_signing_keys_server: Any,
expired_token: str,
) -> None:
"""Test with an expired token."""
_ = mocked_signing_keys_server
dependency = JwkTokenAuthDependency(default_jwk_configuration)
# Assert that an HTTPException is raised when the token is expired
with pytest.raises(HTTPException) as exc_info:
await dependency(dummy_request(expired_token))
assert "Token has expired" in str(exc_info.value)
assert exc_info.value.status_code == 401
@pytest.fixture
def invalid_token(
another_single_key_set: list[dict[str, Any]],
token_header: dict[str, Any],
token_payload: dict[str, Any],
) -> str:
"""A token that is signed with different keys than the signing keys."""
jwt_instance = JsonWebToken(algorithms=["RS256"])
return jwt_instance.encode(
token_header, token_payload, another_single_key_set[0]["private_key"]
).decode()
async def test_invalid(
default_jwk_configuration: JwkConfiguration,
mocked_signing_keys_server: Any,
invalid_token: str,
) -> None:
"""Test with an invalid token."""
_ = mocked_signing_keys_server
dependency = JwkTokenAuthDependency(default_jwk_configuration)
with pytest.raises(HTTPException) as exc_info:
await dependency(dummy_request(invalid_token))
assert "Invalid token" in str(exc_info.value)
assert exc_info.value.status_code == 401
async def test_no_auth_header(
default_jwk_configuration: JwkConfiguration,
mocked_signing_keys_server: Any,
no_token_request: Request,
) -> None:
"""Test with no Authorization header."""
_ = mocked_signing_keys_server
dependency = JwkTokenAuthDependency(default_jwk_configuration)
user_id, username, skip_userid_check, token_claims = await dependency(
no_token_request
)
assert user_id == DEFAULT_USER_UID
assert username == DEFAULT_USER_NAME
assert skip_userid_check is True
assert token_claims == NO_USER_TOKEN
async def test_no_bearer(
default_jwk_configuration: JwkConfiguration,
mocked_signing_keys_server: Any,
not_bearer_token_request: Request,
) -> None:
"""Test with Authorization header that does not start with Bearer."""
_ = mocked_signing_keys_server
dependency = JwkTokenAuthDependency(default_jwk_configuration)
with pytest.raises(HTTPException) as exc_info:
await dependency(not_bearer_token_request)
assert exc_info.value.status_code == 401
assert exc_info.value.detail == "No token found in Authorization header"
@pytest.fixture
def no_user_id_token(
single_key_set: list[dict[str, Any]],
token_payload: dict[str, Any],
token_header: dict[str, Any],
) -> str:
"""Token without a user_id claim."""
jwt_instance = JsonWebToken(algorithms=["RS256"])
# Modify the token payload to include different claims
del token_payload["user_id"]
return jwt_instance.encode(
token_header, token_payload, single_key_set[0]["private_key"]
).decode()
async def test_no_user_id(
default_jwk_configuration: JwkConfiguration,
mocked_signing_keys_server: Any,
no_user_id_token: str,
) -> None:
"""Test with a token that has no user_id claim."""
_ = mocked_signing_keys_server
dependency = JwkTokenAuthDependency(default_jwk_configuration)
with pytest.raises(HTTPException) as exc_info:
await dependency(dummy_request(no_user_id_token))
assert exc_info.value.status_code == 401
assert "user_id" in str(exc_info.value.detail) and "missing" in str(
exc_info.value.detail
)
@pytest.fixture
def no_username_token(
single_key_set: list[dict[str, Any]],
token_payload: dict[str, Any],
token_header: dict[str, Any],
) -> str:
"""Token without a username claim."""
jwt_instance = JsonWebToken(algorithms=["RS256"])
# Modify the token payload to include different claims
del token_payload["username"]
return jwt_instance.encode(
token_header, token_payload, single_key_set[0]["private_key"]
).decode()
async def test_no_username(
default_jwk_configuration: JwkConfiguration,
mocked_signing_keys_server: Any,
no_username_token: str,
) -> None:
"""Test with a token that has no username claim."""
_ = mocked_signing_keys_server
dependency = JwkTokenAuthDependency(default_jwk_configuration)
with pytest.raises(HTTPException) as exc_info:
await dependency(dummy_request(no_username_token))
assert exc_info.value.status_code == 401
assert "username" in str(exc_info.value.detail) and "missing" in str(
exc_info.value.detail
)
@pytest.fixture
def custom_claims_token(
single_key_set: list[dict[str, Any]],
token_payload: dict[str, Any],
token_header: dict[str, Any],
) -> str:
"""Token with custom claims."""
jwt_instance = JsonWebToken(algorithms=["RS256"])
del token_payload["user_id"]
del token_payload["username"]
# Add custom claims
token_payload["id_of_the_user"] = TEST_USER_ID
token_payload["name_of_the_user"] = TEST_USER_NAME
return jwt_instance.encode(
token_header, token_payload, single_key_set[0]["private_key"]
).decode()
@pytest.fixture
def custom_claims_configuration(
default_jwk_configuration: JwkConfiguration,
) -> JwkConfiguration:
"""Configuration for custom claims."""
# Create a copy of the default configuration
custom_config = default_jwk_configuration.model_copy()
# Set custom claims
custom_config.jwt_configuration.user_id_claim = "id_of_the_user"
custom_config.jwt_configuration.username_claim = "name_of_the_user"
return custom_config
async def test_custom_claims(
custom_claims_configuration: JwkConfiguration,
mocked_signing_keys_server: Any,
custom_claims_token: str,
) -> None:
"""Test with a token that has custom claims."""
_ = mocked_signing_keys_server
dependency = JwkTokenAuthDependency(custom_claims_configuration)
auth_tuple = await dependency(dummy_request(custom_claims_token))
# Assert the expected values
ensure_test_user_id_and_name(auth_tuple, custom_claims_token)
@pytest.fixture
def token_header_256_1(multi_key_set: list[dict[str, Any]]) -> dict[str, Any]:
"""A sample token header for RS256 using multi_key_set."""
return {"alg": "RS256", "typ": "JWT", "kid": multi_key_set[0]["kid"]}
@pytest.fixture
def token_header_256_2(multi_key_set: list[dict[str, Any]]) -> dict[str, Any]:
"""A sample token header for RS256 using multi_key_set."""
return {"alg": "RS256", "typ": "JWT", "kid": multi_key_set[1]["kid"]}
@pytest.fixture
def token_header_384(multi_key_set: list[dict[str, Any]]) -> dict[str, Any]:
"""A sample token header."""
return {"alg": "RS384", "typ": "JWT", "kid": multi_key_set[2]["kid"]}
@pytest.fixture
def token_header_256_no_kid() -> dict[str, Any]:
"""RS256 no kid."""
return {"alg": "RS256", "typ": "JWT"}
@pytest.fixture
def token_header_384_no_kid() -> dict[str, Any]:
"""RS384 no kid."""
return {"alg": "RS384", "typ": "JWT"}
@pytest.fixture
def multi_key_set() -> list[dict[str, Any]]:
"""Default multi-key set for signing tokens."""
return [make_key(), make_key(), make_key()]
@pytest.fixture
def valid_tokens(
multi_key_set: list[dict[str, Any]],
token_header_256_1: dict[str, Any],
token_header_256_2: dict[str, Any],
token_payload: dict[str, Any],
token_header_384: dict[str, Any],
) -> tuple[str, str, str]:
"""Generate valid tokens for each key in the multi-key set."""
key_for_256_1 = multi_key_set[0]
key_for_256_2 = multi_key_set[1]
key_for_384 = multi_key_set[2]
jwt_instance1 = JsonWebToken(algorithms=["RS256"])
token1 = jwt_instance1.encode(
token_header_256_1, token_payload, key_for_256_1["private_key"]
).decode()
jwt_instance2 = JsonWebToken(algorithms=["RS256"])
token2 = jwt_instance2.encode(
token_header_256_2, token_payload, key_for_256_2["private_key"]
).decode()
jwt_instance3 = JsonWebToken(algorithms=["RS384"])
token3 = jwt_instance3.encode(
token_header_384, token_payload, key_for_384["private_key"]
).decode()
return token1, token2, token3
@pytest.fixture
def valid_tokens_no_kid(
multi_key_set: list[dict[str, Any]],
token_header_256_no_kid: dict[str, Any],
token_payload: dict[str, Any],
token_header_384_no_kid: dict[str, Any],
) -> tuple[str, str, str]:
"""Generate valid tokens for each key in the multi-key set without a kid."""
key_for_256_1 = multi_key_set[0]
key_for_256_2 = multi_key_set[1]
key_for_384 = multi_key_set[2]
jwt_instance1 = JsonWebToken(algorithms=["RS256"])
token1 = jwt_instance1.encode(
token_header_256_no_kid, token_payload, key_for_256_1["private_key"]
).decode()
jwt_instance2 = JsonWebToken(algorithms=["RS256"])
token2 = jwt_instance2.encode(
token_header_256_no_kid, token_payload, key_for_256_2["private_key"]
).decode()
jwt_instance3 = JsonWebToken(algorithms=["RS384"])
token3 = jwt_instance3.encode(
token_header_384_no_kid, token_payload, key_for_384["private_key"]
).decode()
return token1, token2, token3
@pytest.fixture
def multi_key_signing_server(
mocker: MockerFixture, multi_key_set: list[dict[str, Any]]
) -> Any:
"""Multi-key signing server."""
return make_signing_server(mocker, multi_key_set, ["RS256", "RS256", "RS384"])
async def test_multi_key_valid(
default_jwk_configuration: JwkConfiguration,
multi_key_signing_server: Any,
valid_tokens: tuple[str, str, str],
) -> None:
"""Test with valid tokens from a multi-key set."""
_ = multi_key_signing_server
token1, token2, token3 = valid_tokens
dependency = JwkTokenAuthDependency(default_jwk_configuration)
auth_tuple = await dependency(dummy_request(token1))
ensure_test_user_id_and_name(auth_tuple, token1)
auth_tuple = await dependency(dummy_request(token2))
ensure_test_user_id_and_name(auth_tuple, token2)
auth_tuple = await dependency(dummy_request(token3))
ensure_test_user_id_and_name(auth_tuple, token3)
async def test_multi_key_no_kid(
default_jwk_configuration: JwkConfiguration,
multi_key_signing_server: Any,
valid_tokens_no_kid: tuple[str, str, str],
) -> None:
"""Test with valid tokens from a multi-key set without a kid."""
_ = multi_key_signing_server
token1, token2, token3 = valid_tokens_no_kid
dependency = JwkTokenAuthDependency(default_jwk_configuration)
auth_tuple = await dependency(dummy_request(token1))
ensure_test_user_id_and_name(auth_tuple, token1)
# Token 2 should fail, as it has no kid and multiple keys for its algorithm are present
# and the one that signed it is not the first key
with pytest.raises(HTTPException) as exc_info:
await dependency(dummy_request(token2))
assert exc_info.value.status_code == 401
# Token 3 will succeed, as it has a different algorithm (RS384) and there's only one key
# for that algorithm in the multi-key set
auth_tuple = await dependency(dummy_request(token3))
ensure_test_user_id_and_name(auth_tuple, token3)