| 35 | |
| 36 | |
| 37 | class TestJWT: |
| 38 | def test_no_alg(self, claims, key): |
| 39 | token = jwt.encode(claims, key, algorithm="HS384") |
| 40 | b64header, b64payload, b64signature = token.split(".") |
| 41 | header_json = base64.urlsafe_b64decode(b64header.encode("utf-8")) |
| 42 | header = json.loads(header_json.decode("utf-8")) |
| 43 | del header["alg"] |
| 44 | bad_header_json_bytes = json.dumps(header).encode("utf-8") |
| 45 | bad_b64header_bytes = base64.urlsafe_b64encode(bad_header_json_bytes) |
| 46 | bad_b64header_bytes_short = bad_b64header_bytes.replace(b"=", b"") |
| 47 | bad_b64header = bad_b64header_bytes.decode("utf-8") |
| 48 | bad_token = ".".join([bad_b64header, b64payload, b64signature]) |
| 49 | with pytest.raises(JWTError): |
| 50 | jwt.decode(token=bad_token, key=key, algorithms=[]) |
| 51 | |
| 52 | @pytest.mark.parametrize( |
| 53 | "key, token", |
| 54 | [ |
| 55 | ( |
| 56 | "1234567890", |
| 57 | "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoidGVzdCJ9.aNBlulVhiYSCzvsh1rTzXZC2eWJmNrMBjINT-0wQz4k", |
| 58 | ), |
| 59 | ( |
| 60 | "123456789.0", |
| 61 | "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoidGVzdCJ9.D8WLFPMi3yKgua2jm3BKThFsParXpgxhIbsUc39zJDw", |
| 62 | ), |
| 63 | ], |
| 64 | ) |
| 65 | def test_numeric_key(self, key, token): |
| 66 | token_info = jwt.decode(token, key) |
| 67 | assert token_info == {"name": "test"} |
| 68 | |
| 69 | def test_invalid_claims_json(self): |
| 70 | old_jws_verify = jws.verify |
| 71 | try: |
| 72 | token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8" |
| 73 | |
| 74 | def return_invalid_json(token, key, algorithms, verify=True): |
| 75 | return b'["a", "b"}' |
| 76 | |
| 77 | jws.verify = return_invalid_json |
| 78 | |
| 79 | with pytest.raises(JWTError, match="Invalid payload string: "): |
| 80 | jwt.decode(token, "secret", ["HS256"]) |
| 81 | finally: |
| 82 | jws.verify = old_jws_verify |
| 83 | |
| 84 | def test_invalid_claims(self): |
| 85 | old_jws_verify = jws.verify |
| 86 | try: |
| 87 | token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8" |
| 88 | |
| 89 | def return_encoded_array(token, key, algorithms, verify=True): |
| 90 | return b'["a","b"]' |
| 91 | |
| 92 | jws.verify = return_encoded_array |
| 93 | |
| 94 | with pytest.raises(JWTError, match="Invalid payload string: must be a json object"): |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…