diff --git a/CHANGELOG.md b/CHANGELOG.md index a777931..691567b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,19 @@ # Change Log +## Unreleased + +**Changed** +- Migrated JOSE operations from `authlib.jose` to `joserfc` across all supported + Python versions (3.10+) and dropped the unused `authlib` dependency. +- Added configurable `jwt_algorithms` for access-token signatures (default + `RS256`); only recognized asymmetric algorithms are accepted, and JWKS `alg` + restrictions are enforced. +- Decoded access-token and DPoP claims are returned as plain dictionaries. + `joserfc` validates JOSE header names/types, header and payload sizes, and + key `use`, `key_ops`, and `alg` metadata more strictly than legacy Authlib. + Incompatible tokens or keys may require migration. +- Malformed DPoP proof payloads and unusable JWKS keys now raise SDK-specific + verification errors instead of exposing lower-level exceptions. + ## [1.0.0b11](https://github.com/auth0/auth0-api-python/tree/1.0.0b11) (2026-11-11) [Full Changelog](https://github.com/auth0/auth0-api-python/compare/1.0.0b10...1.0.0b11) diff --git a/README.md b/README.md index 395cf4f..2216483 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,33 @@ This SDK provides comprehensive support for securing APIs with Auth0-issued acce - **Framework Agnostic** - Works with FastAPI, Django, Flask, or any Python web framework ## Documentation +## JWT algorithms and `joserfc` validation + +Access-token verification accepts `RS256` by default. To allow another asymmetric +signature algorithm, supply `jwt_algorithms` when constructing `ApiClientOptions`: + +```python +ApiClientOptions( + domain="example.us.auth0.com", + audience="my-api", + jwt_algorithms=["RS256", "RS384"], +) +``` + +The list must be non-empty and contain supported `RS*`, `PS*`, or `ES*` algorithms. +Symmetric (`HS*`), unsigned (`none`), and unrecognized algorithms are rejected at +construction. The configuration is copied when the client is constructed. The JWT's +declared algorithm must also match any `alg` restriction set on the selected JWKS +key; configuring `RS384` does not override a key declared for `RS256`. A tenant +that issues RS384 tokens must publish an RS384-capable key. + +JOSE operations use `joserfc` directly. Decoded access-token and DPoP claims are +returned as plain dictionaries, and invalid key material produces SDK verification +errors. `joserfc` enforces strict validation of JOSE headers (including registered +header names and their types), encoded header/payload sizes, and JWK usage +restrictions (`use`, `key_ops`, and `alg`). DPoP remains restricted to `ES256` +regardless of `jwt_algorithms`. + - [Docs Site](https://auth0.com/docs) - explore our docs site and learn more about Auth0. diff --git a/poetry.lock b/poetry.lock index ce67897..fd42419 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,4 +1,4 @@ -# This file is automatically @generated by Poetry 2.3.4 and should not be changed by hand. +# This file is automatically @generated by Poetry 2.5.2 and should not be changed by hand. [[package]] name = "ada-url" @@ -101,22 +101,6 @@ files = [ [package.dependencies] typing-extensions = {version = ">=4", markers = "python_version < \"3.11\""} -[[package]] -name = "authlib" -version = "1.7.2" -description = "The ultimate Python library in building OAuth and OpenID Connect servers and clients." -optional = false -python-versions = ">=3.10" -groups = ["main"] -files = [ - {file = "authlib-1.7.2-py2.py3-none-any.whl", hash = "sha256:3e1faedc9d87e7d56a164eca3ccb6ace0d61b94abe83e92242f8dc8bba9b4a9f"}, - {file = "authlib-1.7.2.tar.gz", hash = "sha256:2cea25fefcd4e7173bdf1372c0afc265c8034b23a8cd5dcb6a9164b826c64231"}, -] - -[package.dependencies] -cryptography = "*" -joserfc = ">=1.6.0" - [[package]] name = "babel" version = "2.18.0" @@ -720,14 +704,14 @@ i18n = ["Babel (>=2.7)"] [[package]] name = "joserfc" -version = "1.7.4" +version = "1.7.7" description = "The ultimate Python library for JOSE RFCs, including JWS, JWE, JWK, JWA, JWT" optional = false python-versions = ">=3.10" groups = ["main"] files = [ - {file = "joserfc-1.7.4-py3-none-any.whl", hash = "sha256:32d46c2cd5e3203c13e87a6c61333cab310b1ba80cd54b4c4f386a848a122463"}, - {file = "joserfc-1.7.4.tar.gz", hash = "sha256:b3bc561672ae541b17a9237053b48a03dacddd92d68047b3ecdfb4b5714a88ed"}, + {file = "joserfc-1.7.7-py3-none-any.whl", hash = "sha256:06979cfbab78bc802f14c0358f32969826cc26720e13cb38926ffdc86bc0cb2c"}, + {file = "joserfc-1.7.7.tar.gz", hash = "sha256:471d0fd12a5a0d1c0942de280f39efe6f597878315033270b504d4d006d25510"}, ] [package.dependencies] @@ -1403,6 +1387,7 @@ description = "A lil' TOML parser" optional = false python-versions = ">=3.8" groups = ["dev", "docs"] +markers = "python_version == \"3.10\"" files = [ {file = "tomli-2.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30"}, {file = "tomli-2.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a"}, @@ -1452,7 +1437,6 @@ files = [ {file = "tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe"}, {file = "tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f"}, ] -markers = {dev = "python_full_version <= \"3.11.0a6\"", docs = "python_version == \"3.10\""} [[package]] name = "typing-extensions" @@ -1488,4 +1472,4 @@ zstd = ["backports-zstd (>=1.0.0) ; python_version < \"3.14\""] [metadata] lock-version = "2.1" python-versions = ">=3.10" -content-hash = "e82b0e3b2aeefe35847d90d33e6c76c0d8b756858551ea82e24a773670dc2af5" +content-hash = "1f81bd373be508843887fbf8bd4b15f8503e82515a33f0fc326d479459ada92c" diff --git a/pyproject.toml b/pyproject.toml index 23ef3a8..3f37733 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ packages = [ [tool.poetry.dependencies] python = ">=3.10" -authlib = "^1.0" # For JWT/OIDC features +joserfc = ">=1.7.6,<2.0" requests = "^2.31.0" # If you use requests for HTTP calls (e.g., discovery) httpx = "^0.28.1" cryptography = ">=43.0.1" diff --git a/requirements.txt b/requirements.txt index 34efe28..3eaa93b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ # This file is maintained manually for SCA scanning (.github/workflows/sca_scan.yml) # Source of truth for dependencies: pyproject.toml + poetry.lock -authlib>=1.6.12 +joserfc>=1.7.6,<2.0 httpx>=0.28.1 ada-url>=1.32.0 pytest>=8.0 diff --git a/src/auth0_api_python/api_client.py b/src/auth0_api_python/api_client.py index bf5e10d..648a4f6 100644 --- a/src/auth0_api_python/api_client.py +++ b/src/auth0_api_python/api_client.py @@ -6,7 +6,7 @@ from typing import Any import httpx -from authlib.jose import JsonWebKey, JsonWebToken +from joserfc import jwk, jwt from ._internal.cache_expiry import is_fresh from ._internal.cache_keys import m2m_cache_key @@ -51,6 +51,14 @@ logger = logging.getLogger(__name__) +# Access tokens must use a supported asymmetric signature algorithm. +# Never allow "none" (unsigned JWTs) or symmetric algorithms with public JWKS keys. +SUPPORTED_JWT_ALGORITHMS = frozenset({ + "RS256", "RS384", "RS512", + "PS256", "PS384", "PS512", + "ES256", "ES384", "ES512", +}) + # Token Exchange constants TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" # noqa: S105 OBO_ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" # noqa: S105 @@ -78,6 +86,17 @@ def __init__(self, options: ApiClientOptions): if not options.audience: raise MissingRequiredArgumentError("audience") + if not isinstance(options.jwt_algorithms, list) or not options.jwt_algorithms: + raise ConfigurationError("jwt_algorithms must be a non-empty list") + for algorithm in options.jwt_algorithms: + if not isinstance(algorithm, str) or algorithm not in SUPPORTED_JWT_ALGORITHMS: + raise ConfigurationError( + f"Unsupported JWT signing algorithm: {algorithm!r}. " + "Only RS*, PS*, and ES* asymmetric algorithms are supported." + ) + # Do not allow mutation of the caller's list to change accepted algorithms. + self._jwt_algorithms = list(options.jwt_algorithms) + # Validate domains parameter if provided if options.domains is not None: if isinstance(options.domains, list): @@ -190,10 +209,7 @@ def __init__(self, options: ApiClientOptions): self._cache_ttl = options.cache_ttl_seconds - self._jwt = JsonWebToken(["RS256"]) - self._dpop_algorithms = ["ES256"] - self._dpop_jwt = JsonWebToken(self._dpop_algorithms) def is_dpop_required(self) -> bool: """Check if DPoP authentication is required.""" @@ -481,7 +497,7 @@ async def verify_access_token( Asynchronously verifies the provided JWT access token. - Fetches OIDC metadata and JWKS if not already cached. - - Decodes and validates signature (RS256) with the correct key. + - Decodes and validates the signature with the configured jwt_algorithms (default RS256). - Checks standard claims: 'iss', 'aud', 'exp', 'nbf', 'iat' - Checks extra required claims if 'required_claims' is provided. - Enforces organization_policy: requires 'org_id' when set to "required", @@ -524,6 +540,8 @@ async def verify_access_token( f"Symmetric algorithm '{alg}' is not supported. " "Only asymmetric algorithms (e.g., RS256) are allowed." ) + if alg not in self._jwt_algorithms: + raise VerifyAccessTokenError(f"JWT signing algorithm '{alg}' is not allowed") # Extract and validate issuer claim (before network calls) try: @@ -610,13 +628,19 @@ async def verify_access_token( if not matching_key_dict: raise VerifyAccessTokenError("No matching key found in JWKS") - # Import public key and verify signature - public_key = JsonWebKey.import_key(matching_key_dict) + # Respect the key's declared algorithm so a JWKS key for RS256 cannot verify an RS384 token. + key_alg = matching_key_dict.get("alg") + if key_alg is not None and key_alg != alg: + raise VerifyAccessTokenError("JWT algorithm does not match JWKS key algorithm") if isinstance(access_token, str) and access_token.startswith("b'"): access_token = access_token[2:-1] try: - claims = self._jwt.decode(access_token, public_key) + public_key = jwk.import_key(matching_key_dict) + claims = jwt.decode(access_token, public_key, algorithms=self._jwt_algorithms).claims + if not isinstance(claims, dict): + raise ValueError("JWT payload is not a JSON object") + claims = dict(claims) except Exception as e: raise VerifyAccessTokenError(f"Signature verification failed: {str(e)}") from e @@ -712,15 +736,18 @@ async def verify_dpop_proof( raise InvalidDpopProofError("Only P-256 curve is supported") try: - public_key = JsonWebKey.import_key(jwk_dict) + public_key = jwk.import_key(jwk_dict) except Exception: raise InvalidDpopProofError("Missing or invalid jwk in header") try: - claims = self._dpop_jwt.decode(proof, public_key) + claims = jwt.decode(proof, public_key, algorithms=self._dpop_algorithms).claims except Exception as e: raise InvalidDpopProofError(f"JWT signature verification failed: {e}") + if not isinstance(claims, dict): + raise InvalidDpopProofError("DPoP proof payload must be a JSON object") + # Checks all required claims are present self._validate_claims_presence(claims, ["iat", "ath", "htm", "htu", "jti"]) diff --git a/src/auth0_api_python/config.py b/src/auth0_api_python/config.py index 31da638..ab96720 100644 --- a/src/auth0_api_python/config.py +++ b/src/auth0_api_python/config.py @@ -49,6 +49,9 @@ class ApiClientOptions: the request, and requires a token_store subclassing IndexedTokenStore (raises ConfigurationError at construction without one). client_info: Name, version and optional env of a wrapper SDK built on this one, as a dict with non-empty string "name" and "version" keys and an optional "env" dict of string keys and values. Sent in the Auth0-Client header. An invalid value raises ConfigurationError at construction, and the "python" and "auth0-api-python" entries in env are set by this SDK. + jwt_algorithms: Non-empty list of supported asymmetric JWT signing algorithms. + Defaults to ["RS256"]; unknown, symmetric, and unsigned algorithms + raise ConfigurationError at ApiClient construction. """ def __init__( self, @@ -71,10 +74,12 @@ def __init__( organization_id: str | list[str] | None = None, scope_matching: str = "strict", client_info: dict | None = None, + jwt_algorithms: list[str] | None = None, ): self.domain = domain self.domains = domains self.audience = audience + self.jwt_algorithms = ["RS256"] if jwt_algorithms is None else jwt_algorithms self.custom_fetch = custom_fetch self.cache_adapter = cache_adapter self.token_store = token_store diff --git a/src/auth0_api_python/token_utils.py b/src/auth0_api_python/token_utils.py index 515cc8c..2f27090 100644 --- a/src/auth0_api_python/token_utils.py +++ b/src/auth0_api_python/token_utils.py @@ -2,7 +2,9 @@ import uuid from typing import Any -from authlib.jose import JsonWebKey, jwt +from joserfc import jwk, jwt +from joserfc.jws import JWSRegistry +from joserfc.registry import HeaderParameter from .utils import calculate_jwk_thumbprint, normalize_url_for_htu, sha256_base64url @@ -33,9 +35,10 @@ async def generate_token( exp: bool = True, claims: dict[str, Any] | None = None, expiration_time: int = 3600, + algorithm: str = "RS256", ) -> str: """ - Generates a real RS256-signed JWT using the private key above. + Generates a signed JWT using the private key above. Args: domain: The Auth0 domain (used if issuer is not False). @@ -49,9 +52,10 @@ async def generate_token( exp: Whether to set the 'exp' claim. If False, skip it. claims: Additional custom claims to merge into the token. expiration_time: If exp is True, how many seconds from now until expiration. + algorithm: Signing algorithm (default RS256); tests may use RS384, for example. Returns: - A RS256-signed JWT string. + A signed JWT string. Example usage: token = generate_token( @@ -80,10 +84,11 @@ async def generate_token( token_claims["aud"] = audience - key = JsonWebKey.import_key(PRIVATE_JWK) + key_data = {**PRIVATE_JWK, "alg": algorithm} + key = jwk.import_key(key_data) - header = {"alg": "RS256", "kid": PRIVATE_JWK["kid"]} - token = jwt.encode(header, token_claims, key) + header = {"alg": algorithm, "kid": PRIVATE_JWK["kid"]} + token = jwt.encode(header, token_claims, key, algorithms=[algorithm]) # Ensure we return a string, not bytes return token.decode('utf-8') if isinstance(token, bytes) else token @@ -163,13 +168,20 @@ async def generate_dpop_proof( } + key = jwk.import_key(PRIVATE_EC_JWK) + if header_overrides: header.update(header_overrides) - - key = JsonWebKey.import_key(PRIVATE_EC_JWK) - token = jwt.encode(header, proof_claims, key) - # Ensure we return a string, not bytes - return token.decode('utf-8') if isinstance(token, bytes) else token + registry = JWSRegistry( + header_registry={ + name: HeaderParameter("header override", lambda _: None) + for name in header_overrides + } + ) + token = jwt.encode(header, proof_claims, key, registry=registry) + else: + token = jwt.encode(header, proof_claims, key) + return token.decode("utf-8") if isinstance(token, bytes) else token async def generate_token_with_cnf( diff --git a/tests/test_api_client.py b/tests/test_api_client.py index 35bc973..2d20281 100644 --- a/tests/test_api_client.py +++ b/tests/test_api_client.py @@ -3,6 +3,7 @@ import json import logging import time +from types import SimpleNamespace import httpx import pytest @@ -23,6 +24,7 @@ unsigned_jwt, ) from freezegun import freeze_time +from joserfc import jwk, jwt from pytest_httpx import HTTPXMock from auth0_api_python import ( @@ -87,6 +89,144 @@ async def test_init_missing_args(): _ = ApiClient(ApiClientOptions(domain="example.us.auth0.com", audience="")) +def test_custom_jwt_algorithms_are_copied(): + algorithms = ["RS384", "RS512"] + client = ApiClient(ApiClientOptions( + domain="example.us.auth0.com", + audience="my-audience", + jwt_algorithms=algorithms, + )) + assert client._jwt_algorithms == ["RS384", "RS512"] + algorithms.append("RS256") + assert client._jwt_algorithms == ["RS384", "RS512"] + + +@pytest.mark.parametrize("algorithms", [ + [], (), "RS256", [None], [""], [" "], ["FOO"], + ["none"], ["RS256", "none"], ["HS256"], ["RS256", 7], +]) +def test_reject_invalid_jwt_algorithms(algorithms): + with pytest.raises(ConfigurationError): + ApiClient(ApiClientOptions( + domain="example.us.auth0.com", + audience="my-audience", + jwt_algorithms=algorithms, + )) + + +@pytest.mark.asyncio +async def test_verify_access_token_rs384_requires_explicit_configuration(httpx_mock: HTTPXMock): + """A genuine RS384 signature is rejected by default, accepted when enabled.""" + token = await generate_token( + domain="auth0.local", user_id="user_123", + audience="my-audience", algorithm="RS384", + ) + httpx_mock.add_response( + method="GET", url=DISCOVERY_URL, + json={"issuer": "https://auth0.local/", "jwks_uri": JWKS_URL}, + ) + # A key without an 'alg' restriction may verify another RS* algorithm. + jwks_key = {key: value for key, value in PUBLIC_RSA_JWK.items() if key != "alg"} + httpx_mock.add_response(method="GET", url=JWKS_URL, json={"keys": [jwks_key]}) + default_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + with pytest.raises(VerifyAccessTokenError, match="not allowed"): + await default_client.verify_access_token(token) + + configured = ApiClient(ApiClientOptions( + domain="auth0.local", audience="my-audience", jwt_algorithms=["RS384"], + )) + claims = await configured.verify_access_token(token) + assert isinstance(claims, dict) + assert claims["sub"] == "user_123" + + +@pytest.mark.asyncio +async def test_verify_access_token_rejects_conflicting_jwks_key_algorithm(httpx_mock: HTTPXMock): + """JWKS key algorithm restrictions are enforced during access-token verification.""" + token = await generate_token( + domain="auth0.local", user_id="user_123", + audience="my-audience", algorithm="RS384", + ) + httpx_mock.add_response( + method="GET", url=DISCOVERY_URL, + json={"issuer": "https://auth0.local/", "jwks_uri": JWKS_URL}, + ) + httpx_mock.add_response(method="GET", url=JWKS_URL, json={"keys": [PUBLIC_RSA_JWK]}) + client = ApiClient(ApiClientOptions( + domain="auth0.local", audience="my-audience", jwt_algorithms=["RS384"], + )) + with pytest.raises(VerifyAccessTokenError, match="JWKS key algorithm"): + await client.verify_access_token(token) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("key_changes", [ + {"n": None}, + {"key_ops": ["encrypt"]}, +]) +async def test_verify_access_token_bad_jwks_key_raises_sdk_error(httpx_mock: HTTPXMock, key_changes): + """Malformed or unusable JWKS material never leaks a JOSE exception.""" + token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience") + httpx_mock.add_response( + method="GET", url=DISCOVERY_URL, + json={"issuer": "https://auth0.local/", "jwks_uri": JWKS_URL}, + ) + bad_key = {**PUBLIC_RSA_JWK, **key_changes} + if bad_key.get("n") is None: + bad_key.pop("n", None) + httpx_mock.add_response(method="GET", url=JWKS_URL, json={"keys": [bad_key]}) + client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + with pytest.raises(VerifyAccessTokenError): + await client.verify_access_token(token) + + +@pytest.mark.asyncio +async def test_unsigned_jwt_is_never_supported(): + """The none algorithm must be rejected even before a JWKS lookup.""" + client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + unsigned = unsigned_jwt( + {"alg": "none", "kid": "TEST_KEY"}, + {"iss": "https://auth0.local/", "aud": "my-audience"}, + ) + with pytest.raises(VerifyAccessTokenError, match="not allowed"): + await client.verify_access_token(unsigned) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("payload", [5, None, True, "not-an-object"]) +async def test_verify_dpop_proof_rejects_non_object_decoded_payload(payload, monkeypatch): + """A decoded non-object must be reported as InvalidDpopProofError, not TypeError.""" + token = "test_token" + proof = await generate_dpop_proof( + access_token=token, http_method="GET", http_url="https://api.example.com/resource", + ) + client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + monkeypatch.setattr( + "auth0_api_python.api_client.jwt.decode", + lambda *_args, **_kwargs: SimpleNamespace(claims=payload), + ) + with pytest.raises(InvalidDpopProofError, match="JSON object"): + await client.verify_dpop_proof( + access_token=token, proof=proof, + http_method="GET", http_url="https://api.example.com/resource", + ) + + +@pytest.mark.asyncio +async def test_generate_dpop_proof_header_overrides_preserve_valid_signature(): + """header_overrides are signed into the proof rather than mutating the header post-signing.""" + proof = await generate_dpop_proof( + access_token="test_token", + http_method="GET", + http_url="https://api.example.com/resource", + header_overrides={"typ": "jwt"}, + ) + public_key = jwk.import_key({k: v for k, v in PRIVATE_EC_JWK.items() if k != "d"}) + decoded = jwt.decode(proof, public_key, algorithms=["ES256"]) + assert decoded.header["typ"] == "jwt" + assert decoded.claims["htm"] == "GET" + + @pytest.mark.asyncio async def test_verify_access_token_successfully(httpx_mock: HTTPXMock): """