Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/auth0/authentication/token_verifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 RSA 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(
Expand Down
160 changes: 159 additions & 1 deletion tests/authentication/test_token_verifier.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import base64
import json
import time
import unittest
from unittest.mock import MagicMock, patch
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,
Expand All @@ -30,6 +33,44 @@
"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"}
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,
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"
Expand Down Expand Up @@ -135,6 +176,52 @@ 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 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"
Expand Down Expand Up @@ -307,6 +394,42 @@ 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):
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"

Expand Down Expand Up @@ -592,3 +715,38 @@ 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)

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)
Loading