Debian Codegraph @

tests/test_algorithms.py

raw
1 import base64
2 import json
3 from typing import Union, cast
4
5 import pytest
6
7 from jwt.algorithms import HMACAlgorithm, NoneAlgorithm, has_crypto
8 from jwt.exceptions import InvalidKeyError
9 from jwt.utils import base64url_decode
10
11 from .keys import load_ec_pub_key_p_521, load_hmac_key, load_rsa_pub_key
12 from .utils import crypto_required, key_path
13
14 if has_crypto:
15 from cryptography.hazmat.primitives.asymmetric.ec import (
16 EllipticCurvePrivateKey,
17 EllipticCurvePublicKey,
18 )
19 from cryptography.hazmat.primitives.asymmetric.ed448 import (
20 Ed448PrivateKey,
21 Ed448PublicKey,
22 )
23 from cryptography.hazmat.primitives.asymmetric.ed25519 import (
24 Ed25519PrivateKey,
25 Ed25519PublicKey,
26 )
27 from cryptography.hazmat.primitives.asymmetric.rsa import (
28 RSAPrivateKey,
29 RSAPublicKey,
30 )
31
32 from jwt.algorithms import ECAlgorithm, OKPAlgorithm, RSAAlgorithm, RSAPSSAlgorithm
33
34
35 class TestAlgorithms:
36 def test_check_crypto_key_type_should_fail_when_not_using_crypto(self) -> None:
37 """If has_crypto is False, or if _crypto_key_types is None, then this method should throw."""
38
39 algo = NoneAlgorithm()
40 with pytest.raises(ValueError):
41 algo.check_crypto_key_type("key") # type: ignore[arg-type,unused-ignore]
42
43 def test_none_algorithm_should_throw_exception_if_key_is_not_none(self) -> None:
44 algo = NoneAlgorithm()
45
46 with pytest.raises(InvalidKeyError):
47 algo.prepare_key("123")
48
49 def test_none_algorithm_should_throw_exception_on_to_jwk(self) -> None:
50 algo = NoneAlgorithm()
51
52 with pytest.raises(NotImplementedError):
53 algo.to_jwk("dummy") # Using a dummy argument as is it not relevant
54
55 def test_none_algorithm_should_throw_exception_on_from_jwk(self) -> None:
56 algo = NoneAlgorithm()
57
58 with pytest.raises(NotImplementedError):
59 algo.from_jwk({}) # Using a dummy argument as is it not relevant
60
61 def test_hmac_should_reject_nonstring_key(self) -> None:
62 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
63
64 with pytest.raises(TypeError) as context:
65 algo.prepare_key(object()) # type: ignore[arg-type]
66
67 exception = context.value
68 assert str(exception) == "Expected a string value"
69
70 def test_hmac_should_accept_unicode_key(self) -> None:
71 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
72
73 algo.prepare_key("awesome")
74
75 @pytest.mark.parametrize(
76 "key",
77 [
78 "testkey2_rsa.pub.pem",
79 "testkey2_rsa.pub.pem",
80 "testkey_pkcs1.pub.pem",
81 "testkey_rsa.cer",
82 "testkey_rsa.pub",
83 ],
84 )
85 def test_hmac_should_throw_exception(self, key: str) -> None:
86 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
87
88 with pytest.raises(InvalidKeyError):
89 with open(key_path(key)) as keyfile:
90 algo.prepare_key(keyfile.read())
91
92 def test_hmac_jwk_should_parse_and_verify(self) -> None:
93 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
94
95 with open(key_path("jwk_hmac.json")) as keyfile:
96 key = algo.from_jwk(keyfile.read())
97
98 signature = algo.sign(b"Hello World!", key)
99 assert algo.verify(b"Hello World!", key, signature)
100
101 @pytest.mark.parametrize("as_dict", (False, True))
102 def test_hmac_to_jwk_returns_correct_values(self, as_dict: bool) -> None:
103 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
104 if as_dict:
105 key = algo.to_jwk("secret", as_dict=True)
106 else:
107 key = json.loads(algo.to_jwk("secret", as_dict=False))
108
109 assert key == {"kty": "oct", "k": "c2VjcmV0"}
110
111 def test_hmac_from_jwk_should_raise_exception_if_not_hmac_key(self) -> None:
112 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
113
114 with open(key_path("jwk_rsa_pub.json")) as keyfile:
115 with pytest.raises(InvalidKeyError):
116 algo.from_jwk(keyfile.read())
117
118 def test_hmac_from_jwk_should_raise_exception_if_empty_json(self) -> None:
119 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
120
121 with open(key_path("jwk_empty.json")) as keyfile:
122 with pytest.raises(InvalidKeyError):
123 algo.from_jwk(keyfile.read())
124
125 @pytest.mark.parametrize("empty_key", ["", b""])
126 def test_hmac_prepare_key_rejects_empty_key(
127 self, empty_key: Union[str, bytes]
128 ) -> None:
129 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
130
131 with pytest.raises(InvalidKeyError, match="must not be empty"):
132 algo.prepare_key(empty_key)
133
134 @pytest.mark.parametrize(
135 "jwk_file",
136 [
137 "jwk_rsa_pub.json",
138 "jwk_ec_pub_P-256.json",
139 "jwk_okp_pub_Ed25519.json",
140 "jwk_hmac.json",
141 ],
142 )
143 def test_hmac_prepare_key_rejects_jwk_json(self, jwk_file: str) -> None:
144 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
145
146 with open(key_path(jwk_file)) as keyfile:
147 with pytest.raises(InvalidKeyError, match="looks like a JWK"):
148 algo.prepare_key(keyfile.read())
149
150 def test_hmac_prepare_key_accepts_json_without_kty(self) -> None:
151 # JSON that doesn't look like a JWK (no "kty") should not be misclassified.
152 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
153
154 key = algo.prepare_key('{"this": "is just a json-shaped secret"}')
155 assert key == b'{"this": "is just a json-shaped secret"}'
156
157 @crypto_required
158 def test_rsa_should_parse_pem_public_key(self) -> None:
159 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
160
161 with open(key_path("testkey2_rsa.pub.pem")) as pem_key:
162 algo.prepare_key(pem_key.read())
163
164 @crypto_required
165 def test_rsa_should_accept_pem_private_key_bytes(self) -> None:
166 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
167
168 with open(key_path("testkey_rsa.priv"), "rb") as pem_key:
169 algo.prepare_key(pem_key.read())
170
171 @crypto_required
172 def test_rsa_should_accept_unicode_key(self) -> None:
173 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
174
175 with open(key_path("testkey_rsa.priv")) as rsa_key:
176 algo.prepare_key(rsa_key.read())
177
178 @crypto_required
179 def test_rsa_should_reject_non_string_key(self) -> None:
180 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
181
182 with pytest.raises(TypeError):
183 algo.prepare_key(None) # type: ignore[arg-type,unused-ignore]
184
185 @crypto_required
186 def test_rsa_verify_should_return_false_if_signature_invalid(self) -> None:
187 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
188
189 message = b"Hello World!"
190
191 sig = base64.b64decode(
192 b"yS6zk9DBkuGTtcBzLUzSpo9gGJxJFOGvUqN01iLhWHrzBQ9ZEz3+Ae38AXp"
193 b"10RWwscp42ySC85Z6zoN67yGkLNWnfmCZSEv+xqELGEvBJvciOKsrhiObUl"
194 b"2mveSc1oeO/2ujkGDkkkJ2epn0YliacVjZF5+/uDmImUfAAj8lzjnHlzYix"
195 b"sn5jGz1H07jYYbi9diixN8IUhXeTafwFg02IcONhum29V40Wu6O5tAKWlJX"
196 b"fHJnNUzAEUOXS0WahHVb57D30pcgIji9z923q90p5c7E2cU8V+E1qe8NdCA"
197 b"APCDzZZ9zQ/dgcMVaBrGrgimrcLbPjueOKFgSO+SSjIElKA=="
198 )
199
200 sig += b"123" # Signature is now invalid
201
202 with open(key_path("testkey_rsa.pub")) as keyfile:
203 pub_key = cast(RSAPublicKey, algo.prepare_key(keyfile.read()))
204
205 result = algo.verify(message, pub_key, sig)
206 assert not result
207
208 @crypto_required
209 def test_ec_jwk_public_and_private_keys_should_parse_and_verify(self) -> None:
210 tests = {
211 "P-256": ECAlgorithm.SHA256,
212 "P-384": ECAlgorithm.SHA384,
213 "P-521": ECAlgorithm.SHA512,
214 "secp256k1": ECAlgorithm.SHA256,
215 }
216 for curve, hash in tests.items():
217 algo = ECAlgorithm(hash)
218
219 with open(key_path(f"jwk_ec_pub_{curve}.json")) as keyfile:
220 pub_key = cast(EllipticCurvePublicKey, algo.from_jwk(keyfile.read()))
221
222 with open(key_path(f"jwk_ec_key_{curve}.json")) as keyfile:
223 priv_key = cast(EllipticCurvePrivateKey, algo.from_jwk(keyfile.read()))
224
225 signature = algo.sign(b"Hello World!", priv_key)
226 assert algo.verify(b"Hello World!", pub_key, signature)
227
228 @crypto_required
229 def test_ec_jwk_fails_on_invalid_json(self) -> None:
230 algo = ECAlgorithm(ECAlgorithm.SHA512)
231
232 valid_points = {
233 "P-256": {
234 "x": "PTTjIY84aLtaZCxLTrG_d8I0G6YKCV7lg8M4xkKfwQ4",
235 "y": "ank6KA34vv24HZLXlChVs85NEGlpg2sbqNmR_BcgyJU",
236 },
237 "P-384": {
238 "x": "IDC-5s6FERlbC4Nc_4JhKW8sd51AhixtMdNUtPxhRFP323QY6cwWeIA3leyZhz-J",
239 "y": "eovmN9ocANS8IJxDAGSuC1FehTq5ZFLJU7XSPg36zHpv4H2byKGEcCBiwT4sFJsy",
240 },
241 "P-521": {
242 "x": "AHKZLLOsCOzz5cY97ewNUajB957y-C-U88c3v13nmGZx6sYl_oJXu9A5RkTKqjqvjyekWF-7ytDyRXYgCF5cj0Kt",
243 "y": "AdymlHvOiLxXkEhayXQnNCvDX4h9htZaCJN34kfmC6pV5OhQHiraVySsUdaQkAgDPrwQrJmbnX9cwlGfP-HqHZR1",
244 },
245 "secp256k1": {
246 "x": "MLnVyPDPQpNm0KaaO4iEh0i8JItHXJE0NcIe8GK1SYs",
247 "y": "7r8d-xF7QAgT5kSRdly6M8xeg4Jz83Gs_CQPQRH65QI",
248 },
249 }
250
251 # Invalid JSON
252 with pytest.raises(InvalidKeyError):
253 algo.from_jwk("<this isn't json>")
254
255 # Bad key type
256 with pytest.raises(InvalidKeyError):
257 algo.from_jwk('{"kty": "RSA"}')
258
259 # Missing data
260 with pytest.raises(InvalidKeyError):
261 algo.from_jwk('{"kty": "EC"}')
262 with pytest.raises(InvalidKeyError):
263 algo.from_jwk('{"kty": "EC", "x": "1"}')
264 with pytest.raises(InvalidKeyError):
265 algo.from_jwk('{"kty": "EC", "y": "1"}')
266
267 # Missing curve
268 with pytest.raises(InvalidKeyError):
269 algo.from_jwk('{"kty": "EC", "x": "dGVzdA==", "y": "dGVzdA=="}')
270
271 # EC coordinates not equally long
272 with pytest.raises(InvalidKeyError):
273 algo.from_jwk('{"kty": "EC", "x": "dGVzdHRlc3Q=", "y": "dGVzdA=="}')
274
275 # EC coordinates length invalid
276 for curve in ("P-256", "P-384", "P-521", "secp256k1"):
277 with pytest.raises(InvalidKeyError):
278 algo.from_jwk(
279 f'{{"kty": "EC", "crv": "{curve}", "x": "dGVzdA==", "y": "dGVzdA=="}}'
280 )
281
282 # EC private key length invalid
283 for curve, point in valid_points.items():
284 with pytest.raises(InvalidKeyError):
285 algo.from_jwk(
286 f'{{"kty": "EC", "crv": "{curve}", "x": "{point["x"]}", "y": "{point["y"]}", "d": "dGVzdA=="}}'
287 )
288
289 @crypto_required
290 def test_ec_private_key_to_jwk_works_with_from_jwk(self) -> None:
291 algo = ECAlgorithm(ECAlgorithm.SHA256)
292
293 with open(key_path("testkey_ec.priv")) as ec_key:
294 orig_key = cast(EllipticCurvePrivateKey, algo.prepare_key(ec_key.read()))
295
296 parsed_key = cast(EllipticCurvePrivateKey, algo.from_jwk(algo.to_jwk(orig_key)))
297 assert parsed_key.private_numbers() == orig_key.private_numbers()
298 assert (
299 parsed_key.private_numbers().public_numbers
300 == orig_key.private_numbers().public_numbers
301 )
302
303 @crypto_required
304 def test_ec_public_key_to_jwk_works_with_from_jwk(self) -> None:
305 algo = ECAlgorithm(ECAlgorithm.SHA256)
306
307 with open(key_path("testkey_ec.pub")) as ec_key:
308 orig_key = cast(EllipticCurvePublicKey, algo.prepare_key(ec_key.read()))
309
310 parsed_key = cast(EllipticCurvePublicKey, algo.from_jwk(algo.to_jwk(orig_key)))
311 assert parsed_key.public_numbers() == orig_key.public_numbers()
312
313 @crypto_required
314 @pytest.mark.parametrize("as_dict", (False, True))
315 def test_ec_to_jwk_returns_correct_values_for_public_key(
316 self, as_dict: bool
317 ) -> None:
318 algo = ECAlgorithm(ECAlgorithm.SHA256)
319
320 with open(key_path("testkey_ec.pub")) as keyfile:
321 pub_key = algo.prepare_key(keyfile.read())
322
323 if as_dict:
324 key = algo.to_jwk(pub_key, as_dict=True)
325 else:
326 key = json.loads(algo.to_jwk(pub_key, as_dict=False))
327
328 expected = {
329 "kty": "EC",
330 "crv": "P-256",
331 "x": "HzAcUWSlGBHcuf3y3RiNrWI-pE6-dD2T7fIzg9t6wEc",
332 "y": "t2G02kbWiOqimYfQAfnARdp2CTycsJPhwA8rn1Cn0SQ",
333 }
334
335 assert key == expected
336
337 @crypto_required
338 @pytest.mark.parametrize("as_dict", (False, True))
339 def test_ec_to_jwk_returns_correct_values_for_private_key(
340 self, as_dict: bool
341 ) -> None:
342 algo = ECAlgorithm(ECAlgorithm.SHA256)
343
344 with open(key_path("testkey_ec.priv")) as keyfile:
345 priv_key = algo.prepare_key(keyfile.read())
346
347 if as_dict:
348 key = algo.to_jwk(priv_key, as_dict=True)
349 else:
350 key = json.loads(algo.to_jwk(priv_key, as_dict=False))
351
352 expected = {
353 "kty": "EC",
354 "crv": "P-256",
355 "x": "HzAcUWSlGBHcuf3y3RiNrWI-pE6-dD2T7fIzg9t6wEc",
356 "y": "t2G02kbWiOqimYfQAfnARdp2CTycsJPhwA8rn1Cn0SQ",
357 "d": "2nninfu2jMHDwAbn9oERUhRADS6duQaJEadybLaa0YQ",
358 }
359
360 assert key == expected
361
362 @crypto_required
363 def test_ec_to_jwk_raises_exception_on_invalid_key(self) -> None:
364 algo = ECAlgorithm(ECAlgorithm.SHA256)
365
366 with pytest.raises(InvalidKeyError):
367 # crypto-mypy reports call-overload; no-crypto-mypy reports
368 # unused-ignore because mypy resolves the argument type to Any.
369 algo.to_jwk({"not": "a valid key"}) # type: ignore[call-overload,unused-ignore]
370
371 @crypto_required
372 @pytest.mark.parametrize("as_dict", (False, True))
373 def test_ec_to_jwk_with_valid_curves(self, as_dict: bool) -> None:
374 tests = {
375 "P-256": ECAlgorithm.SHA256,
376 "P-384": ECAlgorithm.SHA384,
377 "P-521": ECAlgorithm.SHA512,
378 "secp256k1": ECAlgorithm.SHA256,
379 }
380 for curve, hash in tests.items():
381 algo = ECAlgorithm(hash)
382
383 with open(key_path(f"jwk_ec_pub_{curve}.json")) as keyfile:
384 pub_key = algo.from_jwk(keyfile.read())
385 if as_dict:
386 jwk = algo.to_jwk(pub_key, as_dict=True)
387 else:
388 jwk = json.loads(algo.to_jwk(pub_key, as_dict=False))
389
390 assert jwk["crv"] == curve
391
392 with open(key_path(f"jwk_ec_key_{curve}.json")) as keyfile:
393 priv_key = algo.from_jwk(keyfile.read())
394 if as_dict:
395 jwk = algo.to_jwk(priv_key, as_dict=True)
396 else:
397 jwk = json.loads(algo.to_jwk(priv_key, as_dict=False))
398
399 assert jwk["crv"] == curve
400
401 @crypto_required
402 def test_ec_to_jwk_with_invalid_curve(self) -> None:
403 algo = ECAlgorithm(ECAlgorithm.SHA256)
404
405 with open(key_path("testkey_ec_secp192r1.priv")) as keyfile:
406 priv_key = algo.prepare_key(keyfile.read())
407
408 with pytest.raises(InvalidKeyError):
409 algo.to_jwk(priv_key)
410
411 @crypto_required
412 def test_rsa_jwk_public_and_private_keys_should_parse_and_verify(self) -> None:
413 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
414
415 with open(key_path("jwk_rsa_pub.json")) as keyfile:
416 pub_key = cast(RSAPublicKey, algo.from_jwk(keyfile.read()))
417
418 with open(key_path("jwk_rsa_key.json")) as keyfile:
419 priv_key = cast(RSAPrivateKey, algo.from_jwk(keyfile.read()))
420
421 signature = algo.sign(b"Hello World!", priv_key)
422 assert algo.verify(b"Hello World!", pub_key, signature)
423
424 @crypto_required
425 def test_rsa_private_key_to_jwk_works_with_from_jwk(self) -> None:
426 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
427
428 with open(key_path("testkey_rsa.priv")) as rsa_key:
429 orig_key = cast(RSAPrivateKey, algo.prepare_key(rsa_key.read()))
430
431 parsed_key = cast(RSAPrivateKey, algo.from_jwk(algo.to_jwk(orig_key)))
432 assert parsed_key.private_numbers() == orig_key.private_numbers()
433 assert (
434 parsed_key.private_numbers().public_numbers
435 == orig_key.private_numbers().public_numbers
436 )
437
438 @crypto_required
439 def test_rsa_public_key_to_jwk_works_with_from_jwk(self) -> None:
440 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
441
442 with open(key_path("testkey_rsa.pub")) as rsa_key:
443 orig_key = cast(RSAPublicKey, algo.prepare_key(rsa_key.read()))
444
445 parsed_key = cast(RSAPublicKey, algo.from_jwk(algo.to_jwk(orig_key)))
446 assert parsed_key.public_numbers() == orig_key.public_numbers()
447
448 @crypto_required
449 def test_rsa_jwk_private_key_with_other_primes_is_invalid(self) -> None:
450 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
451
452 with open(key_path("jwk_rsa_key.json")) as keyfile:
453 with pytest.raises(InvalidKeyError):
454 keydata = json.loads(keyfile.read())
455 keydata["oth"] = []
456
457 algo.from_jwk(json.dumps(keydata))
458
459 @crypto_required
460 def test_rsa_jwk_private_key_with_missing_values_is_invalid(self) -> None:
461 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
462
463 with open(key_path("jwk_rsa_key.json")) as keyfile:
464 with pytest.raises(InvalidKeyError):
465 keydata = json.loads(keyfile.read())
466 del keydata["p"]
467
468 algo.from_jwk(json.dumps(keydata))
469
470 @crypto_required
471 def test_rsa_jwk_private_key_can_recover_prime_factors(self) -> None:
472 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
473
474 with open(key_path("jwk_rsa_key.json")) as keyfile:
475 keybytes = keyfile.read()
476 control_key = cast(RSAPrivateKey, algo.from_jwk(keybytes)).private_numbers()
477
478 keydata = json.loads(keybytes)
479 delete_these = ["p", "q", "dp", "dq", "qi"]
480 for field in delete_these:
481 del keydata[field]
482
483 parsed_key = cast(
484 RSAPrivateKey, algo.from_jwk(json.dumps(keydata))
485 ).private_numbers()
486
487 assert control_key.d == parsed_key.d
488 assert control_key.p == parsed_key.p
489 assert control_key.q == parsed_key.q
490 assert control_key.dmp1 == parsed_key.dmp1
491 assert control_key.dmq1 == parsed_key.dmq1
492 assert control_key.iqmp == parsed_key.iqmp
493
494 @crypto_required
495 def test_rsa_jwk_private_key_with_missing_required_values_is_invalid(self) -> None:
496 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
497
498 with open(key_path("jwk_rsa_key.json")) as keyfile:
499 with pytest.raises(InvalidKeyError):
500 keydata = json.loads(keyfile.read())
501 del keydata["p"]
502
503 algo.from_jwk(json.dumps(keydata))
504
505 @crypto_required
506 def test_rsa_jwk_raises_exception_if_not_a_valid_key(self) -> None:
507 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
508
509 # Invalid JSON
510 with pytest.raises(InvalidKeyError):
511 algo.from_jwk("{not-a-real-key")
512
513 # Missing key parts
514 with pytest.raises(InvalidKeyError):
515 algo.from_jwk('{"kty": "RSA"}')
516
517 @crypto_required
518 @pytest.mark.parametrize("as_dict", (False, True))
519 def test_rsa_to_jwk_returns_correct_values_for_public_key(
520 self, as_dict: bool
521 ) -> None:
522 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
523
524 with open(key_path("testkey_rsa.pub")) as keyfile:
525 pub_key = algo.prepare_key(keyfile.read())
526
527 if as_dict:
528 key = algo.to_jwk(pub_key, as_dict=True)
529 else:
530 key = json.loads(algo.to_jwk(pub_key, as_dict=False))
531
532 expected = {
533 "e": "AQAB",
534 "key_ops": ["verify"],
535 "kty": "RSA",
536 "n": (
537 "1HgzBfJv2cOjQryCwe8NEelriOTNFWKZUivevUrRhlqcmZJdCvuCJRr-xCN-"
538 "OmO8qwgJJR98feNujxVg-J9Ls3_UOA4HcF9nYH6aqVXELAE8Hk_ALvxi96ms"
539 "1DDuAvQGaYZ-lANxlvxeQFOZSbjkz_9mh8aLeGKwqJLp3p-OhUBQpwvAUAPg"
540 "82-OUtgTW3nSljjeFr14B8qAneGSc_wl0ni--1SRZUXFSovzcqQOkla3W27r"
541 "rLfrD6LXgj_TsDs4vD1PnIm1zcVenKT7TfYI17bsG_O_Wecwz2Nl19pL7gDo"
542 "sNruF3ogJWNq1Lyn_ijPQnkPLpZHyhvuiycYcI3DiQ"
543 ),
544 }
545 assert key == expected
546
547 @crypto_required
548 @pytest.mark.parametrize("as_dict", (False, True))
549 def test_rsa_to_jwk_returns_correct_values_for_private_key(
550 self, as_dict: bool
551 ) -> None:
552 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
553
554 with open(key_path("testkey_rsa.priv")) as keyfile:
555 priv_key = algo.prepare_key(keyfile.read())
556
557 if as_dict:
558 key = algo.to_jwk(priv_key, as_dict=True)
559 else:
560 key = json.loads(algo.to_jwk(priv_key, as_dict=False))
561
562 expected = {
563 "key_ops": ["sign"],
564 "kty": "RSA",
565 "e": "AQAB",
566 "n": (
567 "1HgzBfJv2cOjQryCwe8NEelriOTNFWKZUivevUrRhlqcmZJdCvuCJRr-xCN-"
568 "OmO8qwgJJR98feNujxVg-J9Ls3_UOA4HcF9nYH6aqVXELAE8Hk_ALvxi96ms"
569 "1DDuAvQGaYZ-lANxlvxeQFOZSbjkz_9mh8aLeGKwqJLp3p-OhUBQpwvAUAPg"
570 "82-OUtgTW3nSljjeFr14B8qAneGSc_wl0ni--1SRZUXFSovzcqQOkla3W27r"
571 "rLfrD6LXgj_TsDs4vD1PnIm1zcVenKT7TfYI17bsG_O_Wecwz2Nl19pL7gDo"
572 "sNruF3ogJWNq1Lyn_ijPQnkPLpZHyhvuiycYcI3DiQ"
573 ),
574 "d": (
575 "rfbs8AWdB1RkLJRlC51LukrAvYl5UfU1TE6XRa4o-DTg2-03OXLNEMyVpMr"
576 "a47weEnu14StypzC8qXL7vxXOyd30SSFTffLfleaTg-qxgMZSDw-Fb_M-pU"
577 "HMPMEDYG-lgGma4l4fd1yTX2ATtoUo9BVOQgWS1LMZqi0ASEOkUfzlBgL04"
578 "UoaLhPSuDdLygdlDzgruVPnec0t1uOEObmrcWIkhwU2CGQzeLtuzX6OVgPh"
579 "k7xcnjbDurTTVpWH0R0gbZ5ukmQ2P-YuCX8T9iWNMGjPNSkb7h02s2Oe9ZR"
580 "zP007xQ0VF-Z7xyLuxk6ASmoX1S39ujSbk2WF0eXNPRgFwQ"
581 ),
582 "q": (
583 "47hlW2f1ARuWYJf9Dl6MieXjdj2dGx9PL2UH0unVzJYInd56nqXNPrQrc5k"
584 "ZU65KApC9n9oKUwIxuqwAAbh8oGNEQDqnuTj-powCkdC6bwA8KH1Y-wotpq"
585 "_GSjxkNzjWRm2GArJSzZc6Fb8EuObOrAavKJ285-zMPCEfus1WZG0"
586 ),
587 "p": (
588 "7tr0z929Lp4OHIRJjIKM_rDrWMPtRgnV-51pgWsN6qdpDzns_PgFwrHcoyY"
589 "sWIO-4yCdVWPxFOgEZ8xXTM_uwOe4VEmdZhw55Tx7axYZtmZYZbO_RIP4CG"
590 "mlJlOFTiYnxpr-2Cx6kIeQmd-hf7fA3tL018aEzwYMbFMcnAGnEg0"
591 ),
592 "qi": (
593 "djo95mB0LVYikNPa-NgyDwLotLqrueb9IviMmn6zKHCwiOXReqXDX9slB8"
594 "RA15uv56bmN04O__NyVFcgJ2ef169GZHiRFIgIy0Pl8LYkMhCYKKhyqM7g"
595 "xN-SqGqDTKDC22j00S7jcvCaa1qadn1qbdfukZ4NXv7E2d_LO0Y2Kkc"
596 ),
597 "dp": (
598 "tgZ2-tJpEdWxu1m1EzeKa644LHVjpTRptk7H0LDc8i6SieADEuWQvkb9df"
599 "fpY6tDFaQNQr3fQ6dtdAztmsP7l1b_ynwvT1nDZUcqZvl4ruBgDWFmKbjI"
600 "lOCt0v9jX6MEPP5xqBx9axdkw18BnGtUuHrbzHSlUX-yh_rumpVH1SE"
601 ),
602 "dq": (
603 "xxCIuhD0YlWFbUcwFgGdBWcLIm_WCMGj7SB6aGu1VDTLr4Wu10TFWM0TNu"
604 "hc9YPker2gpj5qzAmdAzwcfWSSvXpJTYR43jfulBTMoj8-2o3wCM0anclW"
605 "AuKhin-kc4mh9ssDXRQZwlMymZP0QtaxUDw_nlfVrUCZgO7L1_ZsUTk"
606 ),
607 }
608 assert key == expected
609
610 @crypto_required
611 def test_rsa_to_jwk_raises_exception_on_invalid_key(self) -> None:
612 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
613
614 with pytest.raises(InvalidKeyError):
615 # crypto-mypy reports call-overload; no-crypto-mypy reports
616 # unused-ignore because mypy resolves the argument type to Any.
617 algo.to_jwk({"not": "a valid key"}) # type: ignore[call-overload,unused-ignore]
618
619 @crypto_required
620 def test_rsa_from_jwk_raises_exception_on_invalid_key(self) -> None:
621 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
622
623 with open(key_path("jwk_hmac.json")) as keyfile:
624 with pytest.raises(InvalidKeyError):
625 algo.from_jwk(keyfile.read())
626
627 @crypto_required
628 def test_ec_should_reject_non_string_key(self) -> None:
629 algo = ECAlgorithm(ECAlgorithm.SHA256)
630
631 with pytest.raises(TypeError):
632 algo.prepare_key(None) # type: ignore[arg-type,unused-ignore]
633
634 @crypto_required
635 def test_ec_should_accept_pem_private_key_bytes(self) -> None:
636 algo = ECAlgorithm(ECAlgorithm.SHA256)
637
638 with open(key_path("testkey_ec.priv"), "rb") as ec_key:
639 algo.prepare_key(ec_key.read())
640
641 @crypto_required
642 def test_ec_should_accept_ssh_public_key_bytes(self) -> None:
643 algo = ECAlgorithm(ECAlgorithm.SHA256)
644
645 with open(key_path("testkey_ec_ssh.pub")) as ec_key:
646 algo.prepare_key(ec_key.read())
647
648 @crypto_required
649 def test_ec_verify_should_return_false_if_signature_invalid(self) -> None:
650 algo = ECAlgorithm(ECAlgorithm.SHA256)
651
652 message = b"Hello World!"
653
654 # Mess up the signature by replacing a known byte
655 sig = base64.b64decode(
656 b"AC+m4Jf/xI3guAC6w0w37t5zRpSCF6F4udEz5LiMiTIjCS4vcVe6dDOxK+M"
657 b"mvkF8PxJuvqxP2CO3TR3okDPCl/NjATTO1jE+qBZ966CRQSSzcCM+tzcHzw"
658 b"LZS5kbvKu0Acd/K6Ol2/W3B1NeV5F/gjvZn/jOwaLgWEUYsg0o4XVrAg65".replace(
659 b"r", b"s"
660 )
661 )
662
663 with open(key_path("testkey_ec.pub")) as keyfile:
664 pub_key = algo.prepare_key(keyfile.read())
665
666 result = algo.verify(message, pub_key, sig)
667 assert not result
668
669 @crypto_required
670 def test_ec_verify_should_return_false_if_signature_wrong_length(self) -> None:
671 algo = ECAlgorithm(ECAlgorithm.SHA256)
672
673 message = b"Hello World!"
674
675 sig = base64.b64decode(b"AC+m4Jf/xI3guAC6w0w3")
676
677 with open(key_path("testkey_ec.pub")) as keyfile:
678 pub_key = algo.prepare_key(keyfile.read())
679
680 result = algo.verify(message, pub_key, sig)
681 assert not result
682
683 @crypto_required
684 def test_ec_should_throw_exception_on_wrong_key(self) -> None:
685 algo = ECAlgorithm(ECAlgorithm.SHA256)
686
687 with pytest.raises(InvalidKeyError):
688 with open(key_path("testkey_rsa.priv")) as keyfile:
689 algo.prepare_key(keyfile.read())
690
691 with pytest.raises(InvalidKeyError):
692 with open(key_path("testkey2_rsa.pub.pem")) as pem_key:
693 algo.prepare_key(pem_key.read())
694
695 @crypto_required
696 def test_rsa_pss_sign_then_verify_should_return_true(self) -> None:
697 algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256)
698
699 message = b"Hello World!"
700
701 with open(key_path("testkey_rsa.priv")) as keyfile:
702 priv_key = cast(RSAPrivateKey, algo.prepare_key(keyfile.read()))
703 sig = algo.sign(message, priv_key)
704
705 with open(key_path("testkey_rsa.pub")) as keyfile:
706 pub_key = cast(RSAPublicKey, algo.prepare_key(keyfile.read()))
707
708 result = algo.verify(message, pub_key, sig)
709 assert result
710
711 @crypto_required
712 def test_rsa_pss_verify_should_return_false_if_signature_invalid(self) -> None:
713 algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256)
714
715 jwt_message = b"Hello World!"
716
717 jwt_sig = base64.b64decode(
718 b"ywKAUGRIDC//6X+tjvZA96yEtMqpOrSppCNfYI7NKyon3P7doud5v65oWNu"
719 b"vQsz0fzPGfF7mQFGo9Cm9Vn0nljm4G6PtqZRbz5fXNQBH9k10gq34AtM02c"
720 b"/cveqACQ8gF3zxWh6qr9jVqIpeMEaEBIkvqG954E0HT9s9ybHShgHX9mlWk"
721 b"186/LopP4xe5c/hxOQjwhv6yDlTiwJFiqjNCvj0GyBKsc4iECLGIIO+4mC4"
722 b"daOCWqbpZDuLb1imKpmm8Nsm56kAxijMLZnpCcnPgyb7CqG+B93W9GHglA5"
723 b"drUeR1gRtO7vqbZMsCAQ4bpjXxwbYyjQlEVuMl73UL6sOWg=="
724 )
725
726 jwt_sig += b"123" # Signature is now invalid
727
728 with open(key_path("testkey_rsa.pub")) as keyfile:
729 jwt_pub_key = cast(RSAPublicKey, algo.prepare_key(keyfile.read()))
730
731 result = algo.verify(jwt_message, jwt_pub_key, jwt_sig)
732 assert not result
733
734
735 class TestAlgorithmsRFC7520:
736 """
737 These test vectors were taken from RFC 7520
738 (https://tools.ietf.org/html/rfc7520)
739 """
740
741 def test_hmac_verify_should_return_true_for_test_vector(self) -> None:
742 """
743 This test verifies that HMAC verification works with a known good
744 signature and key.
745
746 Reference: https://tools.ietf.org/html/rfc7520#section-4.4
747 """
748 signing_input = (
749 b"eyJhbGciOiJIUzI1NiIsImtpZCI6IjAxOGMwYWU1LTRkOWItNDcxYi1iZmQ2LWVlZ"
750 b"jMxNGJjNzAzNyJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ"
751 b"29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIG"
752 b"lmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmc"
753 b"gd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"
754 )
755
756 signature = base64url_decode(b"s0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0")
757
758 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
759 key = algo.prepare_key(load_hmac_key())
760
761 result = algo.verify(signing_input, key, signature)
762 assert result
763
764 @crypto_required
765 def test_rsa_verify_should_return_true_for_test_vector(self) -> None:
766 """
767 This test verifies that RSA PKCS v1.5 verification works with a known
768 good signature and key.
769
770 Reference: https://tools.ietf.org/html/rfc7520#section-4.1
771 """
772 signing_input = (
773 b"eyJhbGciOiJSUzI1NiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhb"
774 b"XBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb"
775 b"3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdS"
776 b"Bkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmU"
777 b"geW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"
778 )
779
780 signature = base64url_decode(
781 b"MRjdkly7_-oTPTS3AXP41iQIGKa80A0ZmTuV5MEaHoxnW2e5CZ5NlKtainoFmKZop"
782 b"dHM1O2U4mwzJdQx996ivp83xuglII7PNDi84wnB-BDkoBwA78185hX-Es4JIwmDLJ"
783 b"K3lfWRa-XtL0RnltuYv746iYTh_qHRD68BNt1uSNCrUCTJDt5aAE6x8wW1Kt9eRo4"
784 b"QPocSadnHXFxnt8Is9UzpERV0ePPQdLuW3IS_de3xyIrDaLGdjluPxUAhb6L2aXic"
785 b"1U12podGU0KLUQSE_oI-ZnmKJ3F4uOZDnd6QZWJushZ41Axf_fcIe8u9ipH84ogor"
786 b"ee7vjbU5y18kDquDg"
787 )
788
789 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
790 key = cast(RSAPublicKey, algo.prepare_key(load_rsa_pub_key()))
791
792 result = algo.verify(signing_input, key, signature)
793 assert result
794
795 @crypto_required
796 def test_rsapss_verify_should_return_true_for_test_vector(self) -> None:
797 """
798 This test verifies that RSA-PSS verification works with a known good
799 signature and key.
800
801 Reference: https://tools.ietf.org/html/rfc7520#section-4.2
802 """
803 signing_input = (
804 b"eyJhbGciOiJQUzM4NCIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhb"
805 b"XBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb"
806 b"3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdS"
807 b"Bkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmU"
808 b"geW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"
809 )
810
811 signature = base64url_decode(
812 b"cu22eBqkYDKgIlTpzDXGvaFfz6WGoz7fUDcfT0kkOy42miAh2qyBzk1xEsnk2IpN6"
813 b"-tPid6VrklHkqsGqDqHCdP6O8TTB5dDDItllVo6_1OLPpcbUrhiUSMxbbXUvdvWXz"
814 b"g-UD8biiReQFlfz28zGWVsdiNAUf8ZnyPEgVFn442ZdNqiVJRmBqrYRXe8P_ijQ7p"
815 b"8Vdz0TTrxUeT3lm8d9shnr2lfJT8ImUjvAA2Xez2Mlp8cBE5awDzT0qI0n6uiP1aC"
816 b"N_2_jLAeQTlqRHtfa64QQSUmFAAjVKPbByi7xho0uTOcbH510a6GYmJUAfmWjwZ6o"
817 b"D4ifKo8DYM-X72Eaw"
818 )
819
820 algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA384)
821 key = cast(RSAPublicKey, algo.prepare_key(load_rsa_pub_key()))
822
823 result = algo.verify(signing_input, key, signature)
824 assert result
825
826 @crypto_required
827 def test_ec_verify_should_return_true_for_test_vector(self) -> None:
828 """
829 This test verifies that ECDSA verification works with a known good
830 signature and key.
831
832 Reference: https://tools.ietf.org/html/rfc7520#section-4.3
833 """
834 signing_input = (
835 b"eyJhbGciOiJFUzUxMiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhb"
836 b"XBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb"
837 b"3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdS"
838 b"Bkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmU"
839 b"geW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"
840 )
841
842 signature = base64url_decode(
843 b"AE_R_YZCChjn4791jSQCrdPZCNYqHXCTZH0-JZGYNlaAjP2kqaluUIIUnC9qvbu9P"
844 b"lon7KRTzoNEuT4Va2cmL1eJAQy3mtPBu_u_sDDyYjnAMDxXPn7XrT0lw-kvAD890j"
845 b"l8e2puQens_IEKBpHABlsbEPX6sFY8OcGDqoRuBomu9xQ2"
846 )
847
848 algo = ECAlgorithm(ECAlgorithm.SHA512)
849 key = algo.prepare_key(load_ec_pub_key_p_521())
850
851 result = algo.verify(signing_input, key, signature)
852 assert result
853
854 # private key can also be used.
855 with open(key_path("jwk_ec_key_P-521.json")) as keyfile:
856 private_key = algo.from_jwk(keyfile.read())
857
858 result = algo.verify(signing_input, private_key, signature)
859 assert result
860
861
862 @crypto_required
863 class TestOKPAlgorithms:
864 hello_world_sig = b"Qxa47mk/azzUgmY2StAOguAd4P7YBLpyCfU3JdbaiWnXM4o4WibXwmIHvNYgN3frtE2fcyd8OYEaOiD/KiwkCg=="
865 hello_world_sig_pem = b"9ueQE7PT8uudHIQb2zZZ7tB7k1X3jeTnIfOVvGCINZejrqQbru1EXPeuMlGcQEZrGkLVcfMmr99W/+byxfppAg=="
866 hello_world = b"Hello World!"
867
868 def test_okp_ed25519_should_reject_non_string_key(self) -> None:
869 algo = OKPAlgorithm()
870
871 with pytest.raises(InvalidKeyError):
872 algo.prepare_key(None) # type: ignore[arg-type,unused-ignore]
873
874 with open(key_path("testkey_ed25519")) as keyfile:
875 algo.prepare_key(keyfile.read())
876
877 with open(key_path("testkey_ed25519.pub")) as keyfile:
878 algo.prepare_key(keyfile.read())
879
880 @pytest.mark.parametrize(
881 "private_key_file,public_key_file,sig_attr",
882 [
883 ("testkey_ed25519", "testkey_ed25519.pub", "hello_world_sig"),
884 ("testkey_ed25519.pem", "testkey_ed25519.pub.pem", "hello_world_sig_pem"),
885 ],
886 )
887 def test_okp_ed25519_sign_should_generate_correct_signature_value(
888 self, private_key_file: str, public_key_file: str, sig_attr: str
889 ) -> None:
890 algo = OKPAlgorithm()
891
892 jwt_message = self.hello_world
893
894 expected_sig = base64.b64decode(getattr(self, sig_attr))
895
896 with open(key_path(private_key_file)) as keyfile:
897 jwt_key = cast(Ed25519PrivateKey, algo.prepare_key(keyfile.read()))
898
899 with open(key_path(public_key_file)) as keyfile:
900 jwt_pub_key = cast(Ed25519PublicKey, algo.prepare_key(keyfile.read()))
901
902 algo.sign(jwt_message, jwt_key)
903 result = algo.verify(jwt_message, jwt_pub_key, expected_sig)
904 assert result
905
906 @pytest.mark.parametrize(
907 "public_key_file,sig_attr",
908 [
909 ("testkey_ed25519.pub", "hello_world_sig"),
910 ("testkey_ed25519.pub.pem", "hello_world_sig_pem"),
911 ],
912 )
913 def test_okp_ed25519_verify_should_return_false_if_signature_invalid(
914 self, public_key_file: str, sig_attr: str
915 ) -> None:
916 algo = OKPAlgorithm()
917
918 jwt_message = self.hello_world
919 jwt_sig = base64.b64decode(getattr(self, sig_attr))
920
921 jwt_sig += b"123" # Signature is now invalid
922
923 with open(key_path(public_key_file)) as keyfile:
924 jwt_pub_key = algo.prepare_key(keyfile.read())
925
926 result = algo.verify(jwt_message, jwt_pub_key, jwt_sig)
927 assert not result
928
929 @pytest.mark.parametrize(
930 "public_key_file,sig_attr",
931 [
932 ("testkey_ed25519.pub", "hello_world_sig"),
933 ("testkey_ed25519.pub.pem", "hello_world_sig_pem"),
934 ],
935 )
936 def test_okp_ed25519_verify_should_return_true_if_signature_valid(
937 self, public_key_file: str, sig_attr: str
938 ) -> None:
939 algo = OKPAlgorithm()
940
941 jwt_message = self.hello_world
942 jwt_sig = base64.b64decode(getattr(self, sig_attr))
943
944 with open(key_path(public_key_file)) as keyfile:
945 jwt_pub_key = algo.prepare_key(keyfile.read())
946
947 result = algo.verify(jwt_message, jwt_pub_key, jwt_sig)
948 assert result
949
950 @pytest.mark.parametrize(
951 "public_key_file", ("testkey_ed25519.pub", "testkey_ed25519.pub.pem")
952 )
953 def test_okp_ed25519_prepare_key_should_be_idempotent(
954 self, public_key_file: str
955 ) -> None:
956 algo = OKPAlgorithm()
957
958 with open(key_path(public_key_file)) as keyfile:
959 jwt_pub_key_first = algo.prepare_key(keyfile.read())
960 jwt_pub_key_second = algo.prepare_key(jwt_pub_key_first)
961
962 assert jwt_pub_key_first == jwt_pub_key_second
963
964 def test_okp_ed25519_prepare_key_should_reject_invalid_key(self) -> None:
965 algo = OKPAlgorithm()
966
967 with pytest.raises(InvalidKeyError):
968 algo.prepare_key("not a valid key")
969
970 def test_okp_ed25519_jwk_private_key_should_parse_and_verify(self) -> None:
971 algo = OKPAlgorithm()
972
973 with open(key_path("jwk_okp_key_Ed25519.json")) as keyfile:
974 key = cast(Ed25519PrivateKey, algo.from_jwk(keyfile.read()))
975
976 signature = algo.sign(b"Hello World!", key)
977 assert algo.verify(b"Hello World!", key.public_key(), signature)
978
979 def test_okp_ed25519_jwk_private_key_should_parse_and_verify_with_private_key_as_is(
980 self,
981 ) -> None:
982 algo = OKPAlgorithm()
983
984 with open(key_path("jwk_okp_key_Ed25519.json")) as keyfile:
985 key = cast(Ed25519PrivateKey, algo.from_jwk(keyfile.read()))
986
987 signature = algo.sign(b"Hello World!", key)
988 assert algo.verify(b"Hello World!", key, signature)
989
990 def test_okp_ed25519_jwk_public_key_should_parse_and_verify(self) -> None:
991 algo = OKPAlgorithm()
992
993 with open(key_path("jwk_okp_key_Ed25519.json")) as keyfile:
994 priv_key = cast(Ed25519PrivateKey, algo.from_jwk(keyfile.read()))
995
996 with open(key_path("jwk_okp_pub_Ed25519.json")) as keyfile:
997 pub_key = cast(Ed25519PublicKey, algo.from_jwk(keyfile.read()))
998
999 signature = algo.sign(b"Hello World!", priv_key)
1000 assert algo.verify(b"Hello World!", pub_key, signature)
1001
1002 def test_okp_ed25519_jwk_fails_on_invalid_json(self) -> None:
1003 algo = OKPAlgorithm()
1004
1005 with open(key_path("jwk_okp_pub_Ed25519.json")) as keyfile:
1006 valid_pub = json.loads(keyfile.read())
1007 with open(key_path("jwk_okp_key_Ed25519.json")) as keyfile:
1008 valid_key = json.loads(keyfile.read())
1009
1010 # Invalid instance type
1011 with pytest.raises(InvalidKeyError):
1012 algo.from_jwk(123) # type: ignore[arg-type]
1013
1014 # Invalid JSON
1015 with pytest.raises(InvalidKeyError):
1016 algo.from_jwk("<this isn't json>")
1017
1018 # Invalid kty, not "OKP"
1019 v = valid_pub.copy()
1020 v["kty"] = "oct"
1021 with pytest.raises(InvalidKeyError):
1022 algo.from_jwk(v)
1023
1024 # Invalid crv, not "Ed25519"
1025 v = valid_pub.copy()
1026 v["crv"] = "P-256"
1027 with pytest.raises(InvalidKeyError):
1028 algo.from_jwk(v)
1029
1030 # Invalid crv, "Ed448"
1031 v = valid_pub.copy()
1032 v["crv"] = "Ed448"
1033 with pytest.raises(InvalidKeyError):
1034 algo.from_jwk(v)
1035
1036 # Missing x
1037 v = valid_pub.copy()
1038 del v["x"]
1039 with pytest.raises(InvalidKeyError):
1040 algo.from_jwk(v)
1041
1042 # Invalid x
1043 v = valid_pub.copy()
1044 v["x"] = "123"
1045 with pytest.raises(InvalidKeyError):
1046 algo.from_jwk(v)
1047
1048 # Invalid d
1049 v = valid_key.copy()
1050 v["d"] = "123"
1051 with pytest.raises(InvalidKeyError):
1052 algo.from_jwk(v)
1053
1054 @pytest.mark.parametrize("as_dict", (False, True))
1055 def test_okp_ed25519_to_jwk_works_with_from_jwk(self, as_dict: bool) -> None:
1056 algo = OKPAlgorithm()
1057
1058 with open(key_path("jwk_okp_key_Ed25519.json")) as keyfile:
1059 priv_key_1 = cast(Ed25519PrivateKey, algo.from_jwk(keyfile.read()))
1060
1061 with open(key_path("jwk_okp_pub_Ed25519.json")) as keyfile:
1062 pub_key_1 = cast(Ed25519PublicKey, algo.from_jwk(keyfile.read()))
1063
1064 pub_jwk: Union[dict[str, object], str]
1065 pri_jwk: Union[dict[str, object], str]
1066 if as_dict:
1067 pub_jwk = algo.to_jwk(pub_key_1, as_dict=True)
1068 pri_jwk = algo.to_jwk(priv_key_1, as_dict=True)
1069 else:
1070 pub_jwk = algo.to_jwk(pub_key_1, as_dict=False)
1071 pri_jwk = algo.to_jwk(priv_key_1, as_dict=False)
1072 pub_key_2 = algo.from_jwk(pub_jwk)
1073 priv_key_2 = cast(Ed25519PrivateKey, algo.from_jwk(pri_jwk))
1074
1075 signature_1 = algo.sign(b"Hello World!", priv_key_1)
1076 signature_2 = algo.sign(b"Hello World!", priv_key_2)
1077 assert algo.verify(b"Hello World!", pub_key_2, signature_1)
1078 assert algo.verify(b"Hello World!", pub_key_2, signature_2)
1079
1080 def test_okp_to_jwk_raises_exception_on_invalid_key(self) -> None:
1081 algo = OKPAlgorithm()
1082
1083 with pytest.raises(InvalidKeyError):
1084 # crypto-mypy reports call-overload; no-crypto-mypy reports
1085 # unused-ignore because mypy resolves the argument type to Any.
1086 algo.to_jwk({"not": "a valid key"}) # type: ignore[call-overload,unused-ignore]
1087
1088 def test_okp_ed448_jwk_private_key_should_parse_and_verify(self) -> None:
1089 algo = OKPAlgorithm()
1090
1091 with open(key_path("jwk_okp_key_Ed448.json")) as keyfile:
1092 key = cast(Ed448PrivateKey, algo.from_jwk(keyfile.read()))
1093
1094 signature = algo.sign(b"Hello World!", key)
1095 assert algo.verify(b"Hello World!", key.public_key(), signature)
1096
1097 def test_okp_ed448_jwk_private_key_should_parse_and_verify_with_private_key_as_is(
1098 self,
1099 ) -> None:
1100 algo = OKPAlgorithm()
1101
1102 with open(key_path("jwk_okp_key_Ed448.json")) as keyfile:
1103 key = cast(Ed448PrivateKey, algo.from_jwk(keyfile.read()))
1104
1105 signature = algo.sign(b"Hello World!", key)
1106 assert algo.verify(b"Hello World!", key, signature)
1107
1108 def test_okp_ed448_jwk_public_key_should_parse_and_verify(self) -> None:
1109 algo = OKPAlgorithm()
1110
1111 with open(key_path("jwk_okp_key_Ed448.json")) as keyfile:
1112 priv_key = cast(Ed448PrivateKey, algo.from_jwk(keyfile.read()))
1113
1114 with open(key_path("jwk_okp_pub_Ed448.json")) as keyfile:
1115 pub_key = cast(Ed448PublicKey, algo.from_jwk(keyfile.read()))
1116
1117 signature = algo.sign(b"Hello World!", priv_key)
1118 assert algo.verify(b"Hello World!", pub_key, signature)
1119
1120 def test_okp_ed448_jwk_fails_on_invalid_json(self) -> None:
1121 algo = OKPAlgorithm()
1122
1123 with open(key_path("jwk_okp_pub_Ed448.json")) as keyfile:
1124 valid_pub = json.loads(keyfile.read())
1125 with open(key_path("jwk_okp_key_Ed448.json")) as keyfile:
1126 valid_key = json.loads(keyfile.read())
1127
1128 # Invalid instance type
1129 with pytest.raises(InvalidKeyError):
1130 algo.from_jwk(123) # type: ignore[arg-type]
1131
1132 # Invalid JSON
1133 with pytest.raises(InvalidKeyError):
1134 algo.from_jwk("<this isn't json>")
1135
1136 # Invalid kty, not "OKP"
1137 v = valid_pub.copy()
1138 v["kty"] = "oct"
1139 with pytest.raises(InvalidKeyError):
1140 algo.from_jwk(v)
1141
1142 # Invalid crv, not "Ed448"
1143 v = valid_pub.copy()
1144 v["crv"] = "P-256"
1145 with pytest.raises(InvalidKeyError):
1146 algo.from_jwk(v)
1147
1148 # Invalid crv, "Ed25519"
1149 v = valid_pub.copy()
1150 v["crv"] = "Ed25519"
1151 with pytest.raises(InvalidKeyError):
1152 algo.from_jwk(v)
1153
1154 # Missing x
1155 v = valid_pub.copy()
1156 del v["x"]
1157 with pytest.raises(InvalidKeyError):
1158 algo.from_jwk(v)
1159
1160 # Invalid x
1161 v = valid_pub.copy()
1162 v["x"] = "123"
1163 with pytest.raises(InvalidKeyError):
1164 algo.from_jwk(v)
1165
1166 # Invalid d
1167 v = valid_key.copy()
1168 v["d"] = "123"
1169 with pytest.raises(InvalidKeyError):
1170 algo.from_jwk(v)
1171
1172 @pytest.mark.parametrize("as_dict", (False, True))
1173 def test_okp_ed448_to_jwk_works_with_from_jwk(self, as_dict: bool) -> None:
1174 algo = OKPAlgorithm()
1175
1176 with open(key_path("jwk_okp_key_Ed448.json")) as keyfile:
1177 priv_key_1 = cast(Ed448PrivateKey, algo.from_jwk(keyfile.read()))
1178
1179 with open(key_path("jwk_okp_pub_Ed448.json")) as keyfile:
1180 pub_key_1 = cast(Ed448PublicKey, algo.from_jwk(keyfile.read()))
1181
1182 pub_jwk: Union[dict[str, object], str]
1183 pri_jwk: Union[dict[str, object], str]
1184 if as_dict:
1185 pub_jwk = algo.to_jwk(pub_key_1, as_dict=True)
1186 pri_jwk = algo.to_jwk(priv_key_1, as_dict=True)
1187 else:
1188 pub_jwk = algo.to_jwk(pub_key_1, as_dict=False)
1189 pri_jwk = algo.to_jwk(priv_key_1, as_dict=False)
1190 pub_key_2 = algo.from_jwk(pub_jwk)
1191 priv_key_2 = cast(Ed448PrivateKey, algo.from_jwk(pri_jwk))
1192
1193 signature_1 = algo.sign(b"Hello World!", priv_key_1)
1194 signature_2 = algo.sign(b"Hello World!", priv_key_2)
1195 assert algo.verify(b"Hello World!", pub_key_2, signature_1)
1196 assert algo.verify(b"Hello World!", pub_key_2, signature_2)
1197
1198 @crypto_required
1199 def test_rsa_can_compute_digest(self) -> None:
1200 # this is the well-known sha256 hash of "foo"
1201 foo_hash = base64.b64decode(b"LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564=")
1202
1203 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
1204 computed_hash = algo.compute_hash_digest(b"foo")
1205 assert computed_hash == foo_hash
1206
1207 def test_hmac_can_compute_digest(self) -> None:
1208 # this is the well-known sha256 hash of "foo"
1209 foo_hash = base64.b64decode(b"LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564=")
1210
1211 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
1212 computed_hash = algo.compute_hash_digest(b"foo")
1213 assert computed_hash == foo_hash
1214
1215 @crypto_required
1216 def test_rsa_prepare_key_raises_invalid_key_error_on_invalid_pem(self) -> None:
1217 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
1218 invalid_key = "invalid key"
1219
1220 with pytest.raises(InvalidKeyError) as excinfo:
1221 algo.prepare_key(invalid_key)
1222
1223 # Check that the exception message is correct
1224 assert "Could not parse the provided public key." in str(excinfo.value)
1225
1226
1227 @crypto_required
1228 class TestECCurveValidation:
1229 """Tests for ECDSA curve validation per RFC 7518 Section 3.4."""
1230
1231 def test_ec_curve_validation_rejects_wrong_curve_for_es256(self) -> None:
1232 """ES256 should reject keys that are not P-256."""
1233 from cryptography.hazmat.primitives.asymmetric.ec import SECP256R1
1234
1235 algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256R1)
1236
1237 # P-384 key should be rejected
1238 with open(key_path("jwk_ec_key_P-384.json")) as keyfile:
1239 p384_key = ECAlgorithm.from_jwk(keyfile.read())
1240
1241 with pytest.raises(InvalidKeyError) as excinfo:
1242 algo.prepare_key(p384_key)
1243 assert "secp384r1" in str(excinfo.value)
1244 assert "secp256r1" in str(excinfo.value)
1245
1246 def test_ec_curve_validation_rejects_wrong_curve_for_es384(self) -> None:
1247 """ES384 should reject keys that are not P-384."""
1248 from cryptography.hazmat.primitives.asymmetric.ec import SECP384R1
1249
1250 algo = ECAlgorithm(ECAlgorithm.SHA384, SECP384R1)
1251
1252 # P-256 key should be rejected
1253 with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
1254 p256_key = ECAlgorithm.from_jwk(keyfile.read())
1255
1256 with pytest.raises(InvalidKeyError) as excinfo:
1257 algo.prepare_key(p256_key)
1258 assert "secp256r1" in str(excinfo.value)
1259 assert "secp384r1" in str(excinfo.value)
1260
1261 def test_ec_curve_validation_rejects_wrong_curve_for_es512(self) -> None:
1262 """ES512 should reject keys that are not P-521."""
1263 from cryptography.hazmat.primitives.asymmetric.ec import SECP521R1
1264
1265 algo = ECAlgorithm(ECAlgorithm.SHA512, SECP521R1)
1266
1267 # P-256 key should be rejected
1268 with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
1269 p256_key = ECAlgorithm.from_jwk(keyfile.read())
1270
1271 with pytest.raises(InvalidKeyError) as excinfo:
1272 algo.prepare_key(p256_key)
1273 assert "secp256r1" in str(excinfo.value)
1274 assert "secp521r1" in str(excinfo.value)
1275
1276 def test_ec_curve_validation_rejects_wrong_curve_for_es256k(self) -> None:
1277 """ES256K should reject keys that are not secp256k1."""
1278 from cryptography.hazmat.primitives.asymmetric.ec import SECP256K1
1279
1280 algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256K1)
1281
1282 # P-256 key should be rejected
1283 with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
1284 p256_key = ECAlgorithm.from_jwk(keyfile.read())
1285
1286 with pytest.raises(InvalidKeyError) as excinfo:
1287 algo.prepare_key(p256_key)
1288 assert "secp256r1" in str(excinfo.value)
1289 assert "secp256k1" in str(excinfo.value)
1290
1291 def test_ec_curve_validation_accepts_correct_curve_for_es256(self) -> None:
1292 """ES256 should accept P-256 keys."""
1293 from cryptography.hazmat.primitives.asymmetric.ec import SECP256R1
1294
1295 algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256R1)
1296
1297 with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
1298 key = algo.from_jwk(keyfile.read())
1299 prepared = algo.prepare_key(key)
1300 assert prepared is key
1301
1302 def test_ec_curve_validation_accepts_correct_curve_for_es384(self) -> None:
1303 """ES384 should accept P-384 keys."""
1304 from cryptography.hazmat.primitives.asymmetric.ec import SECP384R1
1305
1306 algo = ECAlgorithm(ECAlgorithm.SHA384, SECP384R1)
1307
1308 with open(key_path("jwk_ec_key_P-384.json")) as keyfile:
1309 key = algo.from_jwk(keyfile.read())
1310 prepared = algo.prepare_key(key)
1311 assert prepared is key
1312
1313 def test_ec_curve_validation_accepts_correct_curve_for_es512(self) -> None:
1314 """ES512 should accept P-521 keys."""
1315 from cryptography.hazmat.primitives.asymmetric.ec import SECP521R1
1316
1317 algo = ECAlgorithm(ECAlgorithm.SHA512, SECP521R1)
1318
1319 with open(key_path("jwk_ec_key_P-521.json")) as keyfile:
1320 key = algo.from_jwk(keyfile.read())
1321 prepared = algo.prepare_key(key)
1322 assert prepared is key
1323
1324 def test_ec_curve_validation_accepts_correct_curve_for_es256k(self) -> None:
1325 """ES256K should accept secp256k1 keys."""
1326 from cryptography.hazmat.primitives.asymmetric.ec import SECP256K1
1327
1328 algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256K1)
1329
1330 with open(key_path("jwk_ec_key_secp256k1.json")) as keyfile:
1331 key = algo.from_jwk(keyfile.read())
1332 prepared = algo.prepare_key(key)
1333 assert prepared is key
1334
1335 def test_ec_curve_validation_rejects_p192_for_es256(self) -> None:
1336 """ES256 should reject P-192 keys (weaker than P-256)."""
1337 from cryptography.hazmat.primitives.asymmetric.ec import SECP256R1
1338
1339 algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256R1)
1340
1341 with open(key_path("testkey_ec_secp192r1.priv")) as keyfile:
1342 with pytest.raises(InvalidKeyError) as excinfo:
1343 algo.prepare_key(keyfile.read())
1344 assert "secp192r1" in str(excinfo.value)
1345 assert "secp256r1" in str(excinfo.value)
1346
1347 def test_ec_algorithm_without_expected_curve_accepts_any_curve(self) -> None:
1348 """ECAlgorithm without expected_curve should accept any curve (backwards compat)."""
1349 algo = ECAlgorithm(ECAlgorithm.SHA256)
1350
1351 # Should accept P-256
1352 with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
1353 p256_key = algo.from_jwk(keyfile.read())
1354 algo.prepare_key(p256_key)
1355
1356 # Should accept P-384
1357 with open(key_path("jwk_ec_key_P-384.json")) as keyfile:
1358 p384_key = algo.from_jwk(keyfile.read())
1359 algo.prepare_key(p384_key)
1360
1361 # Should accept P-521
1362 with open(key_path("jwk_ec_key_P-521.json")) as keyfile:
1363 p521_key = algo.from_jwk(keyfile.read())
1364 algo.prepare_key(p521_key)
1365
1366 # Should accept secp256k1
1367 with open(key_path("jwk_ec_key_secp256k1.json")) as keyfile:
1368 secp256k1_key = algo.from_jwk(keyfile.read())
1369 algo.prepare_key(secp256k1_key)
1370
1371 def test_default_algorithms_have_correct_expected_curve(self) -> None:
1372 """Default algorithms returned by get_default_algorithms should have expected_curve set."""
1373 from cryptography.hazmat.primitives.asymmetric.ec import (
1374 SECP256K1,
1375 SECP256R1,
1376 SECP384R1,
1377 SECP521R1,
1378 )
1379
1380 from jwt.algorithms import get_default_algorithms
1381
1382 algorithms = get_default_algorithms()
1383
1384 es256 = algorithms["ES256"]
1385 assert isinstance(es256, ECAlgorithm)
1386 assert es256.expected_curve == SECP256R1
1387
1388 es256k = algorithms["ES256K"]
1389 assert isinstance(es256k, ECAlgorithm)
1390 assert es256k.expected_curve == SECP256K1
1391
1392 es384 = algorithms["ES384"]
1393 assert isinstance(es384, ECAlgorithm)
1394 assert es384.expected_curve == SECP384R1
1395
1396 es521 = algorithms["ES521"]
1397 assert isinstance(es521, ECAlgorithm)
1398 assert es521.expected_curve == SECP521R1
1399
1400 es512 = algorithms["ES512"]
1401 assert isinstance(es512, ECAlgorithm)
1402 assert es512.expected_curve == SECP521R1
1403
1404 def test_ec_curve_validation_with_pem_key(self) -> None:
1405 """Curve validation should work with PEM-formatted keys."""
1406 from cryptography.hazmat.primitives.asymmetric.ec import SECP256R1
1407
1408 algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256R1)
1409
1410 # P-256 PEM key should be accepted
1411 with open(key_path("testkey_ec.priv")) as keyfile:
1412 algo.prepare_key(keyfile.read())
1413
1414 # P-192 PEM key should be rejected
1415 with open(key_path("testkey_ec_secp192r1.priv")) as keyfile:
1416 with pytest.raises(InvalidKeyError):
1417 algo.prepare_key(keyfile.read())
1418
1419 def test_jwt_encode_decode_rejects_wrong_curve(self) -> None:
1420 """Integration test: jwt.encode/decode should reject wrong curve keys."""
1421 import jwt
1422
1423 # Use P-384 key with ES256 algorithm (expects P-256)
1424 with open(key_path("jwk_ec_key_P-384.json")) as keyfile:
1425 p384_key = ECAlgorithm.from_jwk(keyfile.read())
1426
1427 assert isinstance(p384_key, EllipticCurvePrivateKey)
1428
1429 # Encoding should fail
1430 with pytest.raises(InvalidKeyError):
1431 jwt.encode({"hello": "world"}, p384_key, algorithm="ES256")
1432
1433 # Create a valid token with P-256 key
1434 with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
1435 p256_key = ECAlgorithm.from_jwk(keyfile.read())
1436
1437 assert isinstance(p256_key, EllipticCurvePrivateKey)
1438
1439 token = jwt.encode({"hello": "world"}, p256_key, algorithm="ES256")
1440
1441 # Decoding with wrong curve key should fail
1442 with open(key_path("jwk_ec_pub_P-384.json")) as keyfile:
1443 p384_pub_key = ECAlgorithm.from_jwk(keyfile.read())
1444
1445 assert isinstance(p384_pub_key, EllipticCurvePublicKey)
1446
1447 with pytest.raises(InvalidKeyError):
1448 jwt.decode(token, p384_pub_key, algorithms=["ES256"])
1449
1450 # Decoding with correct curve key should succeed
1451 with open(key_path("jwk_ec_pub_P-256.json")) as keyfile:
1452 p256_pub_key = ECAlgorithm.from_jwk(keyfile.read())
1453
1454 assert isinstance(p256_pub_key, EllipticCurvePublicKey)
1455
1456 decoded = jwt.decode(token, p256_pub_key, algorithms=["ES256"])
1457 assert decoded == {"hello": "world"}
1458
1459
1460 class TestKeyLengthValidation:
1461 """Tests for minimum key length validation (CWE-326)."""
1462
1463 # --- HMAC tests ---
1464
1465 def test_hmac_short_key_warns_by_default_hs256(self) -> None:
1466 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
1467 key = algo.prepare_key(b"short")
1468 msg = algo.check_key_length(key)
1469 assert msg is not None
1470 assert "below" in msg
1471 assert "32" in msg
1472
1473 def test_hmac_short_key_warns_by_default_hs384(self) -> None:
1474 algo = HMACAlgorithm(HMACAlgorithm.SHA384)
1475 key = algo.prepare_key(b"a" * 47)
1476 msg = algo.check_key_length(key)
1477 assert msg is not None
1478 assert "48" in msg
1479
1480 def test_hmac_short_key_warns_by_default_hs512(self) -> None:
1481 algo = HMACAlgorithm(HMACAlgorithm.SHA512)
1482 key = algo.prepare_key(b"a" * 63)
1483 msg = algo.check_key_length(key)
1484 assert msg is not None
1485 assert "64" in msg
1486
1487 def test_hmac_empty_key_rejected_outright(self) -> None:
1488 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
1489 with pytest.raises(InvalidKeyError, match="must not be empty"):
1490 algo.prepare_key(b"")
1491
1492 def test_hmac_exact_minimum_no_warning(self) -> None:
1493 algo = HMACAlgorithm(HMACAlgorithm.SHA256)
1494 key = algo.prepare_key(b"a" * 32)
1495 assert algo.check_key_length(key) is None
1496
1497 def test_hmac_above_minimum_no_warning(self) -> None:
1498 algo = HMACAlgorithm(HMACAlgorithm.SHA512)
1499 key = algo.prepare_key(b"a" * 128)
1500 assert algo.check_key_length(key) is None
1501
1502 def test_hmac_exact_minimum_hs384(self) -> None:
1503 algo = HMACAlgorithm(HMACAlgorithm.SHA384)
1504 key = algo.prepare_key(b"a" * 48)
1505 assert algo.check_key_length(key) is None
1506
1507 def test_hmac_exact_minimum_hs512(self) -> None:
1508 algo = HMACAlgorithm(HMACAlgorithm.SHA512)
1509 key = algo.prepare_key(b"a" * 64)
1510 assert algo.check_key_length(key) is None
1511
1512 # --- RSA tests ---
1513
1514 @crypto_required
1515 def test_rsa_small_key_returns_warning_message(self) -> None:
1516 from cryptography.hazmat.primitives.asymmetric import rsa as rsa_module
1517
1518 small_key = rsa_module.generate_private_key(
1519 public_exponent=65537,
1520 key_size=1024,
1521 )
1522 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
1523 msg = algo.check_key_length(small_key)
1524 assert msg is not None
1525 assert "1024" in msg
1526 assert "2048" in msg
1527
1528 @crypto_required
1529 def test_rsa_small_public_key_returns_warning_message(self) -> None:
1530 from cryptography.hazmat.primitives.asymmetric import rsa as rsa_module
1531
1532 small_key = rsa_module.generate_private_key(
1533 public_exponent=65537,
1534 key_size=1024,
1535 )
1536 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
1537 msg = algo.check_key_length(small_key.public_key())
1538 assert msg is not None
1539
1540 @crypto_required
1541 def test_rsa_2048_key_no_warning(self) -> None:
1542 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
1543 with open(key_path("testkey_rsa.priv")) as f:
1544 key = algo.prepare_key(f.read())
1545 assert algo.check_key_length(key) is None
1546
1547 @crypto_required
1548 def test_rsa_pss_inherits_validation(self) -> None:
1549 from cryptography.hazmat.primitives.asymmetric import rsa as rsa_module
1550
1551 small_key = rsa_module.generate_private_key(
1552 public_exponent=65537,
1553 key_size=1024,
1554 )
1555 algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256)
1556 msg = algo.check_key_length(small_key)
1557 assert msg is not None
1558
1559 @crypto_required
1560 def test_rsa_pem_weak_key_validated(self) -> None:
1561 from cryptography.hazmat.primitives.asymmetric import rsa as rsa_module
1562 from cryptography.hazmat.primitives.serialization import (
1563 Encoding,
1564 NoEncryption,
1565 PrivateFormat,
1566 )
1567
1568 small_key = rsa_module.generate_private_key(
1569 public_exponent=65537,
1570 key_size=1024,
1571 )
1572 pem = small_key.private_bytes(
1573 Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()
1574 )
1575 algo = RSAAlgorithm(RSAAlgorithm.SHA256)
1576 prepared = algo.prepare_key(pem)
1577 msg = algo.check_key_length(prepared)
1578 assert msg is not None
1579
1580 # --- PyJWS integration tests ---
1581
1582 def test_pyjws_encode_warns_short_hmac_key(self) -> None:
1583 import jwt
1584
1585 jws = jwt.PyJWS()
1586 with pytest.warns(jwt.InsecureKeyLengthWarning, match="below"):
1587 jws.encode(b'{"test":"payload"}', b"short", algorithm="HS256")
1588
1589 def test_pyjws_encode_enforces_short_hmac_key(self) -> None:
1590 import jwt
1591
1592 jws = jwt.PyJWS(options={"enforce_minimum_key_length": True})
1593 with pytest.raises(InvalidKeyError, match="below"):
1594 jws.encode(b'{"test":"payload"}', b"short", algorithm="HS256")
1595
1596 def test_pyjws_encode_no_warning_adequate_key(self) -> None:
1597 import warnings
1598
1599 import jwt
1600
1601 jws = jwt.PyJWS()
1602 with warnings.catch_warnings():
1603 warnings.simplefilter("error", jwt.InsecureKeyLengthWarning)
1604 jws.encode(b'{"test":"payload"}', b"a" * 32, algorithm="HS256")
1605
1606 # --- PyJWT integration tests ---
1607
1608 def test_pyjwt_encode_warns_short_hmac_key(self) -> None:
1609 import jwt
1610
1611 with pytest.warns(jwt.InsecureKeyLengthWarning):
1612 jwt.encode({"hello": "world"}, "short", algorithm="HS256")
1613
1614 def test_pyjwt_encode_enforces_short_hmac_key(self) -> None:
1615 import jwt
1616
1617 pyjwt = jwt.PyJWT(options={"enforce_minimum_key_length": True})
1618 with pytest.raises(InvalidKeyError, match="below"):
1619 pyjwt.encode({"hello": "world"}, "short", algorithm="HS256")
1620
1621 def test_pyjwt_decode_enforces_short_hmac_key(self) -> None:
1622 import jwt
1623
1624 adequate_key = "a" * 32
1625 token = jwt.encode({"hello": "world"}, adequate_key, algorithm="HS256")
1626
1627 pyjwt = jwt.PyJWT(options={"enforce_minimum_key_length": True})
1628 # Decoding with adequate key should work
1629 result = pyjwt.decode(token, adequate_key, algorithms=["HS256"])
1630 assert result == {"hello": "world"}
1631
1632 # Decoding with short key should raise
1633 pyjwt_enforce = jwt.PyJWT(options={"enforce_minimum_key_length": True})
1634 with pytest.raises(InvalidKeyError):
1635 pyjwt_enforce.decode(token, "short", algorithms=["HS256"])
1636
1637 def test_pyjwt_decode_honors_per_call_enforce_minimum_key_length(self) -> None:
1638 # Regression: per-call options passed to PyJWT.decode() must be
1639 # forwarded to the JWS verification layer. enforce_minimum_key_length
1640 # was previously dropped between PyJWT.decode_complete and
1641 # PyJWS._verify_signature.
1642 import jwt
1643
1644 adequate_key = "a" * 32
1645 token = jwt.encode({"hello": "world"}, adequate_key, algorithm="HS256")
1646
1647 # Module-level singleton path with per-call enforcement.
1648 with pytest.raises(InvalidKeyError, match="below"):
1649 jwt.decode(
1650 token,
1651 "short",
1652 algorithms=["HS256"],
1653 options={"enforce_minimum_key_length": True},
1654 )
1655
1656 # PyJWT() instance path (instance default off, per-call on).
1657 pyjwt = jwt.PyJWT()
1658 with pytest.raises(InvalidKeyError, match="below"):
1659 pyjwt.decode(
1660 token,
1661 "short",
1662 algorithms=["HS256"],
1663 options={"enforce_minimum_key_length": True},
1664 )
1665
1666 def test_pyjwt_encode_no_warning_adequate_key(self) -> None:
1667 import warnings
1668
1669 import jwt
1670
1671 with warnings.catch_warnings():
1672 warnings.simplefilter("error", jwt.InsecureKeyLengthWarning)
1673 jwt.encode({"hello": "world"}, "a" * 32, algorithm="HS256")
1674
1675 def test_global_register_algorithm_works_with_encode(self) -> None:
1676 """Backward compat: jwt.register_algorithm + jwt.encode use the same JWS."""
1677 import jwt
1678
1679 # This test just verifies the global path still works
1680 # (register_algorithm and encode share the same JWS instance)
1681 token = jwt.encode({"hello": "world"}, "a" * 32, algorithm="HS256")
1682 decoded = jwt.decode(token, "a" * 32, algorithms=["HS256"])
1683 assert decoded == {"hello": "world"}