From cdd6d0e90d69591a9ea7fd43b0726e2805888974 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Thu, 3 Dec 2026 19:00:44 +0100 Subject: [PATCH 1/2] fix: ignore non-RSA keys when parsing the JWKS in the token verifier JwksFetcher._parse_jwks converted every key in the JWKS with the RSA key parser. A JWKS that also contained a key of another type (for example EC or OKP) made PyJWT raise "Not an RSA key", which made the synchronous verifier fail for every token, including RS256 tokens signed with a valid RSA key in the same set. The async verifier swallowed the error and reported "RSA Public Key with ID ... was not found" for every key id. Only keys with kty "RSA" are parsed now, other keys are skipped. Requesting a key id that belongs to a skipped key still fails with the existing "was not found" error. Co-Authored-By: Claude --- src/auth0/authentication/token_verifier.py | 7 +- tests/authentication/test_token_verifier.py | 113 +++++++++++++++++++- 2 files changed, 118 insertions(+), 2 deletions(-) diff --git a/src/auth0/authentication/token_verifier.py b/src/auth0/authentication/token_verifier.py index 4c0864ec..97e9fefe 100644 --- a/src/auth0/authentication/token_verifier.py +++ b/src/auth0/authentication/token_verifier.py @@ -195,11 +195,16 @@ def _fetch_jwks(self, force: bool = False) -> dict[str, RSAPublicKey]: @staticmethod def _parse_jwks(jwks: dict[str, Any]) -> dict[str, RSAPublicKey]: """ - Converts a JWK string representation into a binary certificate in PEM format. + Converts the RSA keys of a JWK set into public keys, indexed by key id. + Keys of any other type (for example EC or post-quantum keys) are ignored, + as they cannot be used to verify RS256 signatures and must not prevent the RSA keys from being used. """ keys: dict[str, RSAPublicKey] = {} for key in jwks["keys"]: + if key.get("kty") != "RSA": + continue + # noinspection PyUnresolvedReferences # requirement already includes cryptography -> pyjwt[crypto] rsa_key: RSAPublicKey = jwt.algorithms.RSAAlgorithm.from_jwk( diff --git a/tests/authentication/test_token_verifier.py b/tests/authentication/test_token_verifier.py index 783b248c..b2a91c60 100644 --- a/tests/authentication/test_token_verifier.py +++ b/tests/authentication/test_token_verifier.py @@ -1,7 +1,8 @@ +import base64 import json import time import unittest -from unittest.mock import MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import jwt @@ -12,6 +13,7 @@ SymmetricSignatureVerifier, TokenVerifier, ) +from auth0.authentication.async_token_verifier import AsyncJwksFetcher from auth0.authentication.exceptions import TokenValidationError RSA_PUB_KEY_1_PEM = b"""-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuGbXWiK3dQTyCbX5xdE4\nyCuYp0AF2d15Qq1JSXT/lx8CEcXb9RbDddl8jGDv+spi5qPa8qEHiK7FwV2KpRE9\n83wGPnYsAm9BxLFb4YrLYcDFOIGULuk2FtrPS512Qea1bXASuvYXEpQNpGbnTGVs\nWXI9C+yjHztqyL2h8P6mlThPY9E9ue2fCqdgixfTFIF9Dm4SLHbphUS2iw7w1JgT\n69s7of9+I9l5lsJ9cozf1rxrXX4V1u/SotUuNB3Fp8oB4C1fLBEhSlMcUJirz1E8\nAziMCxS+VrRPDM+zfvpIJg3JljAh3PJHDiLu902v9w+Iplu1WyoB2aPfitxEhRN0\nYwIDAQAB\n-----END PUBLIC KEY-----\n""" @@ -30,6 +32,26 @@ "e": "AQAB", "kid": "test-key-2", } +# Keys a JWKS may contain next to RSA keys, e.g. a post-quantum ML-DSA key (RFC 9964, kty "AKP") +AKP_PUB_KEY_JWK = { + "kty": "AKP", + "alg": "ML-DSA-65", + "use": "sig", + "pub": base64.urlsafe_b64encode(bytes(1952)).rstrip(b"=").decode(), + "kid": "test-key-akp", +} +EC_PUB_KEY_JWK = { + "kty": "EC", + "crv": "P-256", + "use": "sig", + "x": "UqYdTwmKlGfilKSH44lnBjr1C2LVK94fj6WLcFk-mD0", + "y": "0o2Lbv6OdAVYZuK6gVrlSy16aKp9VwVOXGvaQHirayo", + "kid": "test-key-ec", +} +UNKNOWN_KTY_JWK = {"kty": "XYZ", "use": "sig", "kid": "test-key-unknown"} +JWKS_RESPONSE_MIXED_KEYS = { + "keys": [AKP_PUB_KEY_JWK, EC_PUB_KEY_JWK, UNKNOWN_KTY_JWK, RSA_PUB_KEY_1_JWK] +} JWKS_RESPONSE_SINGLE_KEY = {"keys": [RSA_PUB_KEY_1_JWK]} JWKS_RESPONSE_MULTIPLE_KEYS = {"keys": [RSA_PUB_KEY_1_JWK, RSA_PUB_KEY_2_JWK]} HMAC_SHARED_SECRET = "secret" @@ -135,6 +157,35 @@ def _get_pem_bytes(rsa_public_key): serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo ) + @patch("requests.get") + def test_get_key_ignores_keys_that_are_not_rsa(self, mock_get): + JWKS_URL = "https://app.myhosting.com/.well-known/jwks.json" + fetcher = JwksFetcher(JWKS_URL) + + mock_get.return_value.ok = True + mock_get.return_value.status_code = 200 + mock_get.return_value.json.return_value = JWKS_RESPONSE_MIXED_KEYS + + key_1 = fetcher.get_key("test-key-1") + + self.assertEqual(self._get_pem_bytes(key_1), RSA_PUB_KEY_1_PEM) + + @patch("requests.get") + def test_get_key_fails_with_not_found_for_a_key_that_is_not_rsa(self, mock_get): + JWKS_URL = "https://app.myhosting.com/.well-known/jwks.json" + fetcher = JwksFetcher(JWKS_URL) + + mock_get.return_value.ok = True + mock_get.return_value.status_code = 200 + mock_get.return_value.json.return_value = JWKS_RESPONSE_MIXED_KEYS + + for key_id in ("test-key-akp", "test-key-ec", "test-key-unknown"): + with self.assertRaises(TokenValidationError) as err: + fetcher.get_key(key_id) + self.assertEqual( + str(err.exception), f'RSA Public Key with ID "{key_id}" was not found.' + ) + @patch("requests.get") def test_get_jwks_json_twice_on_cache_expired(self, mock_get): JWKS_URL = "https://app.myhosting.com/.well-known/jwks.json" @@ -307,6 +358,44 @@ def test_err_token_format_invalid(self): token = "a.b.c.d" self.assert_fails_with_error(token, "token could not be decoded.") + @patch("requests.get") + def test_RS256_token_signature_passes_with_non_rsa_keys_in_jwks(self, mock_get): + from cryptography.hazmat.primitives.asymmetric import rsa + + private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + rsa_jwk = json.loads( + jwt.algorithms.RSAAlgorithm.to_jwk(private_key.public_key()) + ) + rsa_jwk.update({"use": "sig", "kid": "signing-key"}) + + mock_get.return_value.ok = True + mock_get.return_value.status_code = 200 + mock_get.return_value.json.return_value = { + "keys": [AKP_PUB_KEY_JWK, UNKNOWN_KTY_JWK, rsa_jwk] + } + + now = int(time.time()) + token = jwt.encode( + { + "iss": expectations["issuer"], + "sub": "auth0|123456789", + "aud": expectations["audience"], + "iat": now, + "exp": now + 600, + }, + private_key, + algorithm="RS256", + headers={"kid": "signing-key"}, + ) + + sv = AsymmetricSignatureVerifier("https://app.myhosting.com/.well-known/jwks.json") + tv = TokenVerifier( + signature_verifier=sv, + issuer=expectations["issuer"], + audience=expectations["audience"], + ) + tv.verify(token) + def test_HS256_token_signature_passes(self): token = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOlsidG9rZW5zLXRlc3QtMTIzIiwiZXh0ZXJuYWwtdGVzdC05OTkiXSwiZXhwIjoxNTg3NzY1MzYxLCJpYXQiOjE1ODc1OTI1NjEsIm5vbmNlIjoiYTFiMmMzZDRlNSIsImF6cCI6InRva2Vucy10ZXN0LTEyMyIsImF1dGhfdGltZSI6MTU4NzY3ODk2MX0.Hn38QVtN_mWN0c-jOa-Fqq69kXpbBp0THsvE-CQ47Ps" @@ -592,3 +681,25 @@ def test_verify_returns_payload(self): self.assertIn("exp", response) self.assertIn("iat", response) self.assertEqual("org_123", response["org_id"]) + + +class TestAsyncJwksFetcher(unittest.IsolatedAsyncioTestCase): + async def test_get_key_ignores_keys_that_are_not_rsa(self): + fetcher = AsyncJwksFetcher("https://app.myhosting.com/.well-known/jwks.json") + fetcher._async_client.get = AsyncMock(return_value=JWKS_RESPONSE_MIXED_KEYS) + + key_1 = await fetcher.get_key("test-key-1") + + self.assertEqual( + TestJwksFetcher._get_pem_bytes(key_1), RSA_PUB_KEY_1_PEM + ) + + async def test_get_key_fails_with_not_found_for_a_key_that_is_not_rsa(self): + fetcher = AsyncJwksFetcher("https://app.myhosting.com/.well-known/jwks.json") + fetcher._async_client.get = AsyncMock(return_value=JWKS_RESPONSE_MIXED_KEYS) + + with self.assertRaises(TokenValidationError) as err: + await fetcher.get_key("test-key-akp") + self.assertEqual( + str(err.exception), 'RSA Public Key with ID "test-key-akp" was not found.' + ) From dc8c0e5cc72fb394fe407b590a85f905cb2f56a4 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Thu, 3 Dec 2026 23:16:00 +0100 Subject: [PATCH 2/2] test: cover more JWKS keys the verifier cannot use Add a key without kty, a key with a lowercase kty (kty is case-sensitive) and a JWKS without any RSA key to the verifier tests, for both the sync and the async fetcher. Move the cryptography import to the top of the test module and put the async_token_verifier import in sorted order. The _parse_jwks docstring now says RSA signatures, as the verifier accepts any RSA algorithm. Co-Authored-By: Claude --- src/auth0/authentication/token_verifier.py | 2 +- tests/authentication/test_token_verifier.py | 57 +++++++++++++++++++-- 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/src/auth0/authentication/token_verifier.py b/src/auth0/authentication/token_verifier.py index 97e9fefe..c597bf74 100644 --- a/src/auth0/authentication/token_verifier.py +++ b/src/auth0/authentication/token_verifier.py @@ -197,7 +197,7 @@ def _parse_jwks(jwks: dict[str, Any]) -> dict[str, RSAPublicKey]: """ Converts the RSA keys of a JWK set into public keys, indexed by key id. Keys of any other type (for example EC or post-quantum keys) are ignored, - as they cannot be used to verify RS256 signatures and must not prevent the RSA keys from being used. + as they cannot be used to verify RSA signatures and must not prevent the RSA keys from being used. """ keys: dict[str, RSAPublicKey] = {} diff --git a/tests/authentication/test_token_verifier.py b/tests/authentication/test_token_verifier.py index b2a91c60..56f49e27 100644 --- a/tests/authentication/test_token_verifier.py +++ b/tests/authentication/test_token_verifier.py @@ -5,7 +5,9 @@ from unittest.mock import AsyncMock, MagicMock, patch import jwt +from cryptography.hazmat.primitives.asymmetric import rsa +from auth0.authentication.async_token_verifier import AsyncJwksFetcher from auth0.authentication.token_verifier import ( AsymmetricSignatureVerifier, JwksFetcher, @@ -13,7 +15,6 @@ SymmetricSignatureVerifier, TokenVerifier, ) -from auth0.authentication.async_token_verifier import AsyncJwksFetcher from auth0.authentication.exceptions import TokenValidationError RSA_PUB_KEY_1_PEM = b"""-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuGbXWiK3dQTyCbX5xdE4\nyCuYp0AF2d15Qq1JSXT/lx8CEcXb9RbDddl8jGDv+spi5qPa8qEHiK7FwV2KpRE9\n83wGPnYsAm9BxLFb4YrLYcDFOIGULuk2FtrPS512Qea1bXASuvYXEpQNpGbnTGVs\nWXI9C+yjHztqyL2h8P6mlThPY9E9ue2fCqdgixfTFIF9Dm4SLHbphUS2iw7w1JgT\n69s7of9+I9l5lsJ9cozf1rxrXX4V1u/SotUuNB3Fp8oB4C1fLBEhSlMcUJirz1E8\nAziMCxS+VrRPDM+zfvpIJg3JljAh3PJHDiLu902v9w+Iplu1WyoB2aPfitxEhRN0\nYwIDAQAB\n-----END PUBLIC KEY-----\n""" @@ -49,9 +50,27 @@ "kid": "test-key-ec", } UNKNOWN_KTY_JWK = {"kty": "XYZ", "use": "sig", "kid": "test-key-unknown"} +MISSING_KTY_JWK = {"use": "sig", "kid": "test-key-no-kty"} +# "kty" values are case-sensitive (RFC 7517 section 4.1), so this is not an RSA key +LOWERCASE_KTY_JWK = {**RSA_PUB_KEY_2_JWK, "kty": "rsa", "kid": "test-key-lowercase-kty"} JWKS_RESPONSE_MIXED_KEYS = { - "keys": [AKP_PUB_KEY_JWK, EC_PUB_KEY_JWK, UNKNOWN_KTY_JWK, RSA_PUB_KEY_1_JWK] + "keys": [ + AKP_PUB_KEY_JWK, + EC_PUB_KEY_JWK, + UNKNOWN_KTY_JWK, + MISSING_KTY_JWK, + LOWERCASE_KTY_JWK, + RSA_PUB_KEY_1_JWK, + ] } +JWKS_RESPONSE_NO_RSA_KEY = {"keys": [AKP_PUB_KEY_JWK, EC_PUB_KEY_JWK]} +SKIPPED_KEY_IDS = ( + "test-key-akp", + "test-key-ec", + "test-key-unknown", + "test-key-no-kty", + "test-key-lowercase-kty", +) JWKS_RESPONSE_SINGLE_KEY = {"keys": [RSA_PUB_KEY_1_JWK]} JWKS_RESPONSE_MULTIPLE_KEYS = {"keys": [RSA_PUB_KEY_1_JWK, RSA_PUB_KEY_2_JWK]} HMAC_SHARED_SECRET = "secret" @@ -179,13 +198,30 @@ def test_get_key_fails_with_not_found_for_a_key_that_is_not_rsa(self, mock_get): mock_get.return_value.status_code = 200 mock_get.return_value.json.return_value = JWKS_RESPONSE_MIXED_KEYS - for key_id in ("test-key-akp", "test-key-ec", "test-key-unknown"): + for key_id in SKIPPED_KEY_IDS: with self.assertRaises(TokenValidationError) as err: fetcher.get_key(key_id) self.assertEqual( str(err.exception), f'RSA Public Key with ID "{key_id}" was not found.' ) + @patch("requests.get") + def test_get_key_fails_with_not_found_when_the_jwks_has_no_rsa_key(self, mock_get): + JWKS_URL = "https://app.myhosting.com/.well-known/jwks.json" + fetcher = JwksFetcher(JWKS_URL) + + mock_get.return_value.ok = True + mock_get.return_value.status_code = 200 + mock_get.return_value.json.return_value = JWKS_RESPONSE_NO_RSA_KEY + + with self.assertRaises(TokenValidationError) as err: + fetcher.get_key("test-key-akp") + self.assertEqual( + str(err.exception), 'RSA Public Key with ID "test-key-akp" was not found.' + ) + # The JWKS was just fetched, so it is not fetched again when the key is not found + self.assertEqual(mock_get.call_count, 1) + @patch("requests.get") def test_get_jwks_json_twice_on_cache_expired(self, mock_get): JWKS_URL = "https://app.myhosting.com/.well-known/jwks.json" @@ -360,8 +396,6 @@ def test_err_token_format_invalid(self): @patch("requests.get") def test_RS256_token_signature_passes_with_non_rsa_keys_in_jwks(self, mock_get): - from cryptography.hazmat.primitives.asymmetric import rsa - private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) rsa_jwk = json.loads( jwt.algorithms.RSAAlgorithm.to_jwk(private_key.public_key()) @@ -698,8 +732,21 @@ async def test_get_key_fails_with_not_found_for_a_key_that_is_not_rsa(self): fetcher = AsyncJwksFetcher("https://app.myhosting.com/.well-known/jwks.json") fetcher._async_client.get = AsyncMock(return_value=JWKS_RESPONSE_MIXED_KEYS) + for key_id in SKIPPED_KEY_IDS: + with self.assertRaises(TokenValidationError) as err: + await fetcher.get_key(key_id) + self.assertEqual( + str(err.exception), f'RSA Public Key with ID "{key_id}" was not found.' + ) + + async def test_get_key_fails_with_not_found_when_the_jwks_has_no_rsa_key(self): + fetcher = AsyncJwksFetcher("https://app.myhosting.com/.well-known/jwks.json") + fetcher._async_client.get = AsyncMock(return_value=JWKS_RESPONSE_NO_RSA_KEY) + with self.assertRaises(TokenValidationError) as err: await fetcher.get_key("test-key-akp") self.assertEqual( str(err.exception), 'RSA Public Key with ID "test-key-akp" was not found.' ) + # The JWKS was just fetched, so it is not fetched again when the key is not found + self.assertEqual(fetcher._async_client.get.call_count, 1)