Debian Codegraph @

tests/test_algorithms.py

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