Debian Codegraph @

tests/test_api_jwt.py

raw
1 import json
2 import time
3 from calendar import timegm
4 from collections.abc import Iterator, MutableMapping
5 from datetime import datetime, timedelta, timezone
6 from decimal import Decimal
7
8 import pytest
9
10 from jwt.types import Options
11 from jwt.api_jwk import PyJWK
12 from jwt.api_jwt import PyJWT
13 from jwt.exceptions import (
14 DecodeError,
15 ExpiredSignatureError,
16 ImmatureSignatureError,
17 InvalidAudienceError,
18 InvalidIssuedAtError,
19 InvalidIssuerError,
20 InvalidJTIError,
21 InvalidSubjectError,
22 MissingRequiredClaimError,
23 )
24 from jwt.utils import base64url_decode
25 from jwt.warnings import RemovedInPyjwt3Warning
26
27 from .utils import crypto_required, key_path, utc_timestamp
28
29
30 @pytest.fixture
31 def jwt() -> PyJWT:
32 return PyJWT()
33
34
35 @pytest.fixture
36 def payload() -> dict[str, object]:
37 """Creates a sample JWT claimset for use as a payload during tests"""
38 return {"iss": "jeff", "exp": utc_timestamp() + 15, "claim": "insanity"}
39
40
41 class TestJWT:
42 def test_decode_does_not_mutate_options_when_signature_verification_is_disabled(
43 self, jwt: PyJWT
44 ) -> None:
45 options: Options = {"verify_signature": False}
46 token = jwt.encode({"claim": "value"}, "a" * 32, algorithm="HS256")
47 original_options = options.copy()
48
49 jwt.decode(token, options=options)
50
51 assert options == original_options
52
53 def test_reused_options_do_not_disable_claim_verification(self, jwt: PyJWT) -> None:
54 options: Options = {"verify_signature": False}
55 token = jwt.encode({"exp": utc_timestamp() - 1}, "a" * 32, algorithm="HS256")
56
57 jwt.decode(token, options=options)
58 options["verify_signature"] = True
59
60 with pytest.raises(ExpiredSignatureError):
61 jwt.decode(token, "a" * 32, algorithms=["HS256"], options=options)
62
63 def test_decode_complete_preserves_mutable_mapping_input(self, jwt: PyJWT) -> None:
64 class MappingWithoutCopy(MutableMapping[str, object]):
65 def __init__(self, values: dict[str, object]) -> None:
66 self._data = values
67
68 def __getitem__(self, key: str) -> object:
69 return self._data[key]
70
71 def __setitem__(self, key: str, value: object) -> None:
72 self._data[key] = value
73
74 def __delitem__(self, key: str) -> None:
75 del self._data[key]
76
77 def __iter__(self) -> Iterator[str]:
78 return iter(self._data)
79
80 def __len__(self) -> int:
81 return len(self._data)
82
83 options = MappingWithoutCopy({"verify_signature": False})
84 token = jwt.encode({"claim": "value"}, "a" * 32, algorithm="HS256")
85
86 jwt.decode_complete(token, options=options) # type: ignore[arg-type]
87
88 assert dict(options) == {"verify_signature": False}
89
90 def test_constructor_does_not_mutate_options_input(self, jwt: PyJWT) -> None:
91 options: Options = {"verify_signature": False}
92
93 PyJWT(options=options)
94
95 assert options == {"verify_signature": False}
96
97 def test_jwt_with_options(self) -> None:
98 jwt = PyJWT(options={"verify_signature": False})
99 assert jwt.options["verify_signature"] is False
100 # assert that unrelated option is unchanged from default
101 assert jwt.options["strict_aud"] is False
102 # assert that verify_signature is respected unless verify_exp is overridden
103 assert jwt.options["verify_exp"] is False
104
105 def test_encode_with_jwk_uses_key_algorithm(self, jwt: PyJWT) -> None:
106 """Test that encoding with a PyJWK key uses the key's algorithm
107 when no algorithm is explicitly specified. Regression test for #1147."""
108 jwk = PyJWK(
109 {
110 "kty": "oct",
111 "alg": "HS384",
112 "k": "c2VjcmV0", # "secret"
113 }
114 )
115 payload = {"hello": "world"}
116 # Should use HS384 from the key, not default to HS256
117 token = jwt.encode(payload, jwk)
118 header = jwt.decode_complete(token, jwk, algorithms=["HS384"])["header"]
119 assert header["alg"] == "HS384"
120
121 def test_decodes_valid_jwt(self, jwt: PyJWT) -> None:
122 example_payload = {"hello": "world"}
123 example_secret = "secret"
124 example_jwt = (
125 b"eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
126 b".eyJoZWxsbyI6ICJ3b3JsZCJ9"
127 b".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
128 )
129 decoded_payload = jwt.decode(example_jwt, example_secret, algorithms=["HS256"])
130
131 assert decoded_payload == example_payload
132
133 def test_decodes_complete_valid_jwt(self, jwt: PyJWT) -> None:
134 example_payload = {"hello": "world"}
135 example_secret = "secret"
136 example_jwt = (
137 b"eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
138 b".eyJoZWxsbyI6ICJ3b3JsZCJ9"
139 b".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
140 )
141 decoded = jwt.decode_complete(example_jwt, example_secret, algorithms=["HS256"])
142
143 assert decoded == {
144 "header": {"alg": "HS256", "typ": "JWT"},
145 "payload": example_payload,
146 "signature": (
147 b'\xb6\xf6\xa0,2\xe8j"J\xc4\xe2\xaa\xa4\x15\xd2'
148 b"\x10l\xbbI\x84\xa2}\x98c\x9e\xd8&\xf5\xcbi\xca?"
149 ),
150 }
151
152 def test_load_verify_valid_jwt(self, jwt: PyJWT) -> None:
153 example_payload = {"hello": "world"}
154 example_secret = "secret"
155 example_jwt = (
156 b"eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
157 b".eyJoZWxsbyI6ICJ3b3JsZCJ9"
158 b".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
159 )
160
161 decoded_payload = jwt.decode(
162 example_jwt, key=example_secret, algorithms=["HS256"]
163 )
164
165 assert decoded_payload == example_payload
166
167 def test_decode_invalid_payload_string(self, jwt: PyJWT) -> None:
168 example_jwt = (
169 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.aGVsb"
170 "G8gd29ybGQ.SIr03zM64awWRdPrAM_61QWsZchAtgDV"
171 "3pphfHPPWkI"
172 )
173 example_secret = "secret"
174
175 with pytest.raises(DecodeError) as exc:
176 jwt.decode(example_jwt, example_secret, algorithms=["HS256"])
177
178 assert "Invalid payload string" in str(exc.value)
179
180 def test_decode_with_non_mapping_payload_throws_exception(self, jwt: PyJWT) -> None:
181 secret = "secret"
182 example_jwt = (
183 "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9."
184 "MQ." # == 1
185 "AbcSR3DWum91KOgfKxUHm78rLs_DrrZ1CrDgpUFFzls"
186 )
187
188 with pytest.raises(DecodeError) as context:
189 jwt.decode(example_jwt, secret, algorithms=["HS256"])
190
191 exception = context.value
192 assert str(exception) == "Invalid payload string: must be a json object"
193
194 def test_decode_with_invalid_audience_param_throws_exception(
195 self, jwt: PyJWT
196 ) -> None:
197 secret = "secret"
198 example_jwt = (
199 "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
200 ".eyJoZWxsbyI6ICJ3b3JsZCJ9"
201 ".tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8"
202 )
203
204 with pytest.raises(TypeError) as context:
205 jwt.decode(
206 example_jwt,
207 secret,
208 audience=1, # type: ignore[arg-type]
209 algorithms=["HS256"],
210 )
211
212 exception = context.value
213 assert str(exception) == "audience must be a string, iterable or None"
214
215 def test_decode_with_nonlist_aud_claim_throws_exception(self, jwt: PyJWT) -> None:
216 secret = "secret"
217 example_jwt = (
218 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
219 ".eyJoZWxsbyI6IndvcmxkIiwiYXVkIjoxfQ" # aud = 1
220 ".Rof08LBSwbm8Z_bhA2N3DFY-utZR1Gi9rbIS5Zthnnc"
221 )
222
223 with pytest.raises(InvalidAudienceError) as context:
224 jwt.decode(
225 example_jwt,
226 secret,
227 audience="my_audience",
228 algorithms=["HS256"],
229 )
230
231 exception = context.value
232 assert str(exception) == "Invalid claim format in token"
233
234 def test_decode_with_invalid_aud_list_member_throws_exception(
235 self, jwt: PyJWT
236 ) -> None:
237 secret = "secret"
238 example_jwt = (
239 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
240 ".eyJoZWxsbyI6IndvcmxkIiwiYXVkIjpbMV19"
241 ".iQgKpJ8shetwNMIosNXWBPFB057c2BHs-8t1d2CCM2A"
242 )
243
244 with pytest.raises(InvalidAudienceError) as context:
245 jwt.decode(
246 example_jwt,
247 secret,
248 audience="my_audience",
249 algorithms=["HS256"],
250 )
251
252 exception = context.value
253 assert str(exception) == "Invalid claim format in token"
254
255 def test_encode_bad_type(self, jwt: PyJWT) -> None:
256 types = ["string", tuple(), list(), 42, set()]
257
258 for t in types:
259 pytest.raises(
260 TypeError,
261 lambda t=t: jwt.encode(t, "secret", algorithm="HS256"),
262 )
263
264 def test_encode_with_non_str_iss(self, jwt: PyJWT) -> None:
265 """Regression test for Issue #1039."""
266 with pytest.raises(TypeError):
267 jwt.encode(
268 {
269 "iss": 123,
270 },
271 key="secret",
272 )
273
274 def test_encode_with_typ(self, jwt: PyJWT) -> None:
275 payload = {
276 "iss": "https://scim.example.com",
277 "iat": 1458496404,
278 "jti": "4d3559ec67504aaba65d40b0363faad8",
279 "aud": [
280 "https://scim.example.com/Feeds/98d52461fa5bbc879593b7754",
281 "https://scim.example.com/Feeds/5d7604516b1d08641d7676ee7",
282 ],
283 "events": {
284 "urn:ietf:params:scim:event:create": {
285 "ref": "https://scim.example.com/Users/44f6142df96bd6ab61e7521d9",
286 "attributes": ["id", "name", "userName", "password", "emails"],
287 }
288 },
289 }
290 token = jwt.encode(
291 payload, "secret", algorithm="HS256", headers={"typ": "secevent+jwt"}
292 )
293 header = token[0 : token.index(".")].encode()
294 header = base64url_decode(header)
295 header_obj = json.loads(header)
296
297 assert "typ" in header_obj
298 assert header_obj["typ"] == "secevent+jwt"
299
300 def test_decode_raises_exception_if_exp_is_not_int(self, jwt: PyJWT) -> None:
301 # >>> jwt.encode({'exp': 'not-an-int'}, 'secret')
302 example_jwt = (
303 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
304 "eyJleHAiOiJub3QtYW4taW50In0."
305 "P65iYgoHtBqB07PMtBSuKNUEIPPPfmjfJG217cEE66s"
306 )
307
308 with pytest.raises(DecodeError) as exc:
309 jwt.decode(example_jwt, "secret", algorithms=["HS256"])
310
311 assert "exp" in str(exc.value)
312
313 def test_decode_raises_exception_if_iat_is_not_int(self, jwt: PyJWT) -> None:
314 # >>> jwt.encode({'iat': 'not-an-int'}, 'secret')
315 example_jwt = (
316 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
317 "eyJpYXQiOiJub3QtYW4taW50In0."
318 "H1GmcQgSySa5LOKYbzGm--b1OmRbHFkyk8pq811FzZM"
319 )
320
321 with pytest.raises(InvalidIssuedAtError):
322 jwt.decode(example_jwt, "secret", algorithms=["HS256"])
323
324 def test_decode_raises_exception_if_iat_is_greater_than_now(
325 self, jwt: PyJWT, payload: dict[str, object]
326 ) -> None:
327 payload["iat"] = utc_timestamp() + 10
328 secret = "secret"
329 jwt_message = jwt.encode(payload, secret)
330
331 with pytest.raises(ImmatureSignatureError):
332 jwt.decode(jwt_message, secret, algorithms=["HS256"])
333
334 def test_decode_works_if_iat_is_str_of_a_number(
335 self, jwt: PyJWT, payload: dict[str, object]
336 ) -> None:
337 payload["iat"] = "1638202770"
338 secret = "secret"
339 jwt_message = jwt.encode(payload, secret)
340 data = jwt.decode(jwt_message, secret, algorithms=["HS256"])
341 assert data["iat"] == "1638202770"
342
343 def test_decode_raises_exception_if_nbf_is_not_int(self, jwt: PyJWT) -> None:
344 # >>> jwt.encode({'nbf': 'not-an-int'}, 'secret')
345 example_jwt = (
346 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
347 "eyJuYmYiOiJub3QtYW4taW50In0."
348 "c25hldC8G2ZamC8uKpax9sYMTgdZo3cxrmzFHaAAluw"
349 )
350
351 with pytest.raises(DecodeError):
352 jwt.decode(example_jwt, "secret", algorithms=["HS256"])
353
354 def test_decode_allows_aud_to_be_none(self, jwt: PyJWT) -> None:
355 # >>> jwt.encode({'aud': None}, 'secret')
356 example_jwt = (
357 "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9."
358 "eyJhdWQiOm51bGx9."
359 "-Peqc-pTugGvrc5C8Bnl0-X1V_5fv-aVb_7y7nGBVvQ"
360 )
361 decoded = jwt.decode(example_jwt, "secret", algorithms=["HS256"])
362 assert decoded["aud"] is None
363
364 def test_encode_datetime(self, jwt: PyJWT) -> None:
365 secret = "secret"
366 current_datetime = datetime.now(tz=timezone.utc)
367 payload = {
368 "exp": current_datetime,
369 "iat": current_datetime,
370 "nbf": current_datetime,
371 }
372 jwt_message = jwt.encode(payload, secret)
373 decoded_payload = jwt.decode(
374 jwt_message, secret, leeway=1, algorithms=["HS256"]
375 )
376
377 assert decoded_payload["exp"] == timegm(current_datetime.utctimetuple())
378 assert decoded_payload["iat"] == timegm(current_datetime.utctimetuple())
379 assert decoded_payload["nbf"] == timegm(current_datetime.utctimetuple())
380 # payload is not mutated.
381 assert payload == {
382 "exp": current_datetime,
383 "iat": current_datetime,
384 "nbf": current_datetime,
385 }
386
387 # 'Control' Elliptic Curve JWT created by another library.
388 # Used to test for regressions that could affect both
389 # encoding / decoding operations equally (causing tests
390 # to still pass).
391 @crypto_required
392 def test_decodes_valid_es256_jwt(self, jwt: PyJWT) -> None:
393 example_payload = {"hello": "world"}
394 with open(key_path("testkey_ec.pub")) as fp:
395 example_pubkey = fp.read()
396 example_jwt = (
397 b"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9."
398 b"eyJoZWxsbyI6IndvcmxkIn0.TORyNQab_MoXM7DvNKaTwbrJr4UY"
399 b"d2SsX8hhlnWelQFmPFSf_JzC2EbLnar92t-bXsDovzxp25ExazrVHkfPkQ"
400 )
401
402 decoded_payload = jwt.decode(example_jwt, example_pubkey, algorithms=["ES256"])
403 assert decoded_payload == example_payload
404
405 # 'Control' RSA JWT created by another library.
406 # Used to test for regressions that could affect both
407 # encoding / decoding operations equally (causing tests
408 # to still pass).
409 @crypto_required
410 def test_decodes_valid_rs384_jwt(self, jwt: PyJWT) -> None:
411 example_payload = {"hello": "world"}
412 with open(key_path("testkey_rsa.pub")) as fp:
413 example_pubkey = fp.read()
414 example_jwt = (
415 b"eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9"
416 b".eyJoZWxsbyI6IndvcmxkIn0"
417 b".yNQ3nI9vEDs7lEh-Cp81McPuiQ4ZRv6FL4evTYYAh1X"
418 b"lRTTR3Cz8pPA9Stgso8Ra9xGB4X3rlra1c8Jz10nTUju"
419 b"O06OMm7oXdrnxp1KIiAJDerWHkQ7l3dlizIk1bmMA457"
420 b"W2fNzNfHViuED5ISM081dgf_a71qBwJ_yShMMrSOfxDx"
421 b"mX9c4DjRogRJG8SM5PvpLqI_Cm9iQPGMvmYK7gzcq2cJ"
422 b"urHRJDJHTqIdpLWXkY7zVikeen6FhuGyn060Dz9gYq9t"
423 b"uwmrtSWCBUjiN8sqJ00CDgycxKqHfUndZbEAOjcCAhBr"
424 b"qWW3mSVivUfubsYbwUdUG3fSRPjaUPcpe8A"
425 )
426 decoded_payload = jwt.decode(example_jwt, example_pubkey, algorithms=["RS384"])
427
428 assert decoded_payload == example_payload
429
430 def test_decode_with_expiration(
431 self, jwt: PyJWT, payload: dict[str, object]
432 ) -> None:
433 payload["exp"] = utc_timestamp() - 1
434 secret = "secret"
435 jwt_message = jwt.encode(payload, secret)
436
437 with pytest.raises(ExpiredSignatureError):
438 jwt.decode(jwt_message, secret, algorithms=["HS256"])
439
440 def test_decode_with_notbefore(
441 self, jwt: PyJWT, payload: dict[str, object]
442 ) -> None:
443 payload["nbf"] = utc_timestamp() + 10
444 secret = "secret"
445 jwt_message = jwt.encode(payload, secret)
446
447 with pytest.raises(ImmatureSignatureError):
448 jwt.decode(jwt_message, secret, algorithms=["HS256"])
449
450 def test_decode_skip_expiration_verification(
451 self, jwt: PyJWT, payload: dict[str, object]
452 ) -> None:
453 payload["exp"] = time.time() - 1
454 secret = "secret"
455 jwt_message = jwt.encode(payload, secret)
456
457 jwt.decode(
458 jwt_message,
459 secret,
460 algorithms=["HS256"],
461 options={"verify_exp": False},
462 )
463
464 def test_decode_skip_notbefore_verification(
465 self, jwt: PyJWT, payload: dict[str, object]
466 ) -> None:
467 payload["nbf"] = time.time() + 10
468 secret = "secret"
469 jwt_message = jwt.encode(payload, secret)
470
471 jwt.decode(
472 jwt_message,
473 secret,
474 algorithms=["HS256"],
475 options={"verify_nbf": False},
476 )
477
478 def test_decode_with_expiration_with_leeway(
479 self, jwt: PyJWT, payload: dict[str, object]
480 ) -> None:
481 payload["exp"] = utc_timestamp() - 2
482 secret = "secret"
483 jwt_message = jwt.encode(payload, secret)
484
485 # With 5 seconds leeway, should be ok
486 for leeway in (5, timedelta(seconds=5)):
487 decoded = jwt.decode(
488 jwt_message, secret, leeway=leeway, algorithms=["HS256"]
489 )
490 assert decoded == payload
491
492 # With 1 seconds, should fail
493 for leeway in (1, timedelta(seconds=1)):
494 with pytest.raises(ExpiredSignatureError):
495 jwt.decode(jwt_message, secret, leeway=leeway, algorithms=["HS256"])
496
497 def test_decode_with_notbefore_with_leeway(
498 self, jwt: PyJWT, payload: dict[str, object]
499 ) -> None:
500 payload["nbf"] = utc_timestamp() + 10
501 secret = "secret"
502 jwt_message = jwt.encode(payload, secret)
503
504 # With 13 seconds leeway, should be ok
505 jwt.decode(jwt_message, secret, leeway=13, algorithms=["HS256"])
506
507 with pytest.raises(ImmatureSignatureError):
508 jwt.decode(jwt_message, secret, leeway=1, algorithms=["HS256"])
509
510 def test_check_audience_when_valid(self, jwt: PyJWT) -> None:
511 payload = {"some": "payload", "aud": "urn:me"}
512 token = jwt.encode(payload, "secret")
513 jwt.decode(token, "secret", audience="urn:me", algorithms=["HS256"])
514
515 def test_check_audience_list_when_valid(self, jwt: PyJWT) -> None:
516 payload = {"some": "payload", "aud": "urn:me"}
517 token = jwt.encode(payload, "secret")
518 jwt.decode(
519 token,
520 "secret",
521 audience=["urn:you", "urn:me"],
522 algorithms=["HS256"],
523 )
524
525 def test_check_audience_none_specified(self, jwt: PyJWT) -> None:
526 payload = {"some": "payload", "aud": "urn:me"}
527 token = jwt.encode(payload, "secret")
528 with pytest.raises(InvalidAudienceError):
529 jwt.decode(token, "secret", algorithms=["HS256"])
530
531 def test_raise_exception_invalid_audience_list(self, jwt: PyJWT) -> None:
532 payload = {"some": "payload", "aud": "urn:me"}
533 token = jwt.encode(payload, "secret")
534 with pytest.raises(InvalidAudienceError):
535 jwt.decode(
536 token,
537 "secret",
538 audience=["urn:you", "urn:him"],
539 algorithms=["HS256"],
540 )
541
542 def test_check_audience_in_array_when_valid(self, jwt: PyJWT) -> None:
543 payload = {"some": "payload", "aud": ["urn:me", "urn:someone-else"]}
544 token = jwt.encode(payload, "secret")
545 jwt.decode(token, "secret", audience="urn:me", algorithms=["HS256"])
546
547 def test_raise_exception_invalid_audience(self, jwt: PyJWT) -> None:
548 payload = {"some": "payload", "aud": "urn:someone-else"}
549
550 token = jwt.encode(payload, "secret")
551
552 with pytest.raises(InvalidAudienceError):
553 jwt.decode(token, "secret", audience="urn-me", algorithms=["HS256"])
554
555 def test_raise_exception_audience_as_bytes(self, jwt: PyJWT) -> None:
556 payload = {"some": "payload", "aud": ["urn:me", "urn:someone-else"]}
557 token = jwt.encode(payload, "secret")
558 with pytest.raises(InvalidAudienceError):
559 jwt.decode(
560 token,
561 "secret",
562 audience=b"urn:me", # type: ignore[arg-type]
563 algorithms=["HS256"],
564 )
565
566 def test_raise_exception_invalid_audience_in_array(self, jwt: PyJWT) -> None:
567 payload = {
568 "some": "payload",
569 "aud": ["urn:someone", "urn:someone-else"],
570 }
571
572 token = jwt.encode(payload, "secret")
573
574 with pytest.raises(InvalidAudienceError):
575 jwt.decode(token, "secret", audience="urn:me", algorithms=["HS256"])
576
577 def test_raise_exception_token_without_issuer(self, jwt: PyJWT) -> None:
578 issuer = "urn:wrong"
579
580 payload = {"some": "payload"}
581
582 token = jwt.encode(payload, "secret")
583
584 with pytest.raises(MissingRequiredClaimError) as exc:
585 jwt.decode(token, "secret", issuer=issuer, algorithms=["HS256"])
586
587 assert exc.value.claim == "iss"
588
589 def test_rasise_exception_on_partial_issuer_match(self, jwt: PyJWT) -> None:
590 issuer = "urn:expected"
591
592 payload = {"iss": "urn:"}
593
594 token = jwt.encode(payload, "secret")
595
596 with pytest.raises(InvalidIssuerError):
597 jwt.decode(token, "secret", issuer=issuer, algorithms=["HS256"])
598
599 def test_raise_exception_token_without_audience(self, jwt: PyJWT) -> None:
600 payload = {"some": "payload"}
601 token = jwt.encode(payload, "secret")
602
603 with pytest.raises(MissingRequiredClaimError) as exc:
604 jwt.decode(token, "secret", audience="urn:me", algorithms=["HS256"])
605
606 assert exc.value.claim == "aud"
607
608 def test_raise_exception_token_with_aud_none_and_without_audience(
609 self, jwt: PyJWT
610 ) -> None:
611 payload = {"some": "payload", "aud": None}
612 token = jwt.encode(payload, "secret")
613
614 with pytest.raises(MissingRequiredClaimError) as exc:
615 jwt.decode(token, "secret", audience="urn:me", algorithms=["HS256"])
616
617 assert exc.value.claim == "aud"
618
619 def test_check_issuer_when_valid(self, jwt: PyJWT) -> None:
620 issuer = "urn:foo"
621 payload = {"some": "payload", "iss": "urn:foo"}
622 token = jwt.encode(payload, "secret")
623 jwt.decode(token, "secret", issuer=issuer, algorithms=["HS256"])
624
625 def test_check_issuer_list_when_valid(self, jwt: PyJWT) -> None:
626 issuer = ["urn:foo", "urn:bar"]
627 payload = {"some": "payload", "iss": "urn:foo"}
628 token = jwt.encode(payload, "secret")
629 jwt.decode(token, "secret", issuer=issuer, algorithms=["HS256"])
630
631 def test_raise_exception_invalid_issuer(self, jwt: PyJWT) -> None:
632 issuer = "urn:wrong"
633
634 payload = {"some": "payload", "iss": "urn:foo"}
635
636 token = jwt.encode(payload, "secret")
637
638 with pytest.raises(InvalidIssuerError):
639 jwt.decode(token, "secret", issuer=issuer, algorithms=["HS256"])
640
641 def test_raise_exception_invalid_issuer_list(self, jwt: PyJWT) -> None:
642 issuer = ["urn:wrong", "urn:bar", "urn:baz"]
643
644 payload = {"some": "payload", "iss": "urn:foo"}
645
646 token = jwt.encode(payload, "secret")
647
648 with pytest.raises(InvalidIssuerError):
649 jwt.decode(token, "secret", issuer=issuer, algorithms=["HS256"])
650
651 def test_skip_check_audience(self, jwt: PyJWT) -> None:
652 payload = {"some": "payload", "aud": "urn:me"}
653 token = jwt.encode(payload, "secret")
654 jwt.decode(
655 token,
656 "secret",
657 options={"verify_aud": False},
658 algorithms=["HS256"],
659 )
660
661 def test_skip_check_exp(self, jwt: PyJWT) -> None:
662 payload = {
663 "some": "payload",
664 "exp": datetime.now(tz=timezone.utc) - timedelta(days=1),
665 }
666 token = jwt.encode(payload, "secret")
667 jwt.decode(
668 token,
669 "secret",
670 options={"verify_exp": False},
671 algorithms=["HS256"],
672 )
673
674 def test_decode_should_raise_error_if_exp_required_but_not_present(
675 self, jwt: PyJWT
676 ) -> None:
677 payload = {
678 "some": "payload",
679 # exp not present
680 }
681 token = jwt.encode(payload, "secret")
682
683 with pytest.raises(MissingRequiredClaimError) as exc:
684 jwt.decode(
685 token,
686 "secret",
687 options={"require": ["exp"]},
688 algorithms=["HS256"],
689 )
690
691 assert exc.value.claim == "exp"
692
693 def test_decode_should_raise_error_if_iat_required_but_not_present(
694 self, jwt: PyJWT
695 ) -> None:
696 payload = {
697 "some": "payload",
698 # iat not present
699 }
700 token = jwt.encode(payload, "secret")
701
702 with pytest.raises(MissingRequiredClaimError) as exc:
703 jwt.decode(
704 token,
705 "secret",
706 options={"require": ["iat"]},
707 algorithms=["HS256"],
708 )
709
710 assert exc.value.claim == "iat"
711
712 def test_decode_should_raise_error_if_nbf_required_but_not_present(
713 self, jwt: PyJWT
714 ) -> None:
715 payload = {
716 "some": "payload",
717 # nbf not present
718 }
719 token = jwt.encode(payload, "secret")
720
721 with pytest.raises(MissingRequiredClaimError) as exc:
722 jwt.decode(
723 token,
724 "secret",
725 options={"require": ["nbf"]},
726 algorithms=["HS256"],
727 )
728
729 assert exc.value.claim == "nbf"
730
731 def test_skip_check_signature(self, jwt: PyJWT) -> None:
732 token = (
733 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
734 ".eyJzb21lIjoicGF5bG9hZCJ9"
735 ".4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZA"
736 )
737 jwt.decode(
738 token,
739 "secret",
740 options={"verify_signature": False},
741 algorithms=["HS256"],
742 )
743
744 def test_skip_check_iat(self, jwt: PyJWT) -> None:
745 payload = {
746 "some": "payload",
747 "iat": datetime.now(tz=timezone.utc) + timedelta(days=1),
748 }
749 token = jwt.encode(payload, "secret")
750 jwt.decode(
751 token,
752 "secret",
753 options={"verify_iat": False},
754 algorithms=["HS256"],
755 )
756
757 def test_skip_check_nbf(self, jwt: PyJWT) -> None:
758 payload = {
759 "some": "payload",
760 "nbf": datetime.now(tz=timezone.utc) + timedelta(days=1),
761 }
762 token = jwt.encode(payload, "secret")
763 jwt.decode(
764 token,
765 "secret",
766 options={"verify_nbf": False},
767 algorithms=["HS256"],
768 )
769
770 def test_custom_json_encoder(self, jwt: PyJWT) -> None:
771 class CustomJSONEncoder(json.JSONEncoder):
772 def default(self, o: object) -> str:
773 assert isinstance(o, Decimal)
774 return "it worked"
775
776 data = {"some_decimal": Decimal("2.2")}
777
778 with pytest.raises(TypeError):
779 jwt.encode(data, "secret", algorithm="HS256")
780
781 token = jwt.encode(data, "secret", json_encoder=CustomJSONEncoder)
782 payload = jwt.decode(token, "secret", algorithms=["HS256"])
783
784 assert payload == {"some_decimal": "it worked"}
785
786 def test_decode_with_verify_exp_option(
787 self, jwt: PyJWT, payload: dict[str, object]
788 ) -> None:
789 payload["exp"] = utc_timestamp() - 1
790 secret = "secret"
791 jwt_message = jwt.encode(payload, secret)
792
793 jwt.decode(
794 jwt_message,
795 secret,
796 algorithms=["HS256"],
797 options={"verify_exp": False},
798 )
799
800 with pytest.raises(ExpiredSignatureError):
801 jwt.decode(
802 jwt_message,
803 secret,
804 algorithms=["HS256"],
805 options={"verify_exp": True},
806 )
807
808 def test_decode_with_verify_exp_option_and_signature_off(
809 self, jwt: PyJWT, payload: dict[str, object]
810 ) -> None:
811 payload["exp"] = utc_timestamp() - 1
812 secret = "secret"
813 jwt_message = jwt.encode(payload, secret)
814
815 jwt.decode(
816 jwt_message,
817 options={"verify_signature": False},
818 )
819
820 with pytest.raises(ExpiredSignatureError):
821 jwt.decode(
822 jwt_message,
823 options={"verify_signature": False, "verify_exp": True},
824 )
825
826 def test_decode_with_optional_algorithms(
827 self, jwt: PyJWT, payload: dict[str, object]
828 ) -> None:
829 secret = "secret"
830 jwt_message = jwt.encode(payload, secret)
831
832 with pytest.raises(DecodeError) as exc:
833 jwt.decode(jwt_message, secret)
834
835 assert (
836 'It is required that you pass in a value for the "algorithms" argument when calling decode().'
837 in str(exc.value)
838 )
839
840 def test_decode_no_algorithms_verify_signature_false(
841 self, jwt: PyJWT, payload: dict[str, object]
842 ) -> None:
843 secret = "secret"
844 jwt_message = jwt.encode(payload, secret)
845
846 jwt.decode(jwt_message, secret, options={"verify_signature": False})
847
848 def test_decode_legacy_verify_warning(
849 self, jwt: PyJWT, payload: dict[str, object]
850 ) -> None:
851 secret = "secret"
852 jwt_message = jwt.encode(payload, secret)
853
854 with pytest.deprecated_call():
855 # The implicit default for options.verify_signature is True,
856 # but the user sets verify to False.
857 jwt.decode(jwt_message, secret, verify=False, algorithms=["HS256"])
858
859 with pytest.deprecated_call():
860 # The user explicitly sets verify=True,
861 # but contradicts it in verify_signature.
862 jwt.decode(
863 jwt_message, secret, verify=True, options={"verify_signature": False}
864 )
865
866 def test_decode_no_options_mutation(
867 self, jwt: PyJWT, payload: dict[str, object]
868 ) -> None:
869 options: Options = {"verify_signature": True}
870 orig_options = options.copy()
871 secret = "secret"
872 jwt_message = jwt.encode(payload, secret)
873 jwt.decode(
874 jwt_message,
875 secret,
876 options=options,
877 algorithms=["HS256"],
878 )
879 assert options == orig_options
880
881 def test_decode_warns_on_unsupported_kwarg(
882 self, jwt: PyJWT, payload: dict[str, object]
883 ) -> None:
884 secret = "secret"
885 jwt_message = jwt.encode(payload, secret)
886
887 with pytest.warns(RemovedInPyjwt3Warning) as record:
888 jwt.decode(jwt_message, secret, algorithms=["HS256"], foo="bar")
889 deprecation_warnings = [
890 w for w in record if issubclass(w.category, RemovedInPyjwt3Warning)
891 ]
892 assert len(deprecation_warnings) == 1
893 assert "foo" in str(deprecation_warnings[0].message)
894
895 def test_decode_complete_warns_on_unsupported_kwarg(
896 self, jwt: PyJWT, payload: dict[str, object]
897 ) -> None:
898 secret = "secret"
899 jwt_message = jwt.encode(payload, secret)
900
901 with pytest.warns(RemovedInPyjwt3Warning) as record:
902 jwt.decode_complete(jwt_message, secret, algorithms=["HS256"], foo="bar")
903 deprecation_warnings = [
904 w for w in record if issubclass(w.category, RemovedInPyjwt3Warning)
905 ]
906 assert len(deprecation_warnings) == 1
907 assert "foo" in str(deprecation_warnings[0].message)
908
909 def test_decode_strict_aud_forbids_list_audience(
910 self, jwt: PyJWT, payload: dict[str, object]
911 ) -> None:
912 secret = "secret"
913 payload["aud"] = "urn:foo"
914 jwt_message = jwt.encode(payload, secret)
915
916 # Decodes without `strict_aud`.
917 jwt.decode(
918 jwt_message,
919 secret,
920 audience=["urn:foo", "urn:bar"],
921 options={"strict_aud": False},
922 algorithms=["HS256"],
923 )
924
925 # Fails with `strict_aud`.
926 with pytest.raises(InvalidAudienceError, match=r"Invalid audience \(strict\)"):
927 jwt.decode(
928 jwt_message,
929 secret,
930 audience=["urn:foo", "urn:bar"],
931 options={"strict_aud": True},
932 algorithms=["HS256"],
933 )
934
935 def test_decode_strict_aud_forbids_list_claim(
936 self, jwt: PyJWT, payload: dict[str, object]
937 ) -> None:
938 secret = "secret"
939 payload["aud"] = ["urn:foo", "urn:bar"]
940 jwt_message = jwt.encode(payload, secret)
941
942 # Decodes without `strict_aud`.
943 jwt.decode(
944 jwt_message,
945 secret,
946 audience="urn:foo",
947 options={"strict_aud": False},
948 algorithms=["HS256"],
949 )
950
951 # Fails with `strict_aud`.
952 with pytest.raises(
953 InvalidAudienceError, match=r"Invalid claim format in token \(strict\)"
954 ):
955 jwt.decode(
956 jwt_message,
957 secret,
958 audience="urn:foo",
959 options={"strict_aud": True},
960 algorithms=["HS256"],
961 )
962
963 def test_decode_strict_aud_does_not_match(
964 self, jwt: PyJWT, payload: dict[str, object]
965 ) -> None:
966 secret = "secret"
967 payload["aud"] = "urn:foo"
968 jwt_message = jwt.encode(payload, secret)
969
970 with pytest.raises(
971 InvalidAudienceError, match=r"Audience doesn't match \(strict\)"
972 ):
973 jwt.decode(
974 jwt_message,
975 secret,
976 audience="urn:bar",
977 options={"strict_aud": True},
978 algorithms=["HS256"],
979 )
980
981 def test_decode_strict_ok(self, jwt: PyJWT, payload: dict[str, object]) -> None:
982 secret = "secret"
983 payload["aud"] = "urn:foo"
984 jwt_message = jwt.encode(payload, secret)
985
986 jwt.decode(
987 jwt_message,
988 secret,
989 audience="urn:foo",
990 options={"strict_aud": True},
991 algorithms=["HS256"],
992 )
993
994 # -------------------- Sub Claim Tests --------------------
995
996 def test_encode_decode_sub_claim(self, jwt: PyJWT) -> None:
997 payload = {
998 "sub": "user123",
999 }
1000 secret = "your-256-bit-secret"
1001 token = jwt.encode(payload, secret, algorithm="HS256")
1002 decoded = jwt.decode(token, secret, algorithms=["HS256"])
1003
1004 assert decoded["sub"] == "user123"
1005
1006 def test_decode_without_and_not_required_sub_claim(self, jwt: PyJWT) -> None:
1007 secret = "your-256-bit-secret"
1008 token = jwt.encode({}, secret, algorithm="HS256")
1009
1010 decoded = jwt.decode(token, secret, algorithms=["HS256"])
1011
1012 assert "sub" not in decoded
1013
1014 def test_decode_missing_sub_but_required_claim(self, jwt: PyJWT) -> None:
1015 secret = "your-256-bit-secret"
1016 token = jwt.encode({}, secret, algorithm="HS256")
1017
1018 with pytest.raises(MissingRequiredClaimError):
1019 jwt.decode(
1020 token, secret, algorithms=["HS256"], options={"require": ["sub"]}
1021 )
1022
1023 def test_decode_invalid_int_sub_claim(self, jwt: PyJWT) -> None:
1024 payload = {
1025 "sub": 1224344,
1026 }
1027 secret = "your-256-bit-secret"
1028 token = jwt.encode(payload, secret, algorithm="HS256")
1029
1030 with pytest.raises(InvalidSubjectError):
1031 jwt.decode(token, secret, algorithms=["HS256"])
1032
1033 def test_decode_with_valid_sub_claim(self, jwt: PyJWT) -> None:
1034 payload = {
1035 "sub": "user123",
1036 }
1037 secret = "your-256-bit-secret"
1038 token = jwt.encode(payload, secret, algorithm="HS256")
1039
1040 decoded = jwt.decode(token, secret, algorithms=["HS256"], subject="user123")
1041
1042 assert decoded["sub"] == "user123"
1043
1044 def test_decode_with_invalid_sub_claim(self, jwt: PyJWT) -> None:
1045 payload = {
1046 "sub": "user123",
1047 }
1048 secret = "your-256-bit-secret"
1049 token = jwt.encode(payload, secret, algorithm="HS256")
1050
1051 with pytest.raises(InvalidSubjectError) as exc_info:
1052 jwt.decode(token, secret, algorithms=["HS256"], subject="user456")
1053
1054 assert "Invalid subject" in str(exc_info.value)
1055
1056 def test_decode_with_sub_claim_and_none_subject(self, jwt: PyJWT) -> None:
1057 payload = {
1058 "sub": "user789",
1059 }
1060 secret = "your-256-bit-secret"
1061 token = jwt.encode(payload, secret, algorithm="HS256")
1062
1063 decoded = jwt.decode(token, secret, algorithms=["HS256"], subject=None)
1064 assert decoded["sub"] == "user789"
1065
1066 # -------------------- JTI Claim Tests --------------------
1067
1068 def test_encode_decode_with_valid_jti_claim(self, jwt: PyJWT) -> None:
1069 payload = {
1070 "jti": "unique-id-456",
1071 }
1072 secret = "your-256-bit-secret"
1073 token = jwt.encode(payload, secret, algorithm="HS256")
1074 decoded = jwt.decode(token, secret, algorithms=["HS256"])
1075
1076 assert decoded["jti"] == "unique-id-456"
1077
1078 def test_decode_missing_jti_when_required_claim(self, jwt: PyJWT) -> None:
1079 payload = {"name": "Bob", "admin": False}
1080 secret = "your-256-bit-secret"
1081 token = jwt.encode(payload, secret, algorithm="HS256")
1082
1083 with pytest.raises(MissingRequiredClaimError) as exc_info:
1084 jwt.decode(
1085 token, secret, algorithms=["HS256"], options={"require": ["jti"]}
1086 )
1087
1088 assert "jti" in str(exc_info.value)
1089
1090 def test_decode_missing_jti_claim(self, jwt: PyJWT) -> None:
1091 secret = "your-256-bit-secret"
1092 token = jwt.encode({}, secret, algorithm="HS256")
1093
1094 decoded = jwt.decode(token, secret, algorithms=["HS256"])
1095
1096 assert decoded.get("jti") is None
1097
1098 def test_jti_claim_with_invalid_int_value(self, jwt: PyJWT) -> None:
1099 special_jti = 12223
1100 payload = {
1101 "jti": special_jti,
1102 }
1103 secret = "your-256-bit-secret"
1104 token = jwt.encode(payload, secret, algorithm="HS256")
1105
1106 with pytest.raises(InvalidJTIError):
1107 jwt.decode(token, secret, algorithms=["HS256"])
1108
1109 def test_validate_iss_with_container_of_str(self, jwt: PyJWT) -> None:
1110 """Check _validate_iss works with Container[str]."""
1111 payload = {
1112 "iss": "urn:expected",
1113 }
1114 # pytest.mark.parametrize triggers Untyped Decorator mypy issue,
1115 # so trying inline for now
1116 for issuer in (
1117 ["urn:expected", "urn:other"],
1118 ("urn:expected", "urn:other"),
1119 {"urn:expected", "urn:other"},
1120 ):
1121 jwt._validate_iss(payload, issuer=issuer)
1122
1123 def test_validate_iss_with_non_str(self, jwt: PyJWT) -> None:
1124 """Regression test for #1039"""
1125 payload = {
1126 "iss": 123,
1127 }
1128 with pytest.raises(InvalidIssuerError):
1129 jwt._validate_iss(payload, issuer="123")
1130
1131 def test_validate_iss_with_non_str_issuer(self, jwt: PyJWT) -> None:
1132 """Regression test for #1039"""
1133 payload = {
1134 "iss": "123",
1135 }
1136 with pytest.raises(InvalidIssuerError):
1137 jwt._validate_iss(
1138 payload,
1139 issuer=123, # type: ignore[arg-type]
1140 )
1141
1142 # -------------------- Crit Header Tests --------------------
1143
1144 def test_decode_rejects_token_with_unknown_crit_extension(self, jwt: PyJWT) -> None:
1145 """RFC 7515 §4.1.11: tokens with unsupported critical extensions MUST be rejected."""
1146 from jwt.exceptions import InvalidTokenError
1147
1148 secret = "secret"
1149 payload = {"sub": "attacker", "role": "admin"}
1150 token = jwt.encode(
1151 payload,
1152 secret,
1153 algorithm="HS256",
1154 headers={"crit": ["x-custom-policy"], "x-custom-policy": "require-mfa"},
1155 )
1156
1157 with pytest.raises(InvalidTokenError, match="Unsupported critical extension"):
1158 jwt.decode(token, secret, algorithms=["HS256"])