diff --git a/EXAMPLES.md b/EXAMPLES.md index c9b5ee9..8888766 100644 --- a/EXAMPLES.md +++ b/EXAMPLES.md @@ -306,6 +306,23 @@ headers = {"authorization": "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."} result = asyncio.run(validate_request(headers)) ``` +### Telling an Outage from an Invalid Token + +`AuthServerUnavailableError` is raised when the discovery document or JWKS cannot be reached. It subclasses `VerifyAccessTokenError`, so catch it first to answer `503` instead of `401`. + +```python +from auth0_api_python import ApiClient, AuthServerUnavailableError, VerifyAccessTokenError + +async def validate_token(api_client: ApiClient, token: str): + try: + claims = await api_client.verify_access_token(token) + return {"success": True, "user": claims["sub"]} + except AuthServerUnavailableError as e: + return {"error": e.get_error_code()}, e.get_status_code() # 503, retry later + except VerifyAccessTokenError as e: + return {"error": e.get_error_code()}, e.get_status_code() # 401, token rejected +``` + ## DPoP Authentication diff --git a/README.md b/README.md index 5dfaa3e..20e25ee 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,12 @@ asyncio.run(main()) In this example, the returned dictionary contains the decoded claims (like `sub`, `scope`, etc.) from the verified token. +If the OIDC discovery document or the JWKS request cannot be reached (connection error, timeout, or an HTTP `5xx` or `429` response), the method raises `AuthServerUnavailableError`, a subclass of `VerifyAccessTokenError` with status `503` and error code `auth_server_unavailable`. Other fetch failures, such as a `404` or a malformed response, still raise `VerifyAccessTokenError`. `verify_request()` raises the same error and sets no `WWW-Authenticate` header, so clients retry later instead of requesting a new token. + +HTTP status codes are checked only for the default HTTP client. With `custom_fetch`, only a connection error or timeout raised by your function is reported as `AuthServerUnavailableError`. + +This error comes from token verification only. Where verification is skipped, such as `get_client_credentials_token()` or an exchange with `verified=`, a failed discovery request raises the underlying `httpx` error. + ### 4. Get an access token for a connection If you need to get an access token for an upstream idp via a connection, you can use the `get_access_token_for_connection` method: diff --git a/docs/MultipleCustomDomain.md b/docs/MultipleCustomDomain.md index 37b06c7..6e84896 100644 --- a/docs/MultipleCustomDomain.md +++ b/docs/MultipleCustomDomain.md @@ -249,6 +249,8 @@ except VerifyAccessTokenError as e: e.get_headers() # {"WWW-Authenticate": "Bearer error=\"invalid_token\", ..."} ``` +If the discovery document or JWKS of an allowed domain cannot be reached, `verify_access_token()` raises `AuthServerUnavailableError` (a `VerifyAccessTokenError` subclass, status `503`, code `auth_server_unavailable`) instead of a 401. + --- ## Migration Guide diff --git a/src/auth0_api_python/__init__.py b/src/auth0_api_python/__init__.py index e927034..be3a880 100644 --- a/src/auth0_api_python/__init__.py +++ b/src/auth0_api_python/__init__.py @@ -11,6 +11,7 @@ from .config import ApiClientOptions from .errors import ( ApiError, + AuthServerUnavailableError, ConfigurationError, DomainsResolverError, GetAccessTokenForConnectionError, @@ -38,6 +39,7 @@ "ApiClient", "ApiClientOptions", "ApiError", + "AuthServerUnavailableError", "CacheAdapter", "ClientCredentialsTokenResult", "ConfigurationError", diff --git a/src/auth0_api_python/api_client.py b/src/auth0_api_python/api_client.py index ff4dcde..c5a1743 100644 --- a/src/auth0_api_python/api_client.py +++ b/src/auth0_api_python/api_client.py @@ -14,6 +14,7 @@ from .config import ApiClientOptions from .errors import ( ApiError, + AuthServerUnavailableError, BaseAuthError, ConfigurationError, DomainsResolverError, @@ -39,6 +40,7 @@ fetch_oidc_metadata, get_unverified_header, get_unverified_payload, + is_auth_server_outage, normalize_domain, normalize_url_for_htu, sha256_base64url, @@ -306,6 +308,7 @@ async def verify_request( InvalidAuthSchemeError: If an unsupported scheme is provided InvalidDpopProofError: If DPoP verification fails VerifyAccessTokenError: If access token verification fails + AuthServerUnavailableError: If the OIDC discovery document or JWKS cannot be reached """ # Normalize header keys to lowercase for robust access headers = {k.lower(): v for k, v in headers.items()} @@ -489,6 +492,7 @@ async def verify_access_token( DomainsResolverError: If domains resolver function fails. MissingOrganizationError: If organization_policy is "required" and the token has no org_id claim. OrganizationNotAllowedError: If the token's org_id is not in the organization_id allowlist. + AuthServerUnavailableError: If the OIDC discovery document or JWKS cannot be reached. """ if not access_token: raise MissingRequiredArgumentError("access_token") @@ -542,7 +546,8 @@ async def verify_access_token( except VerifyAccessTokenError: raise except Exception as e: - raise VerifyAccessTokenError( + error_class = AuthServerUnavailableError if is_auth_server_outage(e) else VerifyAccessTokenError + raise error_class( f"Failed to fetch OIDC discovery metadata: {str(e)}" ) from e @@ -573,7 +578,8 @@ async def verify_access_token( except VerifyAccessTokenError: raise except Exception as e: - raise VerifyAccessTokenError( + error_class = AuthServerUnavailableError if is_auth_server_outage(e) else VerifyAccessTokenError + raise error_class( f"Failed to fetch JWKS: {str(e)}" ) from e @@ -754,6 +760,7 @@ async def get_access_token_for_connection( VerifyAccessTokenError: If a store is configured and either verified is omitted and the token fails verification, or verified is supplied but does not match the access token being exchanged. MissingOrganizationError: If a store is configured, verified is omitted, organization_policy is "required" and the token has no org_id claim. OrganizationNotAllowedError: If a store is configured, verified is omitted and the token's org_id is not in the organization_id allowlist. + AuthServerUnavailableError: If a store is configured, verified is omitted and the OIDC discovery document or JWKS cannot be reached. Returns: Dictionary containing the token response with access_token, expires_in, and scope. @@ -1125,6 +1132,7 @@ async def get_token_on_behalf_of( VerifyAccessTokenError: If a store is configured and either verified is omitted and the token fails verification, or verified is supplied but does not match the access token being exchanged MissingOrganizationError: If a store is configured, verified is omitted, organization_policy is "required" and the token has no org_id claim OrganizationNotAllowedError: If a store is configured, verified is omitted and the token's org_id is not in the organization_id allowlist + AuthServerUnavailableError: If a store is configured, verified is omitted and the OIDC discovery document or JWKS cannot be reached GetTokenByExchangeProfileError: If client credentials are not configured or validation fails ApiError: If the token endpoint returns an error """ @@ -1477,6 +1485,10 @@ def _prepare_error(self, error: BaseAuthError, auth_scheme: Optional[str] = None error: The error to prepare auth_scheme: The authentication scheme that was used ("bearer" or "dpop") """ + if error.get_status_code() >= 500: + error._headers = {} + return error + error_code = error.get_error_code() error_description = error.get_error_description() diff --git a/src/auth0_api_python/errors.py b/src/auth0_api_python/errors.py index 349754c..b7e70e2 100644 --- a/src/auth0_api_python/errors.py +++ b/src/auth0_api_python/errors.py @@ -56,6 +56,16 @@ def get_error_code(self) -> str: return "invalid_token" +class AuthServerUnavailableError(VerifyAccessTokenError): + """Error raised when the OIDC discovery document or JWKS cannot be reached.""" + + def get_status_code(self) -> int: + return 503 + + def get_error_code(self) -> str: + return "auth_server_unavailable" + + class MissingOrganizationError(VerifyAccessTokenError): """Error raised when organization_policy is 'required' but the token has no org_id claim.""" diff --git a/src/auth0_api_python/utils.py b/src/auth0_api_python/utils.py index 72fbef8..981c9ea 100644 --- a/src/auth0_api_python/utils.py +++ b/src/auth0_api_python/utils.py @@ -3,6 +3,7 @@ using httpx or a custom fetch approach. """ +import asyncio import base64 import hashlib import json @@ -82,6 +83,25 @@ def normalize_domain(domain: str) -> str: return f"https://{host}/" +def is_auth_server_outage(error: Exception) -> bool: + """ + Check whether a discovery or JWKS fetch error means the auth server is down or overloaded. + + Args: + error: The exception raised while fetching. + + Returns: + True for connection errors, timeouts, HTTP 5xx and HTTP 429. False for anything else. + """ + if isinstance(error, httpx.HTTPStatusError): + status = error.response.status_code + return status >= 500 or status == 429 + return isinstance( + error, + (httpx.NetworkError, httpx.TimeoutException, ConnectionError, TimeoutError, asyncio.TimeoutError), + ) + + async def fetch_oidc_metadata( domain: str, custom_fetch: Optional[Callable[..., Any]] = None diff --git a/tests/test_api_client.py b/tests/test_api_client.py index 2392106..f83d2ae 100644 --- a/tests/test_api_client.py +++ b/tests/test_api_client.py @@ -24,6 +24,7 @@ from pytest_httpx import HTTPXMock from auth0_api_python import ( + AuthServerUnavailableError, MissingOrganizationError, OrganizationNotAllowedError, get_current_actor, @@ -489,6 +490,114 @@ async def test_verify_access_token_fail_malformed_token(): assert "failed to parse token" in str(e.value).lower() +FETCH_FAILURES = [ + ("connect_error", True), + ("http_500", True), + ("http_429", True), + ("http_404", False), +] + + +def _add_fetch_failure(httpx_mock: HTTPXMock, url: str, failure: str): + if failure == "connect_error": + httpx_mock.add_exception(httpx.ConnectError("boom"), method="GET", url=url) + else: + httpx_mock.add_response(method="GET", url=url, status_code=int(failure.split("_")[1])) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure,unavailable", FETCH_FAILURES) +async def test_verify_access_token_discovery_fetch_failure_status(httpx_mock: HTTPXMock, failure, unavailable): + """Outage-type discovery failures raise the 503 error, other failures stay a 401 invalid token.""" + _add_fetch_failure(httpx_mock, DISCOVERY_URL, failure) + + access_token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience") + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + + with pytest.raises(VerifyAccessTokenError) as err: + await api_client.verify_access_token(access_token) + + assert isinstance(err.value, AuthServerUnavailableError) is unavailable + assert err.value.get_status_code() == (503 if unavailable else 401) + assert err.value.get_error_code() == ("auth_server_unavailable" if unavailable else "invalid_token") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure,unavailable", FETCH_FAILURES) +async def test_verify_access_token_jwks_fetch_failure_status(httpx_mock: HTTPXMock, failure, unavailable): + """Outage-type JWKS failures raise the 503 error, other failures stay a 401 invalid token.""" + httpx_mock.add_response( + method="GET", + url=DISCOVERY_URL, + json={"issuer": "https://auth0.local/", "jwks_uri": JWKS_URL}, + ) + _add_fetch_failure(httpx_mock, JWKS_URL, failure) + + access_token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience") + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + + with pytest.raises(VerifyAccessTokenError) as err: + await api_client.verify_access_token(access_token) + + assert isinstance(err.value, AuthServerUnavailableError) is unavailable + assert err.value.get_status_code() == (503 if unavailable else 401) + assert err.value.get_error_code() == ("auth_server_unavailable" if unavailable else "invalid_token") + + +@pytest.mark.asyncio +async def test_verify_access_token_custom_fetch_failure_is_unavailable(): + """A custom_fetch that raises is reported as an unavailable auth server.""" + async def failing_fetch(url, **kwargs): + raise ConnectionError("boom") + + access_token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience") + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience", custom_fetch=failing_fetch)) + + with pytest.raises(AuthServerUnavailableError) as err: + await api_client.verify_access_token(access_token) + + assert err.value.get_status_code() == 503 + + +@pytest.mark.asyncio +async def test_verify_access_token_custom_fetch_non_network_error_stays_invalid_token(): + """A custom_fetch that raises something other than a connection error or timeout is a 401, not an outage.""" + async def broken_fetch(url, **kwargs): + raise ValueError("boom") + + access_token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience") + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience", custom_fetch=broken_fetch)) + + with pytest.raises(VerifyAccessTokenError) as err: + await api_client.verify_access_token(access_token) + + assert not isinstance(err.value, AuthServerUnavailableError) + assert err.value.get_status_code() == 401 + + +@pytest.mark.asyncio +async def test_verify_access_token_bad_signature_stays_invalid_token(httpx_mock: HTTPXMock): + """A reachable tenant with a token it did not sign still fails as a 401 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") + header, payload, signature = access_token.split(".") + tampered = f"{header}.{payload}.{signature[:-4]}AAAA" + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + + with pytest.raises(VerifyAccessTokenError) as err: + await api_client.verify_access_token(tampered) + + assert not isinstance(err.value, AuthServerUnavailableError) + assert err.value.get_status_code() == 401 + assert err.value.get_error_code() == "invalid_token" + + # ===== Organization Policy: verify_access_token Enforcement ===== @pytest.mark.asyncio @@ -1989,6 +2098,84 @@ async def test_verify_request_fail_dpop_disabled(): assert err.value.get_status_code() == 400 assert "invalid_request" in str(err.value.get_error_code()).lower() +@pytest.mark.asyncio +@pytest.mark.parametrize("fail_at", ["discovery", "jwks"]) +async def test_verify_request_bearer_fetch_failure_is_503_without_challenge(httpx_mock: HTTPXMock, fail_at): + """An unreachable discovery or JWKS endpoint gives a 503 with no WWW-Authenticate challenge.""" + if fail_at == "discovery": + httpx_mock.add_exception(httpx.ConnectError("boom"), method="GET", url=DISCOVERY_URL) + else: + httpx_mock.add_response( + method="GET", + url=DISCOVERY_URL, + json={"issuer": "https://auth0.local/", "jwks_uri": JWKS_URL}, + ) + httpx_mock.add_exception(httpx.ConnectError("boom"), method="GET", url=JWKS_URL) + + access_token = await generate_token(domain="auth0.local", user_id="test_user", audience="my-audience") + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + + with pytest.raises(AuthServerUnavailableError) as err: + await api_client.verify_request( + headers={"authorization": f"Bearer {access_token}"}, + http_method="GET", + http_url="https://api.example.com/resource" + ) + + assert err.value.get_status_code() == 503 + assert err.value.get_error_code() == "auth_server_unavailable" + assert err.value.get_headers() == {} + + +@pytest.mark.asyncio +async def test_verify_request_dpop_fetch_failure_is_503_without_challenge(httpx_mock: HTTPXMock): + """The DPoP path returns the same 503 with no challenge, even with DPoP enabled.""" + httpx_mock.add_exception(httpx.ConnectError("boom"), method="GET", url=DISCOVERY_URL) + + 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="GET", + http_url="https://api.example.com/resource" + ) + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + + with pytest.raises(AuthServerUnavailableError) as err: + await api_client.verify_request( + headers={"authorization": f"DPoP {access_token}", "dpop": dpop_proof}, + http_method="GET", + http_url="https://api.example.com/resource" + ) + + assert err.value.get_status_code() == 503 + assert err.value.get_headers() == {} + + +@pytest.mark.asyncio +async def test_verify_request_bearer_bad_signature_keeps_invalid_token_challenge(httpx_mock: HTTPXMock): + """A reachable tenant with a bad token still returns a 401 with an invalid_token challenge.""" + 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="test_user", audience="my-audience") + header, payload, signature = access_token.split(".") + tampered = f"{header}.{payload}.{signature[:-4]}AAAA" + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + + with pytest.raises(VerifyAccessTokenError) as err: + await api_client.verify_request( + headers={"authorization": f"Bearer {tampered}"}, + http_method="GET", + http_url="https://api.example.com/resource" + ) + + assert err.value.get_status_code() == 401 + assert 'error="invalid_token"' in err.value.get_headers()["WWW-Authenticate"] + @pytest.mark.asyncio async def test_verify_request_fail_missing_authorization_header(): """ @@ -3821,6 +4008,23 @@ async def test_get_token_on_behalf_of_unverifiable_raw_token_raises( assert not [r for r in httpx_mock.get_requests() if r.method == "POST"] +@pytest.mark.asyncio +async def test_get_token_on_behalf_of_discovery_outage_raises_unavailable( + api_client_confidential, httpx_mock +): + """With a store and no verified context, a discovery outage surfaces as the 503 error before any exchange.""" + httpx_mock.add_exception(httpx.ConnectError("boom"), method="GET", url=DISCOVERY_URL) + token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience") + + with pytest.raises(AuthServerUnavailableError): + await api_client_confidential.get_token_on_behalf_of( + access_token=token, + audience="https://api.backend.com", + ) + + assert not [r for r in httpx_mock.get_requests() if r.method == "POST"] + + @pytest.mark.asyncio async def test_get_token_on_behalf_of_verified_context_skips_reverification( mock_discovery, api_client_confidential, httpx_mock, monkeypatch @@ -5442,6 +5646,22 @@ async def stub_verify(access_token: str): assert len(token_requests) == 1 +@pytest.mark.asyncio +async def test_get_access_token_for_connection_discovery_outage_raises_unavailable( + api_client_confidential, httpx_mock +): + """With a store and no verified context, a discovery outage surfaces as the 503 error before any exchange.""" + httpx_mock.add_exception(httpx.ConnectError("boom"), method="GET", url=DISCOVERY_URL) + token = await generate_token(domain="auth0.local", user_id="user_123", audience="my-audience") + + with pytest.raises(AuthServerUnavailableError): + await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, + ) + + assert not [r for r in httpx_mock.get_requests() if r.method == "POST"] + + @pytest.mark.asyncio async def test_get_access_token_for_connection_verified_mismatch_raises( api_client_confidential, httpx_mock @@ -6208,6 +6428,28 @@ async def test_mcd_discovery_missing_issuer_field(httpx_mock): assert "missing 'issuer' field" in str(err.value).lower() +@pytest.mark.asyncio +async def test_mcd_discovery_fetch_failure_is_unavailable(httpx_mock): + """An allowed domain whose discovery cannot be fetched raises the 503 error.""" + token = await generate_token( + domain="tenant1.auth0.com", + user_id="user123", + audience="my-audience", + issuer="https://tenant1.auth0.com/" + ) + httpx_mock.add_exception( + httpx.ConnectError("boom"), + method="GET", + url="https://tenant1.auth0.com/.well-known/openid-configuration", + ) + api_client = ApiClient(ApiClientOptions(domains=["tenant1.auth0.com"], audience="my-audience")) + + with pytest.raises(AuthServerUnavailableError) as err: + await api_client.verify_access_token(token) + + assert err.value.get_status_code() == 503 + + @pytest.mark.asyncio async def test_mcd_discovery_missing_jwks_uri_field(httpx_mock): """Test that missing jwks_uri field in discovery causes clear error."""