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_invalid_payload_padding(self, jws: PyJWS) -> None:
635 example_jws = (
636 "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
637 ".aeyJoZWxsbyI6ICJ3b3JsZCJ9"
638 ".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
639 )
640 example_secret = "secret"
641
642 with pytest.raises(DecodeError) as exc:
643 jws.decode(example_jws, example_secret, algorithms=["HS256"])
644
645 assert "Invalid payload padding" in str(exc.value)
646
647 def test_decode_invalid_crypto_padding(self, jws: PyJWS) -> None:
648 example_jws = (
649 "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
650 ".eyJoZWxsbyI6ICJ3b3JsZCJ9"
651 ".aatvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
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 crypto padding" in str(exc.value)
659
660 def test_decode_with_algo_none_should_fail(
661 self, jws: PyJWS, payload: bytes
662 ) -> None:
663 jws_message = jws.encode(
664 payload,
665 # The type signature does not capture the fact that `key` may be
666 # None when algorithm is "none".
667 key=None, # type: ignore[arg-type,unused-ignore]
668 algorithm="none",
669 )
670
671 with pytest.raises(DecodeError):
672 jws.decode(jws_message, algorithms=["none"])
673
674 def test_decode_with_algo_none_and_verify_false_should_pass(
675 self, jws: PyJWS, payload: bytes
676 ) -> None:
677 jws_message = jws.encode(
678 payload,
679 # The type signature does not capture the fact that `key` may be
680 # None when algorithm is "none".
681 key=None, # type: ignore[arg-type,unused-ignore]
682 algorithm="none",
683 )
684 jws.decode(jws_message, options={"verify_signature": False})
685
686 def test_get_unverified_header_returns_header_values(
687 self, jws: PyJWS, payload: bytes
688 ) -> None:
689 jws_message = jws.encode(
690 payload,
691 key="secret",
692 algorithm="HS256",
693 headers={"kid": "toomanysecrets"},
694 )
695
696 header = jws.get_unverified_header(jws_message)
697
698 assert "kid" in header
699 assert header["kid"] == "toomanysecrets"
700
701 def test_get_unverified_header_fails_on_bad_header_types(
702 self, jws: PyJWS, payload: bytes
703 ) -> None:
704 # Contains a bad kid value (int 123 instead of string)
705 example_jws = (
706 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6MTIzfQ"
707 ".eyJzdWIiOiIxMjM0NTY3ODkwIn0"
708 ".vs2WY54jfpKP3JGC73Vq5YlMsqM5oTZ1ZydT77SiZSk"
709 )
710
711 with pytest.raises(InvalidTokenError) as exc:
712 jws.get_unverified_header(example_jws)
713
714 assert "Key ID header parameter must be a string" == str(exc.value)
715
716 @pytest.mark.parametrize(
717 "algo",
718 [
719 "RS256",
720 "RS384",
721 "RS512",
722 ],
723 )
724 @crypto_required
725 def test_encode_decode_rsa_related_algorithms(
726 self, jws: PyJWS, payload: bytes, algo: str
727 ) -> None:
728 # PEM-formatted RSA key
729 with open(key_path("testkey_rsa.priv"), "rb") as rsa_priv_file:
730 priv_rsakey = load_pem_private_key(rsa_priv_file.read(), password=None)
731
732 assert isinstance(priv_rsakey, RSAPrivateKey)
733
734 jws_message = jws.encode(payload, priv_rsakey, algorithm=algo)
735
736 with open(key_path("testkey_rsa.pub"), "rb") as rsa_pub_file:
737 pub_rsakey = load_ssh_public_key(rsa_pub_file.read())
738
739 assert isinstance(pub_rsakey, RSAPublicKey)
740
741 jws.decode(jws_message, pub_rsakey, algorithms=[algo])
742
743 # string-formatted key
744 with open(key_path("testkey_rsa.priv")) as rsa_priv_file:
745 priv_rsakey_str = rsa_priv_file.read()
746 jws_message = jws.encode(payload, priv_rsakey_str, algorithm=algo)
747
748 with open(key_path("testkey_rsa.pub")) as rsa_pub_file:
749 pub_rsakey_str = rsa_pub_file.read()
750 jws.decode(jws_message, pub_rsakey_str, algorithms=[algo])
751
752 def test_rsa_related_algorithms(self, jws: PyJWS) -> None:
753 jws = PyJWS()
754 jws_algorithms = jws.get_algorithms()
755
756 if has_crypto:
757 assert "RS256" in jws_algorithms
758 assert "RS384" in jws_algorithms
759 assert "RS512" in jws_algorithms
760 assert "PS256" in jws_algorithms
761 assert "PS384" in jws_algorithms
762 assert "PS512" in jws_algorithms
763
764 else:
765 assert "RS256" not in jws_algorithms
766 assert "RS384" not in jws_algorithms
767 assert "RS512" not in jws_algorithms
768 assert "PS256" not in jws_algorithms
769 assert "PS384" not in jws_algorithms
770 assert "PS512" not in jws_algorithms
771
772 @pytest.mark.parametrize(
773 "algo,priv_key_file,pub_key_file",
774 [
775 ("ES256", "jwk_ec_key_P-256.json", "jwk_ec_pub_P-256.json"),
776 ("ES256K", "jwk_ec_key_secp256k1.json", "jwk_ec_pub_secp256k1.json"),
777 ("ES384", "jwk_ec_key_P-384.json", "jwk_ec_pub_P-384.json"),
778 ("ES512", "jwk_ec_key_P-521.json", "jwk_ec_pub_P-521.json"),
779 ],
780 )
781 @crypto_required
782 def test_encode_decode_ecdsa_related_algorithms(
783 self,
784 jws: PyJWS,
785 payload: bytes,
786 algo: str,
787 priv_key_file: str,
788 pub_key_file: str,
789 ) -> None:
790 from jwt.algorithms import ECAlgorithm
791
792 # Load keys from JWK files (each algorithm requires its specific curve)
793 with open(key_path(priv_key_file)) as priv_file:
794 priv_eckey = ECAlgorithm.from_jwk(priv_file.read())
795
796 assert isinstance(priv_eckey, EllipticCurvePrivateKey)
797
798 jws_message = jws.encode(payload, priv_eckey, algorithm=algo)
799
800 with open(key_path(pub_key_file)) as pub_file:
801 pub_eckey = ECAlgorithm.from_jwk(pub_file.read())
802
803 assert isinstance(pub_eckey, EllipticCurvePublicKey)
804
805 jws.decode(jws_message, pub_eckey, algorithms=[algo])
806
807 def test_ecdsa_related_algorithms(self, jws: PyJWS) -> None:
808 jws = PyJWS()
809 jws_algorithms = jws.get_algorithms()
810
811 if has_crypto:
812 assert "ES256" in jws_algorithms
813 assert "ES256K" in jws_algorithms
814 assert "ES384" in jws_algorithms
815 assert "ES512" in jws_algorithms
816 else:
817 assert "ES256" not in jws_algorithms
818 assert "ES256K" not in jws_algorithms
819 assert "ES384" not in jws_algorithms
820 assert "ES512" not in jws_algorithms
821
822 def test_skip_check_signature(self, jws: PyJWS) -> None:
823 token = (
824 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
825 ".eyJzb21lIjoicGF5bG9hZCJ9"
826 ".4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZA"
827 )
828 jws.decode(token, "secret", options={"verify_signature": False})
829
830 def test_decode_options_must_be_dict(self, jws: PyJWS, payload: bytes) -> None:
831 token = jws.encode(payload, "secret")
832
833 with pytest.raises(TypeError):
834 jws.decode(token, "secret", options=object()) # type: ignore[arg-type]
835
836 with pytest.raises((TypeError, ValueError)):
837 jws.decode(token, "secret", options="something") # type: ignore[arg-type]
838
839 def test_custom_json_encoder(self, jws: PyJWS, payload: bytes) -> None:
840 class CustomJSONEncoder(json.JSONEncoder):
841 def default(self, o: object) -> str:
842 assert isinstance(o, Decimal)
843 return "it worked"
844
845 data = {"some_decimal": Decimal("2.2")}
846
847 with pytest.raises(TypeError):
848 jws.encode(payload, "secret", headers=data)
849
850 token = jws.encode(
851 payload, "secret", headers=data, json_encoder=CustomJSONEncoder
852 )
853
854 header, *_ = token.split(".")
855 header = json.loads(base64url_decode(header))
856
857 assert "some_decimal" in header
858 assert header["some_decimal"] == "it worked"
859
860 def test_encode_headers_parameter_adds_headers(
861 self, jws: PyJWS, payload: bytes
862 ) -> None:
863 headers = {"testheader": True}
864 token = jws.encode(payload, "secret", headers=headers)
865
866 encoded_header = token[0 : token.index(".")].encode()
867 decoded_header = base64url_decode(encoded_header)
868 header = decoded_header.decode()
869
870 header_obj = json.loads(header)
871
872 assert "testheader" in header_obj
873 assert header_obj["testheader"] == headers["testheader"]
874
875 def test_encode_with_typ(self, jws: PyJWS) -> None:
876 payload = """
877 {
878 "iss": "https://scim.example.com",
879 "iat": 1458496404,
880 "jti": "4d3559ec67504aaba65d40b0363faad8",
881 "aud": [
882 "https://scim.example.com/Feeds/98d52461fa5bbc879593b7754",
883 "https://scim.example.com/Feeds/5d7604516b1d08641d7676ee7"
884 ],
885 "events": {
886 "urn:ietf:params:scim:event:create": {
887 "ref":
888 "https://scim.example.com/Users/44f6142df96bd6ab61e7521d9",
889 "attributes": ["id", "name", "userName", "password", "emails"]
890 }
891 }
892 }
893 """
894 token = jws.encode(
895 payload.encode("utf-8"), "secret", headers={"typ": "secevent+jwt"}
896 )
897
898 header = token[0 : token.index(".")].encode()
899 header = base64url_decode(header)
900 header_obj = json.loads(header)
901
902 assert "typ" in header_obj
903 assert header_obj["typ"] == "secevent+jwt"
904
905 def test_encode_with_typ_empty_string(self, jws: PyJWS, payload: bytes) -> None:
906 token = jws.encode(payload, "secret", headers={"typ": ""})
907
908 header = token[0 : token.index(".")].encode()
909 header = base64url_decode(header)
910 header_obj = json.loads(header)
911
912 assert "typ" not in header_obj
913
914 def test_encode_with_typ_none(self, jws: PyJWS, payload: bytes) -> None:
915 token = jws.encode(payload, "secret", headers={"typ": None})
916
917 header = token[0 : token.index(".")].encode()
918 header = base64url_decode(header)
919 header_obj = json.loads(header)
920
921 assert "typ" not in header_obj
922
923 def test_encode_with_typ_without_keywords(self, jws: PyJWS, payload: bytes) -> None:
924 headers = {"foo": "bar"}
925 token = jws.encode(payload, "secret", "HS256", headers, None)
926
927 header = token[0 : token.index(".")].encode()
928 header = base64url_decode(header)
929 header_obj = json.loads(header)
930
931 assert "foo" in header_obj
932 assert header_obj["foo"] == "bar"
933
934 def test_encode_fails_on_invalid_kid_types(
935 self, jws: PyJWS, payload: bytes
936 ) -> None:
937 with pytest.raises(InvalidTokenError) as exc:
938 jws.encode(payload, "secret", headers={"kid": 123})
939
940 assert "Key ID header parameter must be a string" == str(exc.value)
941
942 with pytest.raises(InvalidTokenError) as exc:
943 jws.encode(payload, "secret", headers={"kid": None})
944
945 assert "Key ID header parameter must be a string" == str(exc.value)
946
947 def test_encode_decode_with_detached_content(
948 self, jws: PyJWS, payload: bytes
949 ) -> None:
950 secret = "secret"
951 jws_message = jws.encode(
952 payload, secret, algorithm="HS256", is_payload_detached=True
953 )
954
955 jws.decode(jws_message, secret, algorithms=["HS256"], detached_payload=payload)
956
957 def test_encode_detached_content_with_b64_header(
958 self, jws: PyJWS, payload: bytes
959 ) -> None:
960 secret = "secret"
961
962 # Check that detached content is automatically detected when b64 is false
963 headers = {"b64": False}
964 token = jws.encode(payload, secret, "HS256", headers)
965
966 msg_header, msg_payload, _ = token.split(".")
967 msg_header_bytes = base64url_decode(msg_header.encode())
968 msg_header_obj = json.loads(msg_header_bytes)
969
970 assert "b64" in msg_header_obj
971 assert msg_header_obj["b64"] is False
972 # Check that the payload is not inside the token
973 assert not msg_payload
974
975 # Check that content is not detached and b64 header removed when b64 is true
976 headers = {"b64": True}
977 token = jws.encode(payload, secret, "HS256", headers)
978
979 msg_header, msg_payload, _ = token.split(".")
980 msg_header_bytes = base64url_decode(msg_header.encode())
981 msg_header_obj = json.loads(msg_header_bytes)
982
983 assert "b64" not in msg_header_obj
984 assert msg_payload
985
986 def test_encode_b64_false_auto_adds_b64_to_crit(
987 self, jws: PyJWS, payload: bytes
988 ) -> None:
989 # RFC 7797 §3: producers MUST list "b64" in "crit" whenever "b64"
990 # appears in the protected header.
991 secret = "secret"
992 token = jws.encode(payload, secret, algorithm="HS256", is_payload_detached=True)
993
994 msg_header, _, _ = token.split(".")
995 header_obj = json.loads(base64url_decode(msg_header.encode()))
996
997 assert header_obj["b64"] is False
998 assert "b64" in header_obj.get("crit", [])
999
1000 def test_encode_b64_false_preserves_existing_crit_entries(
1001 self, jws: PyJWS, payload: bytes
1002 ) -> None:
1003 secret = "secret"
1004 # Caller-supplied crit (containing a hypothetical extension that
1005 # PyJWT does support) should be preserved alongside the auto-added
1006 # "b64" marker.
1007 token = jws.encode(
1008 payload,
1009 secret,
1010 algorithm="HS256",
1011 headers={"b64": False, "crit": ["b64"]},
1012 )
1013
1014 header_obj = json.loads(base64url_decode(token.split(".")[0].encode()))
1015 assert header_obj["crit"] == ["b64"]
1016
1017 def test_decode_b64_false_rejects_non_empty_payload_segment(
1018 self, jws: PyJWS, payload: bytes
1019 ) -> None:
1020 # RFC 7515 Appendix F detached form: when b64=false, the compact-
1021 # serialization payload segment must be empty. PyJWT must reject a
1022 # non-empty middle segment without doing any base64-decoding work
1023 # on it — that decode used to be the unauthenticated DoS amplifier.
1024 secret = "secret"
1025 import hmac as _hmac
1026 import hashlib as _hashlib
1027
1028 header_obj = {
1029 "typ": "JWT",
1030 "alg": "HS256",
1031 "b64": False,
1032 "crit": ["b64"],
1033 }
1034 header_b64 = base64url_encode(
1035 json.dumps(header_obj, separators=(",", ":")).encode()
1036 )
1037 # Stuff the middle segment with arbitrary attacker-controlled bytes.
1038 # This should be rejected without being base64-decoded.
1039 attacker_segment = b"A" * 1024
1040 signing_input = b".".join([header_b64, payload])
1041 sig = _hmac.new(secret.encode(), signing_input, _hashlib.sha256).digest()
1042 token = b".".join(
1043 [header_b64, attacker_segment, base64url_encode(sig)]
1044 ).decode()
1045
1046 with pytest.raises(DecodeError, match="Payload segment must be empty"):
1047 jws.decode(token, secret, algorithms=["HS256"], detached_payload=payload)
1048
1049 def test_decode_b64_false_without_crit_b64_is_rejected(
1050 self, jws: PyJWS, payload: bytes
1051 ) -> None:
1052 # Hand-craft a non-compliant token: header has b64=false but no
1053 # crit:["b64"]. Per RFC 7797 §3, such tokens are malformed and must
1054 # be rejected even though PyJWT understands b64.
1055 secret = "secret"
1056 import hmac as _hmac
1057 import hashlib as _hashlib
1058
1059 header_obj = {"typ": "JWT", "alg": "HS256", "b64": False}
1060 header_b64 = base64url_encode(
1061 json.dumps(header_obj, separators=(",", ":")).encode()
1062 )
1063 signing_input = b".".join([header_b64, payload])
1064 sig = _hmac.new(secret.encode(), signing_input, _hashlib.sha256).digest()
1065 token = b".".join([header_b64, b"", base64url_encode(sig)]).decode()
1066
1067 with pytest.raises(InvalidTokenError, match="b64.*crit"):
1068 jws.decode(token, secret, algorithms=["HS256"], detached_payload=payload)
1069
1070 def test_decode_detached_content_without_proper_argument(
1071 self, jws: PyJWS, payload: bytes
1072 ) -> None:
1073 example_secret = "secret"
1074 example_jws = jws.encode(
1075 payload, example_secret, algorithm="HS256", is_payload_detached=True
1076 )
1077
1078 with pytest.raises(DecodeError) as exc:
1079 jws.decode(example_jws, example_secret, algorithms=["HS256"])
1080
1081 assert (
1082 '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.'
1083 in str(exc.value)
1084 )
1085
1086 def test_decode_warns_on_unsupported_kwarg(
1087 self, jws: PyJWS, payload: bytes
1088 ) -> None:
1089 secret = "secret"
1090 jws_message = jws.encode(
1091 payload, secret, algorithm="HS256", is_payload_detached=True
1092 )
1093
1094 with pytest.warns(RemovedInPyjwt3Warning) as record:
1095 jws.decode(
1096 jws_message,
1097 secret,
1098 algorithms=["HS256"],
1099 detached_payload=payload,
1100 foo="bar", # type: ignore[arg-type]
1101 )
1102 deprecation_warnings = [
1103 w for w in record if issubclass(w.category, RemovedInPyjwt3Warning)
1104 ]
1105 assert len(deprecation_warnings) == 1
1106 assert "foo" in str(deprecation_warnings[0].message)
1107
1108 def test_decode_complete_warns_on_unuspported_kwarg(
1109 self, jws: PyJWS, payload: bytes
1110 ) -> None:
1111 secret = "secret"
1112 jws_message = jws.encode(
1113 payload, secret, algorithm="HS256", is_payload_detached=True
1114 )
1115
1116 with pytest.warns(RemovedInPyjwt3Warning) as record:
1117 jws.decode_complete(
1118 jws_message,
1119 secret,
1120 algorithms=["HS256"],
1121 detached_payload=payload,
1122 foo="bar", # type: ignore[arg-type]
1123 )
1124 deprecation_warnings = [
1125 w for w in record if issubclass(w.category, RemovedInPyjwt3Warning)
1126 ]
1127 assert len(deprecation_warnings) == 1
1128 assert "foo" in str(deprecation_warnings[0].message)
1129
1130 def test_decode_rejects_unknown_crit_extension(
1131 self, jws: PyJWS, payload: bytes
1132 ) -> None:
1133 secret = "secret"
1134 token = jws.encode(
1135 payload,
1136 secret,
1137 algorithm="HS256",
1138 headers={"crit": ["x-custom-policy"], "x-custom-policy": "require-mfa"},
1139 )
1140
1141 with pytest.raises(InvalidTokenError, match="Unsupported critical extension"):
1142 jws.decode(token, secret, algorithms=["HS256"])
1143
1144 def test_decode_rejects_empty_crit(self, jws: PyJWS, payload: bytes) -> None:
1145 secret = "secret"
1146 token = jws.encode(
1147 payload,
1148 secret,
1149 algorithm="HS256",
1150 headers={"crit": []},
1151 )
1152
1153 with pytest.raises(InvalidTokenError, match="must be a non-empty list"):
1154 jws.decode(token, secret, algorithms=["HS256"])
1155
1156 def test_decode_rejects_non_list_crit(self, jws: PyJWS, payload: bytes) -> None:
1157 secret = "secret"
1158 token = jws.encode(
1159 payload,
1160 secret,
1161 algorithm="HS256",
1162 headers={"crit": "b64"},
1163 )
1164
1165 with pytest.raises(InvalidTokenError, match="must be a non-empty list"):
1166 jws.decode(token, secret, algorithms=["HS256"])
1167
1168 def test_decode_rejects_crit_with_non_string_values(
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": [123]},
1177 )
1178
1179 with pytest.raises(InvalidTokenError, match="values must be strings"):
1180 jws.decode(token, secret, algorithms=["HS256"])
1181
1182 def test_decode_rejects_crit_extension_missing_from_header(
1183 self, jws: PyJWS, payload: bytes
1184 ) -> None:
1185 secret = "secret"
1186 token = jws.encode(
1187 payload,
1188 secret,
1189 algorithm="HS256",
1190 headers={"crit": ["b64"]},
1191 )
1192
1193 with pytest.raises(InvalidTokenError, match="missing from headers"):
1194 jws.decode(token, secret, algorithms=["HS256"])
1195
1196 def test_decode_accepts_supported_crit_extension(
1197 self, jws: PyJWS, payload: bytes
1198 ) -> None:
1199 secret = "secret"
1200 token = jws.encode(
1201 payload,
1202 secret,
1203 algorithm="HS256",
1204 headers={"crit": ["b64"], "b64": False},
1205 is_payload_detached=True,
1206 )
1207
1208 decoded = jws.decode(
1209 token,
1210 secret,
1211 algorithms=["HS256"],
1212 detached_payload=payload,
1213 )
1214 assert decoded == payload
1215
1216 def test_get_unverified_header_rejects_unknown_crit(
1217 self, jws: PyJWS, payload: bytes
1218 ) -> None:
1219 secret = "secret"
1220 token = jws.encode(
1221 payload,
1222 secret,
1223 algorithm="HS256",
1224 headers={"crit": ["x-unknown"], "x-unknown": "value"},
1225 )
1226
1227 with pytest.raises(InvalidTokenError, match="Unsupported critical extension"):
1228 jws.get_unverified_header(token)