From 1c9d3c093501e3a841c8a6ba2a572f7ef49a855c Mon Sep 17 00:00:00 2001 From: Snehil Kishore Date: Tue, 27 Oct 2026 20:23:55 +0530 Subject: [PATCH 1/4] fix: reject malformed token and DPoP proof input with SDK errors --- src/auth0_api_python/_internal/cache_keys.py | 3 - src/auth0_api_python/api_client.py | 28 ++- src/auth0_api_python/encryption.py | 2 + src/auth0_api_python/utils.py | 16 +- tests/conftest.py | 10 + tests/test_api_client.py | 212 ++++++++++++++++++- tests/test_token_store.py | 18 ++ tests/test_utils.py | 36 ++++ 8 files changed, 313 insertions(+), 12 deletions(-) diff --git a/src/auth0_api_python/_internal/cache_keys.py b/src/auth0_api_python/_internal/cache_keys.py index 414cb72..f998706 100644 --- a/src/auth0_api_python/_internal/cache_keys.py +++ b/src/auth0_api_python/_internal/cache_keys.py @@ -33,9 +33,6 @@ def session_fingerprint(access_token: str) -> str: except ValueError: return hashlib.sha256(access_token.encode()).hexdigest() - if not isinstance(payload, dict): - return hashlib.sha256(access_token.encode()).hexdigest() - sid = payload.get("sid") if isinstance(sid, str) and sid: return sid diff --git a/src/auth0_api_python/api_client.py b/src/auth0_api_python/api_client.py index 23c7daf..d9c9c16 100644 --- a/src/auth0_api_python/api_client.py +++ b/src/auth0_api_python/api_client.py @@ -1,5 +1,6 @@ import asyncio import logging +import math import time from collections.abc import Mapping, Sequence from typing import Any, Optional, Union @@ -508,6 +509,8 @@ async def verify_access_token( # Reject symmetric algorithms alg = header.get('alg', '') + if not isinstance(alg, str): + raise VerifyAccessTokenError("Token header 'alg' must be a string") if alg.startswith('HS'): raise VerifyAccessTokenError( f"Symmetric algorithm '{alg}' is not supported. " @@ -626,11 +629,16 @@ async def verify_access_token( raise VerifyAccessTokenError("Audience mismatch (single aud)") now = int(time.time()) - if "exp" not in claims or now >= claims["exp"]: + if "exp" not in claims: + raise VerifyAccessTokenError("Token is expired") + exp = claims["exp"] + if isinstance(exp, bool) or not isinstance(exp, (int, float)) or (isinstance(exp, float) and not math.isfinite(exp)): + raise VerifyAccessTokenError("Invalid 'exp' claim in token") + if now >= exp: raise VerifyAccessTokenError("Token is expired") nbf = claims.get("nbf") if nbf is not None: - if isinstance(nbf, bool) or not isinstance(nbf, (int, float)): + if isinstance(nbf, bool) or not isinstance(nbf, (int, float)) or (isinstance(nbf, float) and not math.isfinite(nbf)): raise VerifyAccessTokenError("Invalid 'nbf' claim in token") if now < nbf: raise VerifyAccessTokenError("Token is not yet valid") @@ -675,7 +683,10 @@ async def verify_dpop_proof( if not http_method or not http_url: raise MissingRequiredArgumentError("http_method/http_url") - header = get_unverified_header(proof) + try: + header = get_unverified_header(proof) + except Exception: + raise InvalidDpopProofError("Failed to parse DPoP proof header") if header.get("typ") != "dpop+jwt": raise InvalidDpopProofError("Unexpected JWT 'typ' header parameter value") @@ -697,7 +708,11 @@ async def verify_dpop_proof( if jwk_dict.get("crv") != "P-256": raise InvalidDpopProofError("Only P-256 curve is supported") - public_key = JsonWebKey.import_key(jwk_dict) + try: + public_key = JsonWebKey.import_key(jwk_dict) + except Exception: + raise InvalidDpopProofError("Missing or invalid jwk in header") + try: claims = self._dpop_jwt.decode(proof, public_key) except Exception as e: @@ -720,7 +735,7 @@ async def verify_dpop_proof( offset = getattr(self.options, "dpop_iat_offset", 300) # default 5 minutes leeway = getattr(self.options, "dpop_iat_leeway", 30) # default 30 seconds - if not isinstance(iat, (int, float)): + if not isinstance(iat, (int, float)) or (isinstance(iat, float) and not math.isfinite(iat)): raise InvalidDpopProofError("Invalid iat claim (must be integer or float)") if iat < now - offset: @@ -728,6 +743,9 @@ async def verify_dpop_proof( elif iat > now + leeway: raise InvalidDpopProofError("DPoP Proof iat is from the future") + if not isinstance(claims["htm"], str): + raise InvalidDpopProofError("htm claim must be a string") + if claims["htm"].lower() != http_method.lower(): raise InvalidDpopProofError("DPoP Proof htm mismatch") diff --git a/src/auth0_api_python/encryption.py b/src/auth0_api_python/encryption.py index 0363889..760eb2a 100644 --- a/src/auth0_api_python/encryption.py +++ b/src/auth0_api_python/encryption.py @@ -34,6 +34,8 @@ def _read_jwe_kid(token: str) -> str: if padding != 4: header_b64 += "=" * padding header = json.loads(base64.urlsafe_b64decode(header_b64)) + if not isinstance(header, dict): + raise ValueError("Invalid JWE header: not a JSON object") kid = header.get("kid") if not kid: raise ValueError('Missing "kid" in JWE header') diff --git a/src/auth0_api_python/utils.py b/src/auth0_api_python/utils.py index 981c9ea..cb18750 100644 --- a/src/auth0_api_python/utils.py +++ b/src/auth0_api_python/utils.py @@ -167,7 +167,7 @@ def _decode_jwt_segment(token: Union[str, bytes], segment_index: int) -> dict: Decoded segment as dictionary Raises: - ValueError: If token format is invalid + ValueError: If token format is invalid, or the segment is not a JSON object or is nested too deeply """ if isinstance(token, bytes): token = token.decode("utf-8") @@ -181,7 +181,13 @@ def _decode_jwt_segment(token: Union[str, bytes], segment_index: int) -> dict: segment_b64 = fix_base64_padding(segment_b64) segment_data = base64.urlsafe_b64decode(segment_b64) - return json.loads(segment_data) + try: + segment = json.loads(segment_data) + except RecursionError: + raise ValueError("Invalid token format: segment is nested too deeply") from None + if not isinstance(segment, dict): + raise ValueError("Invalid token format: segment is not a JSON object") + return segment def get_unverified_header(token: Union[str, bytes]) -> dict: @@ -193,6 +199,9 @@ def get_unverified_header(token: Union[str, bytes]) -> dict: Returns: Decoded header as dictionary + + Raises: + ValueError: If the token is malformed or its header is not a JSON object or is nested too deeply """ return _decode_jwt_segment(token, 0) @@ -206,6 +215,9 @@ def get_unverified_payload(token: Union[str, bytes]) -> dict: Returns: Decoded payload (claims) as dictionary + + Raises: + ValueError: If the token is malformed or its payload is not a JSON object or is nested too deeply """ return _decode_jwt_segment(token, 1) diff --git a/tests/conftest.py b/tests/conftest.py index fb5badf..57943d9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,7 @@ """Shared test fixtures and helpers for auth0-api-python tests.""" import base64 +import json import time import urllib.parse from typing import Optional @@ -98,6 +99,15 @@ def mock_discovery(httpx_mock: HTTPXMock): # ===== Helper Functions ===== +def unsigned_jwt(header, payload) -> str: + """Build a JWT-shaped string from any JSON values, with a dummy signature.""" + + def encode(value): + return base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip("=") + + return f"{encode(header)}.{encode(payload)}.signature" + + def last_form(httpx_mock: HTTPXMock) -> dict[str, list[str]]: """Helper to read the last posted form data.""" req = httpx_mock.get_requests()[-1] diff --git a/tests/test_api_client.py b/tests/test_api_client.py index 3073b50..bbd82df 100644 --- a/tests/test_api_client.py +++ b/tests/test_api_client.py @@ -19,6 +19,7 @@ assert_no_requests, last_form, token_success, + unsigned_jwt, ) from freezegun import freeze_time from pytest_httpx import HTTPXMock @@ -514,15 +515,32 @@ async def test_verify_access_token_fail_fractional_nbf_in_future(httpx_mock: HTT @pytest.mark.asyncio -@pytest.mark.parametrize("bad_nbf", ["soon", True, [1]]) +@pytest.mark.parametrize("bad_nbf", ["soon", True, [1], float("nan"), float("-inf")]) async def test_verify_access_token_fail_non_numeric_nbf(httpx_mock: HTTPXMock, bad_nbf): - """A non-numeric 'nbf' is rejected as an invalid token.""" + """A non-numeric or non-finite 'nbf' is rejected as an invalid token.""" with pytest.raises(VerifyAccessTokenError) as err: await _verify_with_nbf(httpx_mock, bad_nbf) assert "nbf" in str(err.value) +@pytest.mark.asyncio +@pytest.mark.parametrize("bad_exp", ["9999999999", True, False, [1], None, float("nan"), float("inf")]) +async def test_verify_access_token_fail_invalid_exp(httpx_mock: HTTPXMock, bad_exp): + """A non-numeric or non-finite 'exp' is rejected as an invalid token.""" + 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]}) + access_token = await generate_token( + domain="auth0.local", user_id="user_123", audience="my-audience", exp=False, claims={"exp": bad_exp} + ) + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + + with pytest.raises(VerifyAccessTokenError) as err: + await api_client.verify_access_token(access_token=access_token) + + assert "Invalid 'exp' claim" in str(err.value) + + @pytest.mark.asyncio async def test_verify_access_token_fail_no_audience_config(): """ @@ -555,6 +573,34 @@ async def test_verify_access_token_fail_malformed_token(): assert "failed to parse token" in str(e.value).lower() +@pytest.mark.asyncio +@pytest.mark.parametrize("header,payload,message", [ + ([1], {"iss": "https://auth0.local/"}, "failed to parse token header"), + ("text", {"iss": "https://auth0.local/"}, "failed to parse token header"), + (5, {"iss": "https://auth0.local/"}, "failed to parse token header"), + (None, {"iss": "https://auth0.local/"}, "failed to parse token header"), + (True, {"iss": "https://auth0.local/"}, "failed to parse token header"), + ({"alg": 5}, {"iss": "https://auth0.local/"}, "'alg'"), + ({"alg": None}, {"iss": "https://auth0.local/"}, "'alg'"), + ({"alg": ["RS256"]}, {"iss": "https://auth0.local/"}, "'alg'"), + ({"alg": {"a": 1}}, {"iss": "https://auth0.local/"}, "'alg'"), + ({"alg": True}, {"iss": "https://auth0.local/"}, "'alg'"), + ({"alg": "RS256"}, [1], "failed to parse token payload"), + ({"alg": "RS256"}, "text", "failed to parse token payload"), + ({"alg": "RS256"}, 5, "failed to parse token payload"), + ({"alg": "RS256"}, None, "failed to parse token payload"), + ({"alg": "RS256"}, True, "failed to parse token payload"), +]) +async def test_verify_access_token_fail_non_object_segments(header, payload, message): + """Test that a header or payload that is not an object fails as an invalid token.""" + + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + + with pytest.raises(VerifyAccessTokenError) as e: + await api_client.verify_access_token(unsigned_jwt(header, payload)) + assert message in str(e.value).lower() + + FETCH_FAILURES = [ ("connect_error", True), ("http_500", True), @@ -1149,6 +1195,59 @@ async def test_verify_dpop_proof_fail_no_http_url(): assert "http_url" in str(err.value).lower() +@pytest.mark.asyncio +@pytest.mark.parametrize("proof", [ + unsigned_jwt([1], {}), + unsigned_jwt("text", {}), + unsigned_jwt(None, {}), + "a.b", + "not-a-jwt", +]) +async def test_verify_dpop_proof_fail_unparseable_header(proof): + """ + Test that a proof whose header cannot be parsed into an object fails as an invalid proof. + """ + api_client = ApiClient( + ApiClientOptions(domain="auth0.local", audience="my-audience") + ) + + with pytest.raises(InvalidDpopProofError): + await api_client.verify_dpop_proof( + access_token="test_token", + proof=proof, + http_method="GET", + http_url="https://api.example.com/resource" + ) + + +@pytest.mark.asyncio +async def test_verify_dpop_proof_fail_incomplete_jwk(): + """ + Test that a proof whose jwk has no coordinates fails as an invalid proof. + """ + access_token = "test_token" + proof = await generate_dpop_proof( + access_token=access_token, + http_method="GET", + http_url="https://api.example.com/resource", + header_overrides={"jwk": {"kty": "EC", "crv": "P-256"}}, + ) + + api_client = ApiClient( + ApiClientOptions(domain="auth0.local", audience="my-audience") + ) + + with pytest.raises(InvalidDpopProofError) as err: + await api_client.verify_dpop_proof( + access_token=access_token, + proof=proof, + http_method="GET", + http_url="https://api.example.com/resource" + ) + + assert "jwk" in str(err.value).lower() + + # --- Claim Validation Tests --- @pytest.mark.asyncio @@ -1409,6 +1508,34 @@ async def test_verify_dpop_proof_fail_invalid_iat_in_future(): assert "iat is from the future" in str(err.value).lower() +@pytest.mark.asyncio +@pytest.mark.parametrize("bad_iat", [float("nan"), float("inf"), float("-inf")]) +async def test_verify_dpop_proof_fail_non_finite_iat(bad_iat): + """ + Test that a DPoP proof whose 'iat' is NaN or infinite fails verification. + """ + access_token = "test_token" + dpop_proof = await generate_dpop_proof( + access_token=access_token, + http_method="GET", + http_url="https://api.example.com/resource", + iat_time=bad_iat + ) + + api_client = ApiClient( + ApiClientOptions(domain="auth0.local", audience="my-audience") + ) + + with pytest.raises(InvalidDpopProofError) as err: + await api_client.verify_dpop_proof( + access_token=access_token, + proof=dpop_proof, + http_method="GET", + http_url="https://api.example.com/resource" + ) + + assert "invalid iat" in str(err.value).lower() + @pytest.mark.asyncio async def test_verify_dpop_proof_iat_exact_boundary_conditions(): """ @@ -1581,6 +1708,34 @@ async def test_verify_dpop_proof_with_missing_jti(): ) assert "missing required claim: jti" in str(err.value).lower() +@pytest.mark.asyncio +@pytest.mark.parametrize("bad_htm", [5, ["GET"], None, True]) +async def test_verify_dpop_proof_fail_non_string_htm(bad_htm): + """ + Test that a DPoP proof whose 'htm' claim is not a string fails verification. + """ + access_token = "test_token" + dpop_proof = await generate_dpop_proof( + access_token=access_token, + http_method=bad_htm, + http_url="https://api.example.com/resource", + ) + + api_client = ApiClient( + ApiClientOptions(domain="auth0.local", audience="my-audience") + ) + + with pytest.raises(InvalidDpopProofError) as err: + await api_client.verify_dpop_proof( + access_token=access_token, + proof=dpop_proof, + http_method="GET", + http_url="https://api.example.com/resource" + ) + + assert "htm" in str(err.value).lower() + + @pytest.mark.asyncio async def test_verify_dpop_proof_fail_htm_mismatch(): """ @@ -1965,6 +2120,59 @@ async def test_verify_request_dpop_scheme_success(httpx_mock: HTTPXMock): assert result["aud"] == "my-audience" assert result["iss"] == "https://auth0.local/" +@pytest.mark.asyncio +@pytest.mark.parametrize("proof", [unsigned_jwt([1], {}), unsigned_jwt(None, {})]) +async def test_verify_request_dpop_fail_non_object_proof_header(proof): + """ + Test that a DPoP proof whose header is not an object is rejected as an invalid proof. + """ + api_client = ApiClient( + ApiClientOptions(domain="auth0.local", audience="my-audience") + ) + + with pytest.raises(InvalidDpopProofError): + await api_client.verify_request( + headers={"authorization": "DPoP some-token", "dpop": proof}, + http_method="GET", + http_url="https://api.example.com/resource" + ) + + +@pytest.mark.asyncio +async def test_verify_request_dpop_fail_non_string_htm(httpx_mock: HTTPXMock): + """ + Test that a DPoP proof with a non-string 'htm' claim is rejected through verify_request. + """ + httpx_mock.add_response( + method="GET", + url=DISCOVERY_URL, + json={"jwks_uri": JWKS_URL, "issuer": "https://auth0.local/"}, + ) + httpx_mock.add_response(method="GET", url=JWKS_URL, json={"keys": [PUBLIC_RSA_JWK]}) + + access_token = await generate_token_with_cnf( + domain="auth0.local", + user_id="test_user", + audience="my-audience", + ) + dpop_proof = await generate_dpop_proof( + access_token=access_token, + http_method=5, + http_url="https://api.example.com/resource" + ) + + api_client = ApiClient( + ApiClientOptions(domain="auth0.local", audience="my-audience") + ) + + with pytest.raises(InvalidDpopProofError): + await api_client.verify_request( + headers={"authorization": f"DPoP {access_token}", "dpop": dpop_proof}, + http_method="GET", + http_url="https://api.example.com/resource" + ) + + @pytest.mark.asyncio async def test_verify_request_header_normalization(httpx_mock: HTTPXMock): """ diff --git a/tests/test_token_store.py b/tests/test_token_store.py index 037ff2b..55252e2 100644 --- a/tests/test_token_store.py +++ b/tests/test_token_store.py @@ -5,6 +5,7 @@ from typing import Optional import pytest +from conftest import unsigned_jwt from auth0_api_python._internal.cache_keys import ( index_cache_key, @@ -94,6 +95,14 @@ def test_encrypt_decrypt_roundtrip(): assert decrypted == dict(value) +def test_decrypt_rejects_non_object_header(): + """A stored value whose header is not a JSON object raises ValueError.""" + store = ConcreteTokenStore(secret="some-secret-0123456789abcdef-0123456789") + + with pytest.raises(ValueError, match="header"): + store.decrypt("key", unsigned_jwt([1], {})) + + def test_encrypt_different_cache_keys_produce_different_ciphertext(): """Two entries with the same value but different keys produce different ciphertext.""" store = ConcreteTokenStore(secret="some-secret-0123456789abcdef-0123456789") @@ -323,6 +332,15 @@ def test_session_fingerprint_falls_back_to_sha256_for_non_object_payload(): assert session_fingerprint(token) == hashlib.sha256(token.encode()).hexdigest() +def test_session_fingerprint_falls_back_to_sha256_for_deeply_nested_payload(): + """A payload nested deep enough to exhaust the parser falls back to sha256 without raising.""" + depth = 200_000 + payload = base64.urlsafe_b64encode(("[" * depth + "]" * depth).encode()).rstrip(b"=").decode() + token = f"hdr.{payload}.sig" + + assert session_fingerprint(token) == hashlib.sha256(token.encode()).hexdigest() + + def test_session_fingerprint_falls_back_to_sha256_for_malformed_token(): """Test that a malformed, non-JWT string falls back to a sha256 digest without raising.""" malformed = "not-a-real-token" diff --git a/tests/test_utils.py b/tests/test_utils.py index 7e90808..c2d3c4c 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -3,16 +3,22 @@ """ import asyncio +import base64 import pytest +from conftest import unsigned_jwt from auth0_api_python.token_utils import generate_token from auth0_api_python.utils import ( + get_unverified_header, get_unverified_payload, normalize_domain, parse_cache_control_max_age, ) +NON_OBJECT_SEGMENTS = [[1], "text", 5, None, True] + + # ===== normalize_domain ===== @@ -106,6 +112,29 @@ def test_normalize_domain_rejects_empty(): normalize_domain(" ") +# ===== get_unverified_header ===== + + +@pytest.mark.parametrize("segment", NON_OBJECT_SEGMENTS) +def test_get_unverified_header_rejects_non_object(segment): + """Test that a header that is not a JSON object raises ValueError.""" + with pytest.raises(ValueError, match="not a JSON object"): + get_unverified_header(unsigned_jwt(segment, {"iss": "https://tenant.auth0.com/"})) + + +@pytest.mark.parametrize("index", [0, 1]) +def test_get_unverified_segments_reject_deeply_nested_json(index): + """Test that a segment nested too deep for the parser raises ValueError.""" + depth = 200_000 + deep = base64.urlsafe_b64encode(("[" * depth + "]" * depth).encode()).rstrip(b"=").decode() + parts = ["e30", "e30", "sig"] + parts[index] = deep + decode = get_unverified_header if index == 0 else get_unverified_payload + + with pytest.raises(ValueError, match="nested"): + decode(".".join(parts)) + + # ===== get_unverified_payload ===== @@ -135,6 +164,13 @@ def test_get_unverified_payload_invalid_token(): get_unverified_payload(invalid_token) +@pytest.mark.parametrize("segment", NON_OBJECT_SEGMENTS) +def test_get_unverified_payload_rejects_non_object(segment): + """Test that a payload that is not a JSON object raises ValueError.""" + with pytest.raises(ValueError, match="not a JSON object"): + get_unverified_payload(unsigned_jwt({"alg": "RS256"}, segment)) + + # ===== parse_cache_control_max_age ===== From c06f2c25d2315e9c4e802b4272eae072f84f942d Mon Sep 17 00:00:00 2001 From: Snehil Kishore Date: Tue, 27 Oct 2026 20:36:36 +0530 Subject: [PATCH 2/4] chore: drop exp, nbf and decrypt checks that this fix does not need --- src/auth0_api_python/api_client.py | 9 ++------- src/auth0_api_python/encryption.py | 2 -- tests/test_api_client.py | 21 ++------------------- tests/test_token_store.py | 9 --------- 4 files changed, 4 insertions(+), 37 deletions(-) diff --git a/src/auth0_api_python/api_client.py b/src/auth0_api_python/api_client.py index d9c9c16..bbd2d6b 100644 --- a/src/auth0_api_python/api_client.py +++ b/src/auth0_api_python/api_client.py @@ -629,16 +629,11 @@ async def verify_access_token( raise VerifyAccessTokenError("Audience mismatch (single aud)") now = int(time.time()) - if "exp" not in claims: - raise VerifyAccessTokenError("Token is expired") - exp = claims["exp"] - if isinstance(exp, bool) or not isinstance(exp, (int, float)) or (isinstance(exp, float) and not math.isfinite(exp)): - raise VerifyAccessTokenError("Invalid 'exp' claim in token") - if now >= exp: + if "exp" not in claims or now >= claims["exp"]: raise VerifyAccessTokenError("Token is expired") nbf = claims.get("nbf") if nbf is not None: - if isinstance(nbf, bool) or not isinstance(nbf, (int, float)) or (isinstance(nbf, float) and not math.isfinite(nbf)): + if isinstance(nbf, bool) or not isinstance(nbf, (int, float)): raise VerifyAccessTokenError("Invalid 'nbf' claim in token") if now < nbf: raise VerifyAccessTokenError("Token is not yet valid") diff --git a/src/auth0_api_python/encryption.py b/src/auth0_api_python/encryption.py index 760eb2a..0363889 100644 --- a/src/auth0_api_python/encryption.py +++ b/src/auth0_api_python/encryption.py @@ -34,8 +34,6 @@ def _read_jwe_kid(token: str) -> str: if padding != 4: header_b64 += "=" * padding header = json.loads(base64.urlsafe_b64decode(header_b64)) - if not isinstance(header, dict): - raise ValueError("Invalid JWE header: not a JSON object") kid = header.get("kid") if not kid: raise ValueError('Missing "kid" in JWE header') diff --git a/tests/test_api_client.py b/tests/test_api_client.py index bbd82df..02edde8 100644 --- a/tests/test_api_client.py +++ b/tests/test_api_client.py @@ -515,32 +515,15 @@ async def test_verify_access_token_fail_fractional_nbf_in_future(httpx_mock: HTT @pytest.mark.asyncio -@pytest.mark.parametrize("bad_nbf", ["soon", True, [1], float("nan"), float("-inf")]) +@pytest.mark.parametrize("bad_nbf", ["soon", True, [1]]) async def test_verify_access_token_fail_non_numeric_nbf(httpx_mock: HTTPXMock, bad_nbf): - """A non-numeric or non-finite 'nbf' is rejected as an invalid token.""" + """A non-numeric 'nbf' is rejected as an invalid token.""" with pytest.raises(VerifyAccessTokenError) as err: await _verify_with_nbf(httpx_mock, bad_nbf) assert "nbf" in str(err.value) -@pytest.mark.asyncio -@pytest.mark.parametrize("bad_exp", ["9999999999", True, False, [1], None, float("nan"), float("inf")]) -async def test_verify_access_token_fail_invalid_exp(httpx_mock: HTTPXMock, bad_exp): - """A non-numeric or non-finite 'exp' is rejected as an invalid token.""" - 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]}) - access_token = await generate_token( - domain="auth0.local", user_id="user_123", audience="my-audience", exp=False, claims={"exp": bad_exp} - ) - api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) - - with pytest.raises(VerifyAccessTokenError) as err: - await api_client.verify_access_token(access_token=access_token) - - assert "Invalid 'exp' claim" in str(err.value) - - @pytest.mark.asyncio async def test_verify_access_token_fail_no_audience_config(): """ diff --git a/tests/test_token_store.py b/tests/test_token_store.py index 55252e2..804d3bf 100644 --- a/tests/test_token_store.py +++ b/tests/test_token_store.py @@ -5,7 +5,6 @@ from typing import Optional import pytest -from conftest import unsigned_jwt from auth0_api_python._internal.cache_keys import ( index_cache_key, @@ -95,14 +94,6 @@ def test_encrypt_decrypt_roundtrip(): assert decrypted == dict(value) -def test_decrypt_rejects_non_object_header(): - """A stored value whose header is not a JSON object raises ValueError.""" - store = ConcreteTokenStore(secret="some-secret-0123456789abcdef-0123456789") - - with pytest.raises(ValueError, match="header"): - store.decrypt("key", unsigned_jwt([1], {})) - - def test_encrypt_different_cache_keys_produce_different_ciphertext(): """Two entries with the same value but different keys produce different ciphertext.""" store = ConcreteTokenStore(secret="some-secret-0123456789abcdef-0123456789") From be06dac9ca5050cf273c5a44a97bb994eb6381be Mon Sep 17 00:00:00 2001 From: Snehil Kishore Date: Tue, 27 Oct 2026 20:52:45 +0530 Subject: [PATCH 3/4] fix: reject negative expires_in and clarify token exchange docs --- README.md | 1 + docs/OrganizationPolicy.md | 4 ++++ docs/TokenStorage.md | 7 ++++--- src/auth0_api_python/api_client.py | 6 ++++++ tests/test_api_client.py | 26 ++++++++++++++++++++++++++ 5 files changed, 41 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 20e25ee..4e48f65 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,7 @@ async def main(): connection = "my-connection" # The Auth0 connection to the upstream idp access_token = "..." # The Auth0 access token to exchange + await api_client.verify_access_token(access_token) # Verify first so the organization policy applies connection_access_token = await api_client.get_access_token_for_connection({"connection": connection, "access_token": access_token}) # The returned token is the access token for the upstream idp print(connection_access_token) diff --git a/docs/OrganizationPolicy.md b/docs/OrganizationPolicy.md index d0052f0..5c00016 100644 --- a/docs/OrganizationPolicy.md +++ b/docs/OrganizationPolicy.md @@ -51,6 +51,10 @@ api_client = ApiClient(ApiClientOptions( `organization_id` compares the opaque `org_id` claim value directly (string comparison, no network call). It does not accept or resolve the human-readable Organization name. It must be a non-empty string or a non-empty list of non-empty strings, otherwise `ConfigurationError` is raised at construction. +## Token Exchange + +The policy is enforced when a token is verified. `get_token_on_behalf_of()` and `get_access_token_for_connection()` verify the incoming token, and so apply the policy, only when a `token_store` is configured and `verified` is not passed. Without a store, they send the token straight to Auth0 for the exchange and do not check `org_id`. Call `verify_access_token()` first at your API boundary, as in the examples above, so the policy applies before any exchange. + ## Error Handling ### Configuration Errors diff --git a/docs/TokenStorage.md b/docs/TokenStorage.md index c984740..736cb67 100644 --- a/docs/TokenStorage.md +++ b/docs/TokenStorage.md @@ -190,6 +190,7 @@ api_client = ApiClient(ApiClientOptions( )) ``` -An index member holds a hashed `token_key`, the granted scopes, and an expiry, never a bearer -token, so it is not encrypted. The tokens themselves stay encrypted under their own keys as -described above. +An index member holds a `token_key`, the granted scopes, and an expiry, never a bearer token, so +it is not encrypted. The `token_key` is the caller's `sub` in plain text followed by a hash, so +anyone who can read the store can see which callers have entries. The tokens themselves stay +encrypted under their own keys as described above. diff --git a/src/auth0_api_python/api_client.py b/src/auth0_api_python/api_client.py index bbd2d6b..e4b53e1 100644 --- a/src/auth0_api_python/api_client.py +++ b/src/auth0_api_python/api_client.py @@ -884,6 +884,9 @@ async def get_access_token_for_connection( except (TypeError, ValueError): raise ApiError("invalid_response", "expires_in is not an integer.", 502) + if expires_in < 0: + raise ApiError("invalid_response", "expires_in cannot be negative.", 502) + result = { "access_token": access_token, "expires_in": expires_in, @@ -1313,6 +1316,9 @@ async def get_client_credentials_token( if not isinstance(access_token, str) or not access_token: raise ApiError("invalid_response", "Missing or invalid access_token in response.", 502) + if expires_in < 0: + raise ApiError("invalid_response", "expires_in cannot be negative.", 502) + cc_result: ClientCredentialsTokenResult = { "access_token": access_token, "expires_in": expires_in, diff --git a/tests/test_api_client.py b/tests/test_api_client.py index 02edde8..1183eec 100644 --- a/tests/test_api_client.py +++ b/tests/test_api_client.py @@ -2924,6 +2924,31 @@ async def test_get_access_token_for_connection_expires_in_not_integer(httpx_mock assert err.value.status_code == 502 +@pytest.mark.asyncio +async def test_get_access_token_for_connection_expires_in_negative(httpx_mock: HTTPXMock): + httpx_mock.add_response(method="GET", url=DISCOVERY_URL, json={"token_endpoint": TOKEN_ENDPOINT}) + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + status_code=200, + json={"access_token": "abc123", "expires_in": -1} + ) + api_client = ApiClient(ApiClientOptions( + domain="auth0.local", + audience="my-audience", + client_id="cid", + client_secret="csecret", + )) + with pytest.raises(ApiError) as err: + await api_client.get_access_token_for_connection({ + "connection": "test-conn", + "access_token": "user-token" + }) + assert err.value.code == "invalid_response" + assert "negative" in str(err.value).lower() + assert err.value.status_code == 502 + + # ===== Custom Token Exchange Tests ===== @@ -4027,6 +4052,7 @@ async def test_get_client_credentials_token_no_scope_in_response( {"json": {"access_token": "", "expires_in": 3600}}, {"json": {"access_token": "t"}}, {"json": {"access_token": "t", "expires_in": "soon"}}, + {"json": {"access_token": "t", "expires_in": -1}}, ], ) async def test_get_client_credentials_token_malformed_response( From d026f2d8da28104fad07c4867f729e5f81115032 Mon Sep 17 00:00:00 2001 From: Snehil Kishore Date: Wed, 28 Oct 2026 13:24:47 +0530 Subject: [PATCH 4/4] test: cover oversized iat and make nesting-depth tests independent of the interpreter limit The non-finite iat error message now says a finite number is required. --- src/auth0_api_python/api_client.py | 2 +- tests/test_api_client.py | 27 +++++++++++++++++++++++++++ tests/test_token_store.py | 13 ++++++++++++- tests/test_utils.py | 21 ++++++++++++++++++--- 4 files changed, 58 insertions(+), 5 deletions(-) diff --git a/src/auth0_api_python/api_client.py b/src/auth0_api_python/api_client.py index e4b53e1..f200996 100644 --- a/src/auth0_api_python/api_client.py +++ b/src/auth0_api_python/api_client.py @@ -731,7 +731,7 @@ async def verify_dpop_proof( leeway = getattr(self.options, "dpop_iat_leeway", 30) # default 30 seconds if not isinstance(iat, (int, float)) or (isinstance(iat, float) and not math.isfinite(iat)): - raise InvalidDpopProofError("Invalid iat claim (must be integer or float)") + raise InvalidDpopProofError("Invalid iat claim (must be a finite number)") if iat < now - offset: raise InvalidDpopProofError("DPoP Proof iat is too old") diff --git a/tests/test_api_client.py b/tests/test_api_client.py index 1183eec..d5d7a36 100644 --- a/tests/test_api_client.py +++ b/tests/test_api_client.py @@ -1519,6 +1519,33 @@ async def test_verify_dpop_proof_fail_non_finite_iat(bad_iat): assert "invalid iat" in str(err.value).lower() +@pytest.mark.asyncio +async def test_verify_dpop_proof_fail_iat_too_large_for_float(): + """ + Test that a DPoP proof whose 'iat' is an integer too large to convert to a float fails verification. + """ + access_token = "test_token" + dpop_proof = await generate_dpop_proof( + access_token=access_token, + http_method="GET", + http_url="https://api.example.com/resource", + iat_time=10**400 + ) + + api_client = ApiClient( + ApiClientOptions(domain="auth0.local", audience="my-audience") + ) + + with pytest.raises(InvalidDpopProofError) as err: + await api_client.verify_dpop_proof( + access_token=access_token, + proof=dpop_proof, + http_method="GET", + http_url="https://api.example.com/resource" + ) + + assert "from the future" in str(err.value).lower() + @pytest.mark.asyncio async def test_verify_dpop_proof_iat_exact_boundary_conditions(): """ diff --git a/tests/test_token_store.py b/tests/test_token_store.py index 804d3bf..73a0ec8 100644 --- a/tests/test_token_store.py +++ b/tests/test_token_store.py @@ -323,8 +323,19 @@ def test_session_fingerprint_falls_back_to_sha256_for_non_object_payload(): assert session_fingerprint(token) == hashlib.sha256(token.encode()).hexdigest() +def test_session_fingerprint_falls_back_to_sha256_when_the_parser_runs_out_of_depth(monkeypatch): + """A payload the parser cannot handle for depth falls back to sha256 without raising.""" + def raise_recursion_error(*args, **kwargs): + raise RecursionError + + monkeypatch.setattr("auth0_api_python.utils.json.loads", raise_recursion_error) + token = "hdr.e30.sig" + + assert session_fingerprint(token) == hashlib.sha256(token.encode()).hexdigest() + + def test_session_fingerprint_falls_back_to_sha256_for_deeply_nested_payload(): - """A payload nested deep enough to exhaust the parser falls back to sha256 without raising.""" + """A payload nested far deeper than the parser allows falls back to sha256 without raising.""" depth = 200_000 payload = base64.urlsafe_b64encode(("[" * depth + "]" * depth).encode()).rstrip(b"=").decode() token = f"hdr.{payload}.sig" diff --git a/tests/test_utils.py b/tests/test_utils.py index c2d3c4c..4ca32c2 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -122,16 +122,31 @@ def test_get_unverified_header_rejects_non_object(segment): get_unverified_header(unsigned_jwt(segment, {"iss": "https://tenant.auth0.com/"})) +def _raise_recursion_error(*args, **kwargs): + raise RecursionError + + @pytest.mark.parametrize("index", [0, 1]) -def test_get_unverified_segments_reject_deeply_nested_json(index): - """Test that a segment nested too deep for the parser raises ValueError.""" +def test_get_unverified_segments_reject_deeply_nested_json(index, monkeypatch): + """Test that a segment the parser cannot handle for depth raises ValueError.""" + monkeypatch.setattr("auth0_api_python.utils.json.loads", _raise_recursion_error) + parts = ["e30", "e30", "sig"] + decode = get_unverified_header if index == 0 else get_unverified_payload + + with pytest.raises(ValueError, match="nested"): + decode(".".join(parts)) + + +@pytest.mark.parametrize("index", [0, 1]) +def test_get_unverified_segments_reject_real_deeply_nested_json(index): + """Test that a segment nested far deeper than the parser allows raises ValueError.""" depth = 200_000 deep = base64.urlsafe_b64encode(("[" * depth + "]" * depth).encode()).rstrip(b"=").decode() parts = ["e30", "e30", "sig"] parts[index] = deep decode = get_unverified_header if index == 0 else get_unverified_payload - with pytest.raises(ValueError, match="nested"): + with pytest.raises(ValueError): decode(".".join(parts))