Debian Codegraph @

tests/test_api_jwt.py

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