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/_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..f200996 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. " @@ -675,7 +678,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 +703,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,14 +730,17 @@ 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)): - raise InvalidDpopProofError("Invalid iat claim (must be integer or float)") + if not isinstance(iat, (int, float)) or (isinstance(iat, float) and not math.isfinite(iat)): + raise InvalidDpopProofError("Invalid iat claim (must be a finite number)") if iat < now - offset: raise InvalidDpopProofError("DPoP Proof iat is too old") 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") @@ -871,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, @@ -1300,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/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..d5d7a36 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 @@ -555,6 +556,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 +1178,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 +1491,61 @@ 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_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(): """ @@ -1581,6 +1718,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 +2130,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): """ @@ -2733,6 +2951,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 ===== @@ -3836,6 +4079,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( diff --git a/tests/test_token_store.py b/tests/test_token_store.py index 037ff2b..73a0ec8 100644 --- a/tests/test_token_store.py +++ b/tests/test_token_store.py @@ -323,6 +323,26 @@ 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 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" + + 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..4ca32c2 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,44 @@ 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/"})) + + +def _raise_recursion_error(*args, **kwargs): + raise RecursionError + + +@pytest.mark.parametrize("index", [0, 1]) +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): + decode(".".join(parts)) + + # ===== get_unverified_payload ===== @@ -135,6 +179,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 =====