Debian Codegraph @

tests/test_api_jws.py

raw
1 import json
2 from decimal import Decimal
3
4 import pytest
5
6 from jwt.algorithms import NoneAlgorithm, has_crypto
7 from jwt.api_jwk import PyJWK
8 from jwt.api_jws import PyJWS
9 from jwt.exceptions import (
10 DecodeError,
11 InvalidAlgorithmError,
12 InvalidKeyError,
13 InvalidSignatureError,
14 InvalidTokenError,
15 )
16 from jwt.utils import base64url_decode, base64url_encode
17 from jwt.warnings import RemovedInPyjwt3Warning
18
19 from .utils import crypto_required, key_path, no_crypto_required
20
21 try:
22 from cryptography.hazmat.primitives.serialization import (
23 load_pem_private_key,
24 load_pem_public_key,
25 load_ssh_public_key,
26 )
27 from cryptography.hazmat.primitives.asymmetric.ec import (
28 EllipticCurvePrivateKey,
29 EllipticCurvePublicKey,
30 )
31 from cryptography.hazmat.primitives.asymmetric.rsa import (
32 RSAPrivateKey,
33 RSAPublicKey,
34 )
35 except ModuleNotFoundError:
36 pass
37
38
39 @pytest.fixture
40 def jws() -> PyJWS:
41 return PyJWS()
42
43
44 @pytest.fixture
45 def payload() -> bytes:
46 """Creates a sample jws claimset for use as a payload during tests"""
47 return b"hello world"
48
49
50 class TestJWS:
51 def test_register_algo_does_not_allow_duplicate_registration(
52 self, jws: PyJWS
53 ) -> None:
54 jws.register_algorithm("AAA", NoneAlgorithm())
55
56 with pytest.raises(ValueError):
57 jws.register_algorithm("AAA", NoneAlgorithm())
58
59 def test_register_algo_rejects_non_algorithm_obj(self, jws: PyJWS) -> None:
60 with pytest.raises(TypeError):
61 jws.register_algorithm(
62 "AAA123",
63 {}, # type: ignore[arg-type]
64 )
65
66 def test_unregister_algo_removes_algorithm(self, jws: PyJWS) -> None:
67 supported = jws.get_algorithms()
68 assert "none" in supported
69 assert "HS256" in supported
70
71 jws.unregister_algorithm("HS256")
72
73 supported = jws.get_algorithms()
74 assert "HS256" not in supported
75
76 def test_unregister_algo_throws_error_if_not_registered(self, jws: PyJWS) -> None:
77 with pytest.raises(KeyError):
78 jws.unregister_algorithm("AAA")
79
80 def test_algo_parameter_removes_alg_from_algorithms_list(self, jws: PyJWS) -> None:
81 assert "none" in jws.get_algorithms()
82 assert "HS256" in jws.get_algorithms()
83
84 jws = PyJWS(algorithms=["HS256"])
85 assert "none" not in jws.get_algorithms()
86 assert "HS256" in jws.get_algorithms()
87
88 def test_override_options(self) -> None:
89 jws = PyJWS(options={"verify_signature": False})
90
91 assert not jws.options["verify_signature"]
92
93 def test_non_object_options_dont_persist(self, jws: PyJWS, payload: bytes) -> None:
94 token = jws.encode(payload, "secret")
95
96 jws.decode(token, "secret", options={"verify_signature": False})
97
98 assert jws.options["verify_signature"]
99
100 def test_options_must_be_dict(self) -> None:
101 pytest.raises(TypeError, PyJWS, options=object())
102 pytest.raises((TypeError, ValueError), PyJWS, options=("something"))
103
104 def test_encode_decode(self, jws: PyJWS, payload: bytes) -> None:
105 secret = "secret"
106 jws_message = jws.encode(payload, secret, algorithm="HS256")
107 decoded_payload = jws.decode(jws_message, secret, algorithms=["HS256"])
108
109 assert decoded_payload == payload
110
111 def test_decode_fails_when_alg_is_not_on_method_algorithms_param(
112 self, jws: PyJWS, payload: bytes
113 ) -> None:
114 secret = "secret"
115 jws_token = jws.encode(payload, secret, algorithm="HS256")
116 jws.decode(jws_token, secret, algorithms=["HS256"])
117
118 with pytest.raises(InvalidAlgorithmError):
119 jws.decode(jws_token, secret, algorithms=["HS384"])
120
121 def test_decode_works_with_unicode_token(self, jws: PyJWS) -> None:
122 secret = "secret"
123 unicode_jws = (
124 "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
125 ".eyJoZWxsbyI6ICJ3b3JsZCJ9"
126 ".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
127 )
128
129 jws.decode(unicode_jws, secret, algorithms=["HS256"])
130
131 def test_decode_missing_segments_throws_exception(self, jws: PyJWS) -> None:
132 secret = "secret"
133 example_jws = "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJoZWxsbyI6ICJ3b3JsZCJ9" # Missing segment
134
135 with pytest.raises(DecodeError) as context:
136 jws.decode(example_jws, secret, algorithms=["HS256"])
137
138 exception = context.value
139 assert str(exception) == "Not enough segments"
140
141 def test_decode_invalid_token_type_is_none(self, jws: PyJWS) -> None:
142 example_jws = None
143 example_secret = "secret"
144
145 with pytest.raises(DecodeError) as context:
146 jws.decode(
147 example_jws, # type: ignore[arg-type]
148 example_secret,
149 algorithms=["HS256"],
150 )
151
152 exception = context.value
153 assert "Invalid token type" in str(exception)
154
155 def test_decode_invalid_token_type_is_int(self, jws: PyJWS) -> None:
156 example_jws = 123
157 example_secret = "secret"
158
159 with pytest.raises(DecodeError) as context:
160 jws.decode(
161 example_jws, # type: ignore[arg-type]
162 example_secret,
163 algorithms=["HS256"],
164 )
165
166 exception = context.value
167 assert "Invalid token type" in str(exception)
168
169 def test_decode_with_non_mapping_header_throws_exception(self, jws: PyJWS) -> None:
170 secret = "secret"
171 example_jws = (
172 "MQ" # == 1
173 ".eyJoZWxsbyI6ICJ3b3JsZCJ9"
174 ".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
175 )
176
177 with pytest.raises(DecodeError) as context:
178 jws.decode(example_jws, secret, algorithms=["HS256"])
179
180 exception = context.value
181 assert str(exception) == "Invalid header string: must be a json object"
182
183 def test_encode_default_algorithm(self, jws: PyJWS, payload: bytes) -> None:
184 msg = jws.encode(payload, "secret")
185 decoded = jws.decode_complete(msg, "secret", algorithms=["HS256"])
186 assert decoded == {
187 "header": {"alg": "HS256", "typ": "JWT"},
188 "payload": payload,
189 "signature": (
190 b"H\x8a\xf4\xdf3:\xe1\xac\x16E\xd3\xeb\x00\xcf\xfa\xd5\x05\xac"
191 b"e\xc8@\xb6\x00\xd5\xde\x9aa|s\xcfZB"
192 ),
193 }
194
195 def test_encode_algorithm_param_should_be_case_sensitive(
196 self, jws: PyJWS, payload: bytes
197 ) -> None:
198 jws.encode(payload, "secret", algorithm="HS256")
199
200 with pytest.raises(NotImplementedError) as context:
201 jws.encode(payload, "none", algorithm="hs256")
202
203 exception = context.value
204 assert str(exception) == "Algorithm not supported"
205
206 def test_encode_with_headers_alg_none(self, jws: PyJWS, payload: bytes) -> None:
207 msg = jws.encode(
208 payload,
209 # The type signature does not capture the fact that `key` may be
210 # None when algorithm is "none".
211 key=None, # type: ignore[arg-type,unused-ignore]
212 headers={"alg": "none"},
213 )
214 with pytest.raises(DecodeError) as context:
215 jws.decode(msg, algorithms=["none"])
216 assert str(context.value) == "Signature verification failed"
217
218 @crypto_required
219 def test_encode_with_headers_alg_es256(self, jws: PyJWS, payload: bytes) -> None:
220 with open(key_path("testkey_ec.priv"), "rb") as ec_priv_file:
221 priv_key = load_pem_private_key(ec_priv_file.read(), password=None)
222 with open(key_path("testkey_ec.pub"), "rb") as ec_pub_file:
223 pub_key = load_pem_public_key(ec_pub_file.read())
224
225 assert isinstance(priv_key, EllipticCurvePrivateKey)
226 assert isinstance(pub_key, EllipticCurvePublicKey)
227
228 msg = jws.encode(payload, priv_key, headers={"alg": "ES256"})
229 assert b"hello world" == jws.decode(msg, pub_key, algorithms=["ES256"])
230
231 @crypto_required
232 def test_encode_with_alg_hs256_and_headers_alg_es256(
233 self, jws: PyJWS, payload: bytes
234 ) -> None:
235 with open(key_path("testkey_ec.priv"), "rb") as ec_priv_file:
236 priv_key = load_pem_private_key(ec_priv_file.read(), password=None)
237 with open(key_path("testkey_ec.pub"), "rb") as ec_pub_file:
238 pub_key = load_pem_public_key(ec_pub_file.read())
239
240 assert isinstance(priv_key, EllipticCurvePrivateKey)
241 assert isinstance(pub_key, EllipticCurvePublicKey)
242
243 msg = jws.encode(payload, priv_key, algorithm="HS256", headers={"alg": "ES256"})
244 assert b"hello world" == jws.decode(msg, pub_key, algorithms=["ES256"])
245
246 def test_encode_with_jwk(self, jws: PyJWS, payload: bytes) -> None:
247 jwk = PyJWK(
248 {
249 "kty": "oct",
250 "alg": "HS256",
251 "k": "c2VjcmV0", # "secret"
252 }
253 )
254 msg = jws.encode(payload, key=jwk)
255 decoded = jws.decode_complete(msg, key=jwk, algorithms=["HS256"])
256 assert decoded == {
257 "header": {"alg": "HS256", "typ": "JWT"},
258 "payload": payload,
259 "signature": (
260 b"H\x8a\xf4\xdf3:\xe1\xac\x16E\xd3\xeb\x00\xcf\xfa\xd5\x05\xac"
261 b"e\xc8@\xb6\x00\xd5\xde\x9aa|s\xcfZB"
262 ),
263 }
264
265 def test_encode_with_jwk_uses_key_algorithm(
266 self, jws: PyJWS, payload: bytes
267 ) -> None:
268 """Test that encoding with a PyJWK key uses the key's algorithm
269 when no algorithm is explicitly specified. Regression test for #1147."""
270 jwk = PyJWK(
271 {
272 "kty": "oct",
273 "alg": "HS384",
274 "k": "c2VjcmV0", # "secret"
275 }
276 )
277 # Should use HS384 from the key, not default to HS256
278 msg = jws.encode(payload, key=jwk)
279 header = jws.get_unverified_header(msg)
280 assert header["alg"] == "HS384"
281
282 # Should also be decodable with the same key
283 decoded = jws.decode(msg, key=jwk)
284 assert decoded == payload
285
286 def test_decode_algorithm_param_should_be_case_sensitive(self, jws: PyJWS) -> None:
287 example_jws = (
288 "eyJhbGciOiJoczI1NiIsInR5cCI6IkpXVCJ9" # alg = hs256
289 ".eyJoZWxsbyI6IndvcmxkIn0"
290 ".5R_FEPE7SW2dT9GgIxPgZATjFGXfUDOSwo7TtO_Kd_g"
291 )
292
293 with pytest.raises(InvalidAlgorithmError) as context:
294 jws.decode(example_jws, "secret", algorithms=["hs256"])
295
296 exception = context.value
297 assert str(exception) == "Algorithm not supported"
298
299 def test_bad_secret(self, jws: PyJWS, payload: bytes) -> None:
300 right_secret = "foo"
301 bad_secret = "bar"
302 jws_message = jws.encode(payload, right_secret)
303
304 with pytest.raises(DecodeError) as excinfo:
305 # Backward compat for ticket #315
306 jws.decode(jws_message, bad_secret, algorithms=["HS256"])
307 assert "Signature verification failed" == str(excinfo.value)
308
309 with pytest.raises(InvalidSignatureError) as excinfo:
310 jws.decode(jws_message, bad_secret, algorithms=["HS256"])
311 assert "Signature verification failed" == str(excinfo.value)
312
313 def test_decodes_valid_jws(self, jws: PyJWS, payload: bytes) -> None:
314 example_secret = "secret"
315 example_jws = (
316 b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9."
317 b"aGVsbG8gd29ybGQ."
318 b"gEW0pdU4kxPthjtehYdhxB9mMOGajt1xCKlGGXDJ8PM"
319 )
320
321 decoded_payload = jws.decode(example_jws, example_secret, algorithms=["HS256"])
322
323 assert decoded_payload == payload
324
325 def test_decodes_complete_valid_jws(self, jws: PyJWS, payload: bytes) -> None:
326 example_secret = "secret"
327 example_jws = (
328 b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9."
329 b"aGVsbG8gd29ybGQ."
330 b"gEW0pdU4kxPthjtehYdhxB9mMOGajt1xCKlGGXDJ8PM"
331 )
332
333 decoded = jws.decode_complete(example_jws, example_secret, algorithms=["HS256"])
334
335 assert decoded == {
336 "header": {"alg": "HS256", "typ": "JWT"},
337 "payload": payload,
338 "signature": (
339 b"\x80E\xb4\xa5\xd58\x93\x13\xed\x86;^\x85\x87a\xc4"
340 b"\x1ff0\xe1\x9a\x8e\xddq\x08\xa9F\x19p\xc9\xf0\xf3"
341 ),
342 }
343
344 def test_decodes_with_jwk(self, jws: PyJWS, payload: bytes) -> None:
345 jwk = PyJWK(
346 {
347 "kty": "oct",
348 "alg": "HS256",
349 "k": "c2VjcmV0", # "secret"
350 }
351 )
352 example_jws = (
353 b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9."
354 b"aGVsbG8gd29ybGQ."
355 b"gEW0pdU4kxPthjtehYdhxB9mMOGajt1xCKlGGXDJ8PM"
356 )
357
358 decoded_payload = jws.decode(example_jws, jwk, algorithms=["HS256"])
359
360 assert decoded_payload == payload
361
362 def test_decodes_with_jwk_and_no_algorithm(
363 self, jws: PyJWS, payload: bytes
364 ) -> None:
365 jwk = PyJWK(
366 {
367 "kty": "oct",
368 "alg": "HS256",
369 "k": "c2VjcmV0", # "secret"
370 }
371 )
372 example_jws = (
373 b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9."
374 b"aGVsbG8gd29ybGQ."
375 b"gEW0pdU4kxPthjtehYdhxB9mMOGajt1xCKlGGXDJ8PM"
376 )
377
378 decoded_payload = jws.decode(example_jws, jwk)
379
380 assert decoded_payload == payload
381
382 def test_decodes_with_jwk_and_mismatched_algorithm(
383 self, jws: PyJWS, payload: bytes
384 ) -> None:
385 jwk = PyJWK(
386 {
387 "kty": "oct",
388 "alg": "HS512",
389 "k": "c2VjcmV0", # "secret"
390 }
391 )
392 example_jws = (
393 b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9."
394 b"aGVsbG8gd29ybGQ."
395 b"gEW0pdU4kxPthjtehYdhxB9mMOGajt1xCKlGGXDJ8PM"
396 )
397
398 with pytest.raises(InvalidAlgorithmError):
399 jws.decode(example_jws, jwk)
400
401 def test_decodes_with_jwk_rejects_header_alg_outside_jwk_alg(
402 self, jws: PyJWS
403 ) -> None:
404 # Token header says HS256 and the caller's allow-list also accepts
405 # HS256, but the PyJWK is bound to HS512. Even though the allow-list
406 # would pass, verification must be locked to the PyJWK's algorithm
407 # rather than the header's — otherwise an attacker who controls a
408 # registered key can advertise a disallowed algorithm in the header
409 # and have it accepted.
410 jwk = PyJWK(
411 {
412 "kty": "oct",
413 "alg": "HS512",
414 "k": "c2VjcmV0", # "secret"
415 }
416 )
417 example_jws = (
418 b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9."
419 b"aGVsbG8gd29ybGQ."
420 b"gEW0pdU4kxPthjtehYdhxB9mMOGajt1xCKlGGXDJ8PM"
421 )
422
423 with pytest.raises(
424 InvalidAlgorithmError, match="does not match the key's algorithm"
425 ):
426 jws.decode(example_jws, jwk, algorithms=["HS256", "HS512"])
427
428 # 'Control' Elliptic Curve jws created by another library.
429 # Used to test for regressions that could affect both
430 # encoding / decoding operations equally (causing tests
431 # to still pass).
432 @crypto_required
433 def test_decodes_valid_es384_jws(self, jws: PyJWS) -> None:
434 example_payload = {"hello": "world"}
435 with open(key_path("testkey_ec.pub")) as fp:
436 example_pubkey = fp.read()
437 example_jws = (
438 b"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9."
439 b"eyJoZWxsbyI6IndvcmxkIn0.TORyNQab_MoXM7DvNKaTwbrJr4UY"
440 b"d2SsX8hhlnWelQFmPFSf_JzC2EbLnar92t-bXsDovzxp25ExazrVHkfPkQ"
441 )
442 decoded_payload = jws.decode(example_jws, example_pubkey, algorithms=["ES256"])
443 json_payload = json.loads(decoded_payload)
444
445 assert json_payload == example_payload
446
447 # 'Control' RSA jws created by another library.
448 # Used to test for regressions that could affect both
449 # encoding / decoding operations equally (causing tests
450 # to still pass).
451 @crypto_required
452 def test_decodes_valid_rs384_jws(self, jws: PyJWS) -> None:
453 example_payload = {"hello": "world"}
454 with open(key_path("testkey_rsa.pub")) as fp:
455 example_pubkey = fp.read()
456 example_jws = (
457 b"eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9"
458 b".eyJoZWxsbyI6IndvcmxkIn0"
459 b".yNQ3nI9vEDs7lEh-Cp81McPuiQ4ZRv6FL4evTYYAh1X"
460 b"lRTTR3Cz8pPA9Stgso8Ra9xGB4X3rlra1c8Jz10nTUju"
461 b"O06OMm7oXdrnxp1KIiAJDerWHkQ7l3dlizIk1bmMA457"
462 b"W2fNzNfHViuED5ISM081dgf_a71qBwJ_yShMMrSOfxDx"
463 b"mX9c4DjRogRJG8SM5PvpLqI_Cm9iQPGMvmYK7gzcq2cJ"
464 b"urHRJDJHTqIdpLWXkY7zVikeen6FhuGyn060Dz9gYq9t"
465 b"uwmrtSWCBUjiN8sqJ00CDgycxKqHfUndZbEAOjcCAhBr"
466 b"qWW3mSVivUfubsYbwUdUG3fSRPjaUPcpe8A"
467 )
468 decoded_payload = jws.decode(example_jws, example_pubkey, algorithms=["RS384"])
469 json_payload = json.loads(decoded_payload)
470
471 assert json_payload == example_payload
472
473 def test_load_verify_valid_jws(self, jws: PyJWS, payload: bytes) -> None:
474 example_secret = "secret"
475 example_jws = (
476 b"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
477 b"aGVsbG8gd29ybGQ."
478 b"SIr03zM64awWRdPrAM_61QWsZchAtgDV3pphfHPPWkI"
479 )
480
481 decoded_payload = jws.decode(
482 example_jws, key=example_secret, algorithms=["HS256"]
483 )
484 assert decoded_payload == payload
485
486 def test_allow_skip_verification(self, jws: PyJWS, payload: bytes) -> None:
487 right_secret = "foo"
488 jws_message = jws.encode(payload, right_secret)
489 decoded_payload = jws.decode(jws_message, options={"verify_signature": False})
490
491 assert decoded_payload == payload
492
493 def test_decode_with_optional_algorithms(self, jws: PyJWS) -> None:
494 example_secret = "secret"
495 example_jws = (
496 b"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
497 b"aGVsbG8gd29ybGQ."
498 b"SIr03zM64awWRdPrAM_61QWsZchAtgDV3pphfHPPWkI"
499 )
500
501 with pytest.raises(DecodeError) as exc:
502 jws.decode(example_jws, key=example_secret)
503
504 assert (
505 'It is required that you pass in a value for the "algorithms" argument when calling decode().'
506 in str(exc.value)
507 )
508
509 def test_decode_no_algorithms_verify_signature_false(self, jws: PyJWS) -> None:
510 example_secret = "secret"
511 example_jws = (
512 b"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
513 b"aGVsbG8gd29ybGQ."
514 b"SIr03zM64awWRdPrAM_61QWsZchAtgDV3pphfHPPWkI"
515 )
516
517 jws.decode(
518 example_jws,
519 key=example_secret,
520 options={"verify_signature": False},
521 )
522
523 def test_load_no_verification(self, jws: PyJWS, payload: bytes) -> None:
524 right_secret = "foo"
525 jws_message = jws.encode(payload, right_secret)
526
527 decoded_payload = jws.decode(
528 jws_message,
529 # The type signature does not capture the fact that `key` is not
530 # used when options["verify_signature"] is False.
531 key=None, # type: ignore[arg-type,unused-ignore]
532 algorithms=["HS256"],
533 options={"verify_signature": False},
534 )
535
536 assert decoded_payload == payload
537
538 def test_no_secret(self, jws: PyJWS, payload: bytes) -> None:
539 right_secret = "foo"
540 jws_message = jws.encode(payload, right_secret)
541
542 with pytest.raises(InvalidKeyError, match="must not be empty"):
543 jws.decode(jws_message, algorithms=["HS256"])
544
545 def test_verify_signature_with_no_secret(self, jws: PyJWS, payload: bytes) -> None:
546 right_secret = "foo"
547 jws_message = jws.encode(payload, right_secret)
548
549 with pytest.raises(InvalidKeyError, match="must not be empty"):
550 jws.decode(jws_message, algorithms=["HS256"])
551
552 def test_verify_signature_with_no_algo_header_throws_exception(
553 self, jws: PyJWS, payload: bytes
554 ) -> None:
555 example_jws = b"e30.eyJhIjo1fQ.KEh186CjVw_Q8FadjJcaVnE7hO5Z9nHBbU8TgbhHcBY"
556
557 with pytest.raises(InvalidAlgorithmError):
558 jws.decode(example_jws, "secret", algorithms=["HS256"])
559
560 def test_invalid_crypto_alg(self, jws: PyJWS, payload: bytes) -> None:
561 with pytest.raises(NotImplementedError):
562 jws.encode(payload, "secret", algorithm="HS1024")
563
564 @no_crypto_required
565 def test_missing_crypto_library_better_error_messages(
566 self, jws: PyJWS, payload: bytes
567 ) -> None:
568 with pytest.raises(NotImplementedError) as excinfo:
569 jws.encode(payload, "secret", algorithm="RS256")
570 assert "cryptography" in str(excinfo.value)
571
572 def test_unicode_secret(self, jws: PyJWS, payload: bytes) -> None:
573 secret = "\xc2"
574 jws_message = jws.encode(payload, secret)
575 decoded_payload = jws.decode(jws_message, secret, algorithms=["HS256"])
576
577 assert decoded_payload == payload
578
579 def test_nonascii_secret(self, jws: PyJWS, payload: bytes) -> None:
580 secret = "\xc2" # char value that ascii codec cannot decode
581 jws_message = jws.encode(payload, secret)
582
583 decoded_payload = jws.decode(jws_message, secret, algorithms=["HS256"])
584
585 assert decoded_payload == payload
586
587 def test_bytes_secret(self, jws: PyJWS, payload: bytes) -> None:
588 secret = b"\xc2" # char value that ascii codec cannot decode
589 jws_message = jws.encode(payload, secret)
590
591 decoded_payload = jws.decode(jws_message, secret, algorithms=["HS256"])
592
593 assert decoded_payload == payload
594
595 @pytest.mark.parametrize("sort_headers", (False, True))
596 def test_sorting_of_headers(
597 self, jws: PyJWS, payload: bytes, sort_headers: bool
598 ) -> None:
599 jws_message = jws.encode(
600 payload,
601 key="\xc2",
602 headers={"b": "1", "a": "2"},
603 sort_headers=sort_headers,
604 )
605 header_json = base64url_decode(jws_message.split(".")[0])
606 assert sort_headers == (header_json.index(b'"a"') < header_json.index(b'"b"'))
607
608 def test_decode_invalid_header_padding(self, jws: PyJWS) -> None:
609 example_jws = (
610 "aeyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
611 ".eyJoZWxsbyI6ICJ3b3JsZCJ9"
612 ".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
613 )
614 example_secret = "secret"
615
616 with pytest.raises(DecodeError) as exc:
617 jws.decode(example_jws, example_secret, algorithms=["HS256"])
618
619 assert "header padding" in str(exc.value)
620
621 def test_decode_invalid_header_string(self, jws: PyJWS) -> None:
622 example_jws = (
623 "eyJhbGciOiAiSFMyNTbpIiwgInR5cCI6ICJKV1QifQ=="
624 ".eyJoZWxsbyI6ICJ3b3JsZCJ9"
625 ".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
626 )
627 example_secret = "secret"
628
629 with pytest.raises(DecodeError) as exc:
630 jws.decode(example_jws, example_secret, algorithms=["HS256"])
631
632 assert "Invalid header" in str(exc.value)
633
634 def test_decode_deeply_nested_header_throws_decode_error(self, jws: PyJWS) -> None:
635 nested_header = b"[" * 1000 + b"]" * 1000
636 example_jws = ".".join(
637 (
638 base64url_encode(nested_header).decode(),
639 "eyJoZWxsbyI6ICJ3b3JsZCJ9",
640 "tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8",
641 )
642 )
643
644 with pytest.raises(DecodeError, match="Invalid header"):
645 jws.decode(example_jws, "secret", algorithms=["HS256"])
646
647 def test_decode_invalid_payload_padding(self, jws: PyJWS) -> None:
648 example_jws = (
649 "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
650 ".aeyJoZWxsbyI6ICJ3b3JsZCJ9"
651 ".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
652 )
653 example_secret = "secret"
654
655 with pytest.raises(DecodeError) as exc:
656 jws.decode(example_jws, example_secret, algorithms=["HS256"])
657
658 assert "Invalid payload padding" in str(exc.value)
659
660 def test_decode_invalid_crypto_padding(self, jws: PyJWS) -> None:
661 example_jws = (
662 "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
663 ".eyJoZWxsbyI6ICJ3b3JsZCJ9"
664 ".aatvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
665 )
666 example_secret = "secret"
667
668 with pytest.raises(DecodeError) as exc:
669 jws.decode(example_jws, example_secret, algorithms=["HS256"])
670
671 assert "Invalid crypto padding" in str(exc.value)
672
673 def test_decode_rejects_non_canonical_crypto_segment(
674 self, jws: PyJWS, payload: bytes
675 ) -> None:
676 secret = "a" * 32
677 token = jws.encode(payload, secret, algorithm="HS256")
678 header, encoded_payload, signature = token.split(".")
679 mutated_token = ".".join((header, encoded_payload, f"{signature}!!!!"))
680
681 with pytest.raises(DecodeError, match="Invalid crypto padding"):
682 jws.decode(mutated_token, secret, algorithms=["HS256"])
683
684 def test_decode_with_algo_none_should_fail(
685 self, jws: PyJWS, payload: bytes
686 ) -> None:
687 jws_message = jws.encode(
688 payload,
689 # The type signature does not capture the fact that `key` may be
690 # None when algorithm is "none".
691 key=None, # type: ignore[arg-type,unused-ignore]
692 algorithm="none",
693 )
694
695 with pytest.raises(DecodeError):
696 jws.decode(jws_message, algorithms=["none"])
697
698 def test_decode_with_algo_none_and_verify_false_should_pass(
699 self, jws: PyJWS, payload: bytes
700 ) -> None:
701 jws_message = jws.encode(
702 payload,
703 # The type signature does not capture the fact that `key` may be
704 # None when algorithm is "none".
705 key=None, # type: ignore[arg-type,unused-ignore]
706 algorithm="none",
707 )
708 jws.decode(jws_message, options={"verify_signature": False})
709
710 def test_get_unverified_header_returns_header_values(
711 self, jws: PyJWS, payload: bytes
712 ) -> None:
713 jws_message = jws.encode(
714 payload,
715 key="secret",
716 algorithm="HS256",
717 headers={"kid": "toomanysecrets"},
718 )
719
720 header = jws.get_unverified_header(jws_message)
721
722 assert "kid" in header
723 assert header["kid"] == "toomanysecrets"
724
725 def test_get_unverified_header_fails_on_bad_header_types(
726 self, jws: PyJWS, payload: bytes
727 ) -> None:
728 # Contains a bad kid value (int 123 instead of string)
729 example_jws = (
730 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6MTIzfQ"
731 ".eyJzdWIiOiIxMjM0NTY3ODkwIn0"
732 ".vs2WY54jfpKP3JGC73Vq5YlMsqM5oTZ1ZydT77SiZSk"
733 )
734
735 with pytest.raises(InvalidTokenError) as exc:
736 jws.get_unverified_header(example_jws)
737
738 assert "Key ID header parameter must be a string" == str(exc.value)
739
740 @pytest.mark.parametrize(
741 "algo",
742 [
743 "RS256",
744 "RS384",
745 "RS512",
746 ],
747 )
748 @crypto_required
749 def test_encode_decode_rsa_related_algorithms(
750 self, jws: PyJWS, payload: bytes, algo: str
751 ) -> None:
752 # PEM-formatted RSA key
753 with open(key_path("testkey_rsa.priv"), "rb") as rsa_priv_file:
754 priv_rsakey = load_pem_private_key(rsa_priv_file.read(), password=None)
755
756 assert isinstance(priv_rsakey, RSAPrivateKey)
757
758 jws_message = jws.encode(payload, priv_rsakey, algorithm=algo)
759
760 with open(key_path("testkey_rsa.pub"), "rb") as rsa_pub_file:
761 pub_rsakey = load_ssh_public_key(rsa_pub_file.read())
762
763 assert isinstance(pub_rsakey, RSAPublicKey)
764
765 jws.decode(jws_message, pub_rsakey, algorithms=[algo])
766
767 # string-formatted key
768 with open(key_path("testkey_rsa.priv")) as rsa_priv_file:
769 priv_rsakey_str = rsa_priv_file.read()
770 jws_message = jws.encode(payload, priv_rsakey_str, algorithm=algo)
771
772 with open(key_path("testkey_rsa.pub")) as rsa_pub_file:
773 pub_rsakey_str = rsa_pub_file.read()
774 jws.decode(jws_message, pub_rsakey_str, algorithms=[algo])
775
776 def test_rsa_related_algorithms(self, jws: PyJWS) -> None:
777 jws = PyJWS()
778 jws_algorithms = jws.get_algorithms()
779
780 if has_crypto:
781 assert "RS256" in jws_algorithms
782 assert "RS384" in jws_algorithms
783 assert "RS512" in jws_algorithms
784 assert "PS256" in jws_algorithms
785 assert "PS384" in jws_algorithms
786 assert "PS512" in jws_algorithms
787
788 else:
789 assert "RS256" not in jws_algorithms
790 assert "RS384" not in jws_algorithms
791 assert "RS512" not in jws_algorithms
792 assert "PS256" not in jws_algorithms
793 assert "PS384" not in jws_algorithms
794 assert "PS512" not in jws_algorithms
795
796 @pytest.mark.parametrize(
797 "algo,priv_key_file,pub_key_file",
798 [
799 ("ES256", "jwk_ec_key_P-256.json", "jwk_ec_pub_P-256.json"),
800 ("ES256K", "jwk_ec_key_secp256k1.json", "jwk_ec_pub_secp256k1.json"),
801 ("ES384", "jwk_ec_key_P-384.json", "jwk_ec_pub_P-384.json"),
802 ("ES512", "jwk_ec_key_P-521.json", "jwk_ec_pub_P-521.json"),
803 ],
804 )
805 @crypto_required
806 def test_encode_decode_ecdsa_related_algorithms(
807 self,
808 jws: PyJWS,
809 payload: bytes,
810 algo: str,
811 priv_key_file: str,
812 pub_key_file: str,
813 ) -> None:
814 from jwt.algorithms import ECAlgorithm
815
816 # Load keys from JWK files (each algorithm requires its specific curve)
817 with open(key_path(priv_key_file)) as priv_file:
818 priv_eckey = ECAlgorithm.from_jwk(priv_file.read())
819
820 assert isinstance(priv_eckey, EllipticCurvePrivateKey)
821
822 jws_message = jws.encode(payload, priv_eckey, algorithm=algo)
823
824 with open(key_path(pub_key_file)) as pub_file:
825 pub_eckey = ECAlgorithm.from_jwk(pub_file.read())
826
827 assert isinstance(pub_eckey, EllipticCurvePublicKey)
828
829 jws.decode(jws_message, pub_eckey, algorithms=[algo])
830
831 def test_ecdsa_related_algorithms(self, jws: PyJWS) -> None:
832 jws = PyJWS()
833 jws_algorithms = jws.get_algorithms()
834
835 if has_crypto:
836 assert "ES256" in jws_algorithms
837 assert "ES256K" in jws_algorithms
838 assert "ES384" in jws_algorithms
839 assert "ES512" in jws_algorithms
840 else:
841 assert "ES256" not in jws_algorithms
842 assert "ES256K" not in jws_algorithms
843 assert "ES384" not in jws_algorithms
844 assert "ES512" not in jws_algorithms
845
846 def test_skip_check_signature(self, jws: PyJWS) -> None:
847 token = (
848 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
849 ".eyJzb21lIjoicGF5bG9hZCJ9"
850 ".4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZA"
851 )
852 jws.decode(token, "secret", options={"verify_signature": False})
853
854 def test_decode_options_must_be_dict(self, jws: PyJWS, payload: bytes) -> None:
855 token = jws.encode(payload, "secret")
856
857 with pytest.raises(TypeError):
858 jws.decode(token, "secret", options=object()) # type: ignore[arg-type]
859
860 with pytest.raises((TypeError, ValueError)):
861 jws.decode(token, "secret", options="something") # type: ignore[arg-type]
862
863 def test_custom_json_encoder(self, jws: PyJWS, payload: bytes) -> None:
864 class CustomJSONEncoder(json.JSONEncoder):
865 def default(self, o: object) -> str:
866 assert isinstance(o, Decimal)
867 return "it worked"
868
869 data = {"some_decimal": Decimal("2.2")}
870
871 with pytest.raises(TypeError):
872 jws.encode(payload, "secret", headers=data)
873
874 token = jws.encode(
875 payload, "secret", headers=data, json_encoder=CustomJSONEncoder
876 )
877
878 header, *_ = token.split(".")
879 header = json.loads(base64url_decode(header))
880
881 assert "some_decimal" in header
882 assert header["some_decimal"] == "it worked"
883
884 def test_encode_headers_parameter_adds_headers(
885 self, jws: PyJWS, payload: bytes
886 ) -> None:
887 headers = {"testheader": True}
888 token = jws.encode(payload, "secret", headers=headers)
889
890 encoded_header = token[0 : token.index(".")].encode()
891 decoded_header = base64url_decode(encoded_header)
892 header = decoded_header.decode()
893
894 header_obj = json.loads(header)
895
896 assert "testheader" in header_obj
897 assert header_obj["testheader"] == headers["testheader"]
898
899 def test_encode_with_typ(self, jws: PyJWS) -> None:
900 payload = """
901 {
902 "iss": "https://scim.example.com",
903 "iat": 1458496404,
904 "jti": "4d3559ec67504aaba65d40b0363faad8",
905 "aud": [
906 "https://scim.example.com/Feeds/98d52461fa5bbc879593b7754",
907 "https://scim.example.com/Feeds/5d7604516b1d08641d7676ee7"
908 ],
909 "events": {
910 "urn:ietf:params:scim:event:create": {
911 "ref":
912 "https://scim.example.com/Users/44f6142df96bd6ab61e7521d9",
913 "attributes": ["id", "name", "userName", "password", "emails"]
914 }
915 }
916 }
917 """
918 token = jws.encode(
919 payload.encode("utf-8"), "secret", headers={"typ": "secevent+jwt"}
920 )
921
922 header = token[0 : token.index(".")].encode()
923 header = base64url_decode(header)
924 header_obj = json.loads(header)
925
926 assert "typ" in header_obj
927 assert header_obj["typ"] == "secevent+jwt"
928
929 def test_encode_with_typ_empty_string(self, jws: PyJWS, payload: bytes) -> None:
930 token = jws.encode(payload, "secret", headers={"typ": ""})
931
932 header = token[0 : token.index(".")].encode()
933 header = base64url_decode(header)
934 header_obj = json.loads(header)
935
936 assert "typ" not in header_obj
937
938 def test_encode_with_typ_none(self, jws: PyJWS, payload: bytes) -> None:
939 token = jws.encode(payload, "secret", headers={"typ": None})
940
941 header = token[0 : token.index(".")].encode()
942 header = base64url_decode(header)
943 header_obj = json.loads(header)
944
945 assert "typ" not in header_obj
946
947 def test_encode_with_typ_without_keywords(self, jws: PyJWS, payload: bytes) -> None:
948 headers = {"foo": "bar"}
949 token = jws.encode(payload, "secret", "HS256", headers, None)
950
951 header = token[0 : token.index(".")].encode()
952 header = base64url_decode(header)
953 header_obj = json.loads(header)
954
955 assert "foo" in header_obj
956 assert header_obj["foo"] == "bar"
957
958 def test_encode_fails_on_invalid_kid_types(
959 self, jws: PyJWS, payload: bytes
960 ) -> None:
961 with pytest.raises(InvalidTokenError) as exc:
962 jws.encode(payload, "secret", headers={"kid": 123})
963
964 assert "Key ID header parameter must be a string" == str(exc.value)
965
966 with pytest.raises(InvalidTokenError) as exc:
967 jws.encode(payload, "secret", headers={"kid": None})
968
969 assert "Key ID header parameter must be a string" == str(exc.value)
970
971 def test_encode_decode_with_detached_content(
972 self, jws: PyJWS, payload: bytes
973 ) -> None:
974 secret = "secret"
975 jws_message = jws.encode(
976 payload, secret, algorithm="HS256", is_payload_detached=True
977 )
978
979 jws.decode(jws_message, secret, algorithms=["HS256"], detached_payload=payload)
980
981 def test_decode_rejects_detached_payload_for_attached_content(
982 self, jws: PyJWS, payload: bytes
983 ) -> None:
984 secret = "secret"
985 jws_message = jws.encode(payload, secret, algorithm="HS256")
986
987 with pytest.raises(DecodeError, match="detached_payload.*b64.*false"):
988 jws.decode(
989 jws_message,
990 secret,
991 algorithms=["HS256"],
992 detached_payload=b"different payload",
993 )
994
995 def test_encode_detached_content_with_b64_header(
996 self, jws: PyJWS, payload: bytes
997 ) -> None:
998 secret = "secret"
999
1000 # Check that detached content is automatically detected when b64 is false
1001 headers = {"b64": False}
1002 token = jws.encode(payload, secret, "HS256", headers)
1003
1004 msg_header, msg_payload, _ = token.split(".")
1005 msg_header_bytes = base64url_decode(msg_header.encode())
1006 msg_header_obj = json.loads(msg_header_bytes)
1007
1008 assert "b64" in msg_header_obj
1009 assert msg_header_obj["b64"] is False
1010 # Check that the payload is not inside the token
1011 assert not msg_payload
1012
1013 # Check that content is not detached and b64 header removed when b64 is true
1014 headers = {"b64": True}
1015 token = jws.encode(payload, secret, "HS256", headers)
1016
1017 msg_header, msg_payload, _ = token.split(".")
1018 msg_header_bytes = base64url_decode(msg_header.encode())
1019 msg_header_obj = json.loads(msg_header_bytes)
1020
1021 assert "b64" not in msg_header_obj
1022 assert msg_payload
1023
1024 def test_encode_b64_false_auto_adds_b64_to_crit(
1025 self, jws: PyJWS, payload: bytes
1026 ) -> None:
1027 # RFC 7797 §3: producers MUST list "b64" in "crit" whenever "b64"
1028 # appears in the protected header.
1029 secret = "secret"
1030 token = jws.encode(payload, secret, algorithm="HS256", is_payload_detached=True)
1031
1032 msg_header, _, _ = token.split(".")
1033 header_obj = json.loads(base64url_decode(msg_header.encode()))
1034
1035 assert header_obj["b64"] is False
1036 assert "b64" in header_obj.get("crit", [])
1037
1038 def test_encode_b64_false_preserves_existing_crit_entries(
1039 self, jws: PyJWS, payload: bytes
1040 ) -> None:
1041 secret = "secret"
1042 # Caller-supplied crit (containing a hypothetical extension that
1043 # PyJWT does support) should be preserved alongside the auto-added
1044 # "b64" marker.
1045 token = jws.encode(
1046 payload,
1047 secret,
1048 algorithm="HS256",
1049 headers={"b64": False, "crit": ["b64"]},
1050 )
1051
1052 header_obj = json.loads(base64url_decode(token.split(".")[0].encode()))
1053 assert header_obj["crit"] == ["b64"]
1054
1055 def test_decode_b64_false_rejects_non_empty_payload_segment(
1056 self, jws: PyJWS, payload: bytes
1057 ) -> None:
1058 # RFC 7515 Appendix F detached form: when b64=false, the compact-
1059 # serialization payload segment must be empty. PyJWT must reject a
1060 # non-empty middle segment without doing any base64-decoding work
1061 # on it — that decode used to be the unauthenticated DoS amplifier.
1062 secret = "secret"
1063 import hmac as _hmac
1064 import hashlib as _hashlib
1065
1066 header_obj = {
1067 "typ": "JWT",
1068 "alg": "HS256",
1069 "b64": False,
1070 "crit": ["b64"],
1071 }
1072 header_b64 = base64url_encode(
1073 json.dumps(header_obj, separators=(",", ":")).encode()
1074 )
1075 # Stuff the middle segment with arbitrary attacker-controlled bytes.
1076 # This should be rejected without being base64-decoded.
1077 attacker_segment = b"A" * 1024
1078 signing_input = b".".join([header_b64, payload])
1079 sig = _hmac.new(secret.encode(), signing_input, _hashlib.sha256).digest()
1080 token = b".".join(
1081 [header_b64, attacker_segment, base64url_encode(sig)]
1082 ).decode()
1083
1084 with pytest.raises(DecodeError, match="Payload segment must be empty"):
1085 jws.decode(token, secret, algorithms=["HS256"], detached_payload=payload)
1086
1087 def test_decode_b64_false_without_crit_b64_is_rejected(
1088 self, jws: PyJWS, payload: bytes
1089 ) -> None:
1090 # Hand-craft a non-compliant token: header has b64=false but no
1091 # crit:["b64"]. Per RFC 7797 §3, such tokens are malformed and must
1092 # be rejected even though PyJWT understands b64.
1093 secret = "secret"
1094 import hmac as _hmac
1095 import hashlib as _hashlib
1096
1097 header_obj = {"typ": "JWT", "alg": "HS256", "b64": False}
1098 header_b64 = base64url_encode(
1099 json.dumps(header_obj, separators=(",", ":")).encode()
1100 )
1101 signing_input = b".".join([header_b64, payload])
1102 sig = _hmac.new(secret.encode(), signing_input, _hashlib.sha256).digest()
1103 token = b".".join([header_b64, b"", base64url_encode(sig)]).decode()
1104
1105 with pytest.raises(InvalidTokenError, match="b64.*crit"):
1106 jws.decode(token, secret, algorithms=["HS256"], detached_payload=payload)
1107
1108 def test_decode_detached_content_without_proper_argument(
1109 self, jws: PyJWS, payload: bytes
1110 ) -> None:
1111 example_secret = "secret"
1112 example_jws = jws.encode(
1113 payload, example_secret, algorithm="HS256", is_payload_detached=True
1114 )
1115
1116 with pytest.raises(DecodeError) as exc:
1117 jws.decode(example_jws, example_secret, algorithms=["HS256"])
1118
1119 assert (
1120 'It is required that you pass in a value for the "detached_payload" argument to decode a message having the b64 header set to false.'
1121 in str(exc.value)
1122 )
1123
1124 def test_decode_warns_on_unsupported_kwarg(
1125 self, jws: PyJWS, payload: bytes
1126 ) -> None:
1127 secret = "secret"
1128 jws_message = jws.encode(
1129 payload, secret, algorithm="HS256", is_payload_detached=True
1130 )
1131
1132 with pytest.warns(RemovedInPyjwt3Warning) as record:
1133 jws.decode(
1134 jws_message,
1135 secret,
1136 algorithms=["HS256"],
1137 detached_payload=payload,
1138 foo="bar", # type: ignore[arg-type]
1139 )
1140 deprecation_warnings = [
1141 w for w in record if issubclass(w.category, RemovedInPyjwt3Warning)
1142 ]
1143 assert len(deprecation_warnings) == 1
1144 assert "foo" in str(deprecation_warnings[0].message)
1145
1146 def test_decode_complete_warns_on_unuspported_kwarg(
1147 self, jws: PyJWS, payload: bytes
1148 ) -> None:
1149 secret = "secret"
1150 jws_message = jws.encode(
1151 payload, secret, algorithm="HS256", is_payload_detached=True
1152 )
1153
1154 with pytest.warns(RemovedInPyjwt3Warning) as record:
1155 jws.decode_complete(
1156 jws_message,
1157 secret,
1158 algorithms=["HS256"],
1159 detached_payload=payload,
1160 foo="bar", # type: ignore[arg-type]
1161 )
1162 deprecation_warnings = [
1163 w for w in record if issubclass(w.category, RemovedInPyjwt3Warning)
1164 ]
1165 assert len(deprecation_warnings) == 1
1166 assert "foo" in str(deprecation_warnings[0].message)
1167
1168 def test_decode_rejects_unknown_crit_extension(
1169 self, jws: PyJWS, payload: bytes
1170 ) -> None:
1171 secret = "secret"
1172 token = jws.encode(
1173 payload,
1174 secret,
1175 algorithm="HS256",
1176 headers={"crit": ["x-custom-policy"], "x-custom-policy": "require-mfa"},
1177 )
1178
1179 with pytest.raises(InvalidTokenError, match="Unsupported critical extension"):
1180 jws.decode(token, secret, algorithms=["HS256"])
1181
1182 def test_decode_rejects_empty_crit(self, jws: PyJWS, payload: bytes) -> None:
1183 secret = "secret"
1184 token = jws.encode(
1185 payload,
1186 secret,
1187 algorithm="HS256",
1188 headers={"crit": []},
1189 )
1190
1191 with pytest.raises(InvalidTokenError, match="must be a non-empty list"):
1192 jws.decode(token, secret, algorithms=["HS256"])
1193
1194 def test_decode_rejects_non_list_crit(self, jws: PyJWS, payload: bytes) -> None:
1195 secret = "secret"
1196 token = jws.encode(
1197 payload,
1198 secret,
1199 algorithm="HS256",
1200 headers={"crit": "b64"},
1201 )
1202
1203 with pytest.raises(InvalidTokenError, match="must be a non-empty list"):
1204 jws.decode(token, secret, algorithms=["HS256"])
1205
1206 def test_decode_rejects_crit_with_non_string_values(
1207 self, jws: PyJWS, payload: bytes
1208 ) -> None:
1209 secret = "secret"
1210 token = jws.encode(
1211 payload,
1212 secret,
1213 algorithm="HS256",
1214 headers={"crit": [123]},
1215 )
1216
1217 with pytest.raises(InvalidTokenError, match="values must be strings"):
1218 jws.decode(token, secret, algorithms=["HS256"])
1219
1220 def test_decode_rejects_crit_extension_missing_from_header(
1221 self, jws: PyJWS, payload: bytes
1222 ) -> None:
1223 secret = "secret"
1224 token = jws.encode(
1225 payload,
1226 secret,
1227 algorithm="HS256",
1228 headers={"crit": ["b64"]},
1229 )
1230
1231 with pytest.raises(InvalidTokenError, match="missing from headers"):
1232 jws.decode(token, secret, algorithms=["HS256"])
1233
1234 def test_decode_accepts_supported_crit_extension(
1235 self, jws: PyJWS, payload: bytes
1236 ) -> None:
1237 secret = "secret"
1238 token = jws.encode(
1239 payload,
1240 secret,
1241 algorithm="HS256",
1242 headers={"crit": ["b64"], "b64": False},
1243 is_payload_detached=True,
1244 )
1245
1246 decoded = jws.decode(
1247 token,
1248 secret,
1249 algorithms=["HS256"],
1250 detached_payload=payload,
1251 )
1252 assert decoded == payload
1253
1254 def test_get_unverified_header_rejects_unknown_crit(
1255 self, jws: PyJWS, payload: bytes
1256 ) -> None:
1257 secret = "secret"
1258 token = jws.encode(
1259 payload,
1260 secret,
1261 algorithm="HS256",
1262 headers={"crit": ["x-unknown"], "x-unknown": "value"},
1263 )
1264
1265 with pytest.raises(InvalidTokenError, match="Unsupported critical extension"):
1266 jws.get_unverified_header(token)
1267
1268 def test_pyjwk_rejects_empty_hmac_key(self) -> None:
1269 import jwt
1270
1271 with pytest.raises(jwt.InvalidKeyError, match="must not be empty"):
1272 jwt.PyJWK.from_dict(
1273 {"kty": "oct", "k": "", "kid": "active", "alg": "HS256"}
1274 )