diff --git a/EXAMPLES.md b/EXAMPLES.md index 3dc4952..c9b5ee9 100644 --- a/EXAMPLES.md +++ b/EXAMPLES.md @@ -125,6 +125,68 @@ async with httpx.AsyncClient() as client: More info: [Client Credentials Flow](https://auth0.com/docs/get-started/authentication-and-authorization-flow/client-credentials-flow) +## Access Token for a Connection (Token Vault) + +`get_access_token_for_connection()` exchanges the user's Auth0 access token for a token from a federated identity provider (such as Google) via Auth0's Token Vault. + +Three things must exist on your Auth0 tenant before this works. The Token Vault grant must be enabled on your application, which must be a confidential (resource-server) client. The connection (for example `google-oauth2`) must be configured and enabled on that application. The user must have linked their account through Auth0's Connected Accounts flow. See the [Token Vault setup guide](https://auth0.com/docs/secure/tokens/token-vault/configure-token-vault) for the application setup and the [Connected Accounts guide](https://auth0.com/docs/secure/tokens/token-vault/connected-accounts-for-token-vault) for the user-linking step. + +### Basic call + +```python +import httpx + +from auth0_api_python import ApiClient, ApiClientOptions + +api_client = ApiClient(ApiClientOptions( + domain="your-tenant.auth0.com", + audience="https://mcp-server.example.com", + client_id="", + client_secret="", +)) + +incoming_access_token = "incoming-auth0-access-token" + +result = await api_client.get_access_token_for_connection({ + "connection": "google-oauth2", + "access_token": incoming_access_token, +}) + +async with httpx.AsyncClient() as client: + response = await client.get( + "https://www.googleapis.com/calendar/v3/calendars/primary/events", + headers={"Authorization": f"Bearer {result['access_token']}"}, + ) +``` + +### With caching + +Pass a `token_store` to cache the connection token. The SDK caches by `sub` (caller), `connection` and `login_hint`, skipping the exchange on repeat calls for the same user, provider and linked account. Pass `verified=` with a `VerifiedToken` built from the `verify_access_token()` claims to reuse that verification rather than running it again inside the exchange. + +```python +from auth0_api_python import ApiClient, ApiClientOptions, VerifiedToken + +# token_store is your AbstractTokenStore implementation. +# See docs/TokenStorage.md for how to build one and for encryption details. +api_client = ApiClient(ApiClientOptions( + domain="your-tenant.auth0.com", + audience="https://mcp-server.example.com", + client_id="", + client_secret="", + token_store=your_token_store, +)) + +incoming_access_token = "incoming-auth0-access-token" + +# Verify once, then pass the result to avoid a second verification inside the exchange. +claims = await api_client.verify_access_token(access_token=incoming_access_token) + +result = await api_client.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": incoming_access_token}, + verified=VerifiedToken(access_token=incoming_access_token, claims=claims), +) +``` + ## Inspecting Delegation After Token Verification When a downstream API or `MCP` server receives an access token that may have been issued through diff --git a/README.md b/README.md index 5e2e12e..5dfaa3e 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,8 @@ async def main(): asyncio.run(main()) ``` +When a `token_store` is configured on `ApiClientOptions`, the connection token is cached by caller, connection and `login_hint`, skipping the exchange on repeat calls. Pass `verified=` with a `VerifiedToken` built from the `verify_access_token()` claims to reuse that verification rather than verifying a second time. See [Access Token for a Connection](EXAMPLES.md#access-token-for-a-connection-token-vault) for a full example and setup requirements. + More info https://auth0.com/docs/secure/tokens/token-vault ### 5. Custom Token Exchange (Early Access) diff --git a/docs/TokenStorage.md b/docs/TokenStorage.md index 41bfc52..3abe238 100644 --- a/docs/TokenStorage.md +++ b/docs/TokenStorage.md @@ -1,9 +1,6 @@ # Token Storage -The SDK can cache access tokens it mints on the caller's behalf. Currently this covers tokens -returned by `get_token_on_behalf_of()`. This is separate from the `CacheAdapter` described in the -[Caching Guide](Caching.md), which only caches OIDC discovery metadata and JWKS keys, never a live -bearer token. +The SDK can cache access tokens it mints on the caller's behalf. The same store covers tokens returned by `get_token_on_behalf_of()`, M2M tokens from `get_client_credentials_token()`, and federated-connection tokens from `get_access_token_for_connection()`. This is separate from the `CacheAdapter` described in the [Caching Guide](Caching.md), which only caches OIDC discovery metadata and JWKS keys, never a live bearer token. ## Default Behavior @@ -14,6 +11,10 @@ To enable caching, pass a `token_store` to `ApiClientOptions`. Once a store is c automatically builds a cache key from the incoming token and no additional argument is needed per call. +## Cache Key Shapes + +The store uses a different cache key for each exchange method. OBO tokens from `get_token_on_behalf_of()` use the most detailed key, incorporating verified issuer, incoming client, exchange tenant and client, audience, organization, session, and granted scopes (see [On Behalf Of Exchange with Caching](#on-behalf-of-exchange-with-caching) for the full design). M2M tokens from `get_client_credentials_token()` are keyed on tenant, client, audience, and the requested scope set because the server is the identity and there is no user `sub`. Connection tokens from `get_access_token_for_connection()` are keyed on tenant, client, `sub` (the caller), and `connection` with no scope dimension, since the federated provider determines what scopes apply. + ## On Behalf Of Exchange with Caching The following example verifies an incoming token and exchanges for a downstream token. The result diff --git a/src/auth0_api_python/__init__.py b/src/auth0_api_python/__init__.py index 3661e0c..e927034 100644 --- a/src/auth0_api_python/__init__.py +++ b/src/auth0_api_python/__init__.py @@ -13,10 +13,12 @@ ApiError, ConfigurationError, DomainsResolverError, + GetAccessTokenForConnectionError, GetClientCredentialsTokenError, GetTokenByExchangeProfileError, MissingOrganizationError, OrganizationNotAllowedError, + VerifyAccessTokenError, ) from .token_store import ( AbstractTokenStore, @@ -42,8 +44,10 @@ "DomainsResolver", "DomainsResolverContext", "DomainsResolverError", + "GetAccessTokenForConnectionError", "GetClientCredentialsTokenError", "GetTokenByExchangeProfileError", + "VerifyAccessTokenError", "get_current_actor", "get_delegation_chain", "InMemoryCache", diff --git a/src/auth0_api_python/_internal/cache_keys.py b/src/auth0_api_python/_internal/cache_keys.py index 6669575..414cb72 100644 --- a/src/auth0_api_python/_internal/cache_keys.py +++ b/src/auth0_api_python/_internal/cache_keys.py @@ -143,7 +143,9 @@ def m2m_cache_key(*, tenant: str, client_id: str, audience: str, scopes: Optiona return hashlib.sha256(fields.encode()).hexdigest() -def token_vault_cache_key(sub: str, connection: str) -> str: - """Cache key for a Token Vault exchange, scoped to caller and connection.""" - fields = _FIELD_SEPARATOR.join(["token_vault", sub, connection]) +def token_vault_cache_key( + *, sub: str, connection: str, tenant: str, client_id: str, login_hint: Optional[str] = None +) -> str: + """Cache key for a Token Vault exchange, scoped to tenant, client, caller, connection, and login hint.""" + fields = _FIELD_SEPARATOR.join(["token_vault", tenant, client_id, sub, connection, login_hint or ""]) return hashlib.sha256(fields.encode()).hexdigest() diff --git a/src/auth0_api_python/_internal/token_vault_cache.py b/src/auth0_api_python/_internal/token_vault_cache.py new file mode 100644 index 0000000..c37a715 --- /dev/null +++ b/src/auth0_api_python/_internal/token_vault_cache.py @@ -0,0 +1,71 @@ +"""Caching for Token Vault (federated connection) exchanges: lookup and write.""" + +import logging +import time +from typing import Any, Optional + +from ..token_store import AbstractTokenStore, TokenSet +from .cache_keys import _normalized_scopes, token_vault_cache_key + +logger = logging.getLogger(__name__) + + +class TokenVaultCache: + """Caches Token Vault exchange results in a token store, keyed by caller and connection. + + ApiClient builds one TokenVaultCache when a token_store is configured and delegates + every cache decision to it. + """ + + def __init__(self, token_store: AbstractTokenStore) -> None: + self._store = token_store + + def cache_key( + self, tenant: str, client_id: str, sub: Any, connection: str, login_hint: Optional[str] = None + ) -> Optional[str]: + """Return the cache key, or None when sub is not a usable string (cache skipped with a warning).""" + if not isinstance(sub, str) or not sub: + logger.warning("Access token has no usable sub claim, skipping Token Vault cache") + return None + return token_vault_cache_key( + sub=sub, connection=connection, tenant=tenant, client_id=client_id, login_hint=login_hint + ) + + async def lookup(self, key: str) -> Optional[dict]: + """Return a live cached token or None. Miss cases: absent, malformed, expired.""" + cached: Optional[TokenSet] = None + try: + cached = await self._store.get(key) + except Exception as exc: + logger.warning("Token store read failed, treating as cache miss: %s", exc) + return None + + if cached is None: + return None + access_token = cached.get("access_token") + expires_at = cached.get("expires_at") + if not isinstance(access_token, str) or not access_token or not isinstance(expires_at, int): + logger.warning("Token store returned a malformed entry, treating as cache miss") + return None + now = int(time.time()) + if expires_at <= now: + return None + + return { + "access_token": access_token, + "expires_in": expires_at - now, + "expires_at": expires_at, + "scope": cached.get("granted_scopes") or "", + } + + async def write(self, key: str, result: dict) -> None: + """Store a freshly exchanged connection token. Failures are logged and swallowed.""" + entry: TokenSet = { + "access_token": result["access_token"], + "expires_at": result["expires_at"], + "granted_scopes": _normalized_scopes(result.get("scope")), + } + try: + await self._store.set(key, entry) + except Exception as exc: + logger.warning("Token store write failed, token still returned: %s", exc) diff --git a/src/auth0_api_python/api_client.py b/src/auth0_api_python/api_client.py index 6cff9a0..ff4dcde 100644 --- a/src/auth0_api_python/api_client.py +++ b/src/auth0_api_python/api_client.py @@ -9,6 +9,7 @@ from ._internal.cache_keys import m2m_cache_key from ._internal.obo_cache import OboCache +from ._internal.token_vault_cache import TokenVaultCache from .cache import InMemoryCache from .config import ApiClientOptions from .errors import ( @@ -169,6 +170,11 @@ def __init__(self, options: ApiClientOptions): if options.token_store is not None else None ) + self._token_vault_cache = ( + TokenVaultCache(options.token_store) + if options.token_store is not None + else None + ) self._cache_ttl = options.cache_ttl_seconds @@ -725,7 +731,12 @@ async def verify_dpop_proof( return claims - async def get_access_token_for_connection(self, options: dict[str, Any]) -> dict[str, Any]: + async def get_access_token_for_connection( + self, + options: dict[str, Any], + *, + verified: Optional[VerifiedToken] = None, + ) -> dict[str, Any]: """ Retrieves a token for a connection. @@ -733,10 +744,16 @@ async def get_access_token_for_connection(self, options: dict[str, Any]) -> dict options: Options for retrieving an access token for a connection. Must include 'connection' and 'access_token' keys. May optionally include 'login_hint'. + verified: The already-verified token, supplied by a caller that has verified it (for + example an MCP server). When omitted and a token_store is configured, the + token is verified here before any cache lookup. Raises: GetAccessTokenForConnectionError: If there was an issue requesting the access token. ApiError: If the token exchange endpoint returns an error. + 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. Returns: Dictionary containing the token response with access_token, expires_in, and scope. @@ -745,8 +762,8 @@ async def get_access_token_for_connection(self, options: dict[str, Any]) -> dict SUBJECT_TYPE_ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token" # noqa S105 REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN = "http://auth0.com/oauth/token-type/federated-connection-access-token" # noqa S105 GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN = "urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token" # noqa S105 - connection = options.get("connection") - access_token = options.get("access_token") + connection = options.get("connection", "") + access_token = options.get("access_token", "") if not connection: raise MissingRequiredArgumentError("connection") @@ -759,6 +776,29 @@ async def get_access_token_for_connection(self, options: dict[str, Any]) -> dict if not client_id or not client_secret: raise GetAccessTokenForConnectionError("You must configure the SDK with a client_id and client_secret to use get_access_token_for_connection.") + cache_key = None + if self._token_vault_cache is not None: + if verified is None: + claims = await self.verify_access_token(access_token) + verified = VerifiedToken(access_token=access_token, claims=claims) + elif verified.access_token != access_token: + # Claims must belong to the token being exchanged or a caller could read another token's entry. + raise VerifyAccessTokenError( + "verified token does not match the access token being exchanged" + ) + cache_key = self._token_vault_cache.cache_key( + tenant=self.options.domain or "", + client_id=self.options.client_id or "", + sub=verified.claims.get("sub"), + connection=connection, + login_hint=options.get("login_hint"), + ) + + if cache_key is not None: + hit = await self._token_vault_cache.lookup(cache_key) + if hit is not None: + return hit + metadata = await self._discover() token_endpoint = metadata.get("token_endpoint") @@ -817,12 +857,18 @@ async def get_access_token_for_connection(self, options: dict[str, Any]) -> dict except (TypeError, ValueError): raise ApiError("invalid_response", "expires_in is not an integer.", 502) - return { + result = { "access_token": access_token, + "expires_in": expires_in, "expires_at": int(time.time()) + expires_in, "scope": token_endpoint_response.get("scope", "") } + if cache_key is not None: + await self._token_vault_cache.write(cache_key, result) + + return result + except httpx.TimeoutException as exc: raise ApiError( "timeout_error", diff --git a/tests/test_api_client.py b/tests/test_api_client.py index e169761..2392106 100644 --- a/tests/test_api_client.py +++ b/tests/test_api_client.py @@ -35,6 +35,7 @@ m2m_cache_key, obo_cache_key, session_fingerprint, + token_vault_cache_key, ) from auth0_api_python.api_client import MAX_ARRAY_VALUES_PER_KEY, ApiClient from auth0_api_python.config import ApiClientOptions @@ -5081,6 +5082,384 @@ async def test_nss_index_non_atomic_store_loses_concurrent_add(mock_discovery, h assert posts_total == 3 +# ----- Token Vault (get_access_token_for_connection) ----- + + +def tv_key(sub: str, connection: str) -> str: + """The token_vault_cache_key for the confidential fixture's tenant and client.""" + return token_vault_cache_key( + sub=sub, connection=connection, + tenant=CONFIDENTIAL_TENANT, client_id=CONFIDENTIAL_CID, + ) + + +@pytest.mark.asyncio +async def test_get_access_token_for_connection_cache_hit( + mock_discovery, api_client_confidential, httpx_mock +): + """Cache hit: two calls for the same sub+connection perform only one network exchange. + + MUTATION-CHECKED: removing the lookup call from get_access_token_for_connection causes + this test to fail because a second POST is made and len(token_requests) == 2 != 1. + """ + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="tv-access-token"), + ) + + token = make_access_token("auth0|user1") + verified = VerifiedToken(access_token=token, claims={"sub": "auth0|user1", "iss": CONFIDENTIAL_ISS}) + + result1 = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, + verified=verified, + ) + result2 = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, + verified=verified, + ) + + assert result1["access_token"] == "tv-access-token" + assert result2["access_token"] == "tv-access-token" + token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"] + assert len(token_requests) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("exchange_scope", [{"scope": "read:calendar"}, {}]) +async def test_get_access_token_for_connection_cache_hit_matches_fresh_result( + mock_discovery, api_client_confidential, httpx_mock, exchange_scope +): + """A cache hit carries the same keys as a fresh result, with or without a scope in the exchange response.""" + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="tv-access-token", **exchange_scope), + ) + + token = make_access_token("auth0|user1") + verified = verified_for(token) + options = {"connection": "google-oauth2", "access_token": token} + + fresh = await api_client_confidential.get_access_token_for_connection(options, verified=verified) + hit = await api_client_confidential.get_access_token_for_connection(options, verified=verified) + + assert hit.keys() == fresh.keys() + assert hit["scope"] == fresh["scope"] + assert hit["expires_at"] == fresh["expires_at"] + assert 0 < hit["expires_in"] <= fresh["expires_in"] + token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"] + assert len(token_requests) == 1 + + +@pytest.mark.asyncio +async def test_get_access_token_for_connection_different_login_hint_not_reused( + mock_discovery, api_client_confidential, httpx_mock +): + """Two linked accounts on one connection each get their own token, and each hint then hits its own entry.""" + httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="tv-account-a")) + httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="tv-account-b")) + + token = make_access_token("auth0|user1") + verified = verified_for(token) + + def options(hint): + return {"connection": "google-oauth2", "access_token": token, "login_hint": hint} + + a1 = await api_client_confidential.get_access_token_for_connection(options("a@example.com"), verified=verified) + b1 = await api_client_confidential.get_access_token_for_connection(options("b@example.com"), verified=verified) + a2 = await api_client_confidential.get_access_token_for_connection(options("a@example.com"), verified=verified) + b2 = await api_client_confidential.get_access_token_for_connection(options("b@example.com"), verified=verified) + + assert [a1["access_token"], b1["access_token"]] == ["tv-account-a", "tv-account-b"] + assert a2["access_token"] == "tv-account-a" + assert b2["access_token"] == "tv-account-b" + token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"] + assert len(token_requests) == 2 + + +@pytest.mark.asyncio +async def test_get_access_token_for_connection_cache_miss_after_expiry( + mock_discovery, api_client_confidential, httpx_mock +): + """An expired cached entry triggers a fresh exchange.""" + key = tv_key("auth0|user1", "google-oauth2") + await api_client_confidential._token_store.set( + key, + {"access_token": "stale-tv-token", "expires_at": int(time.time()) - 10}, + ) + + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="fresh-tv-token"), + ) + + token = make_access_token("auth0|user1") + result = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, + verified=VerifiedToken(access_token=token, claims={"sub": "auth0|user1", "iss": CONFIDENTIAL_ISS}), + ) + + assert result["access_token"] == "fresh-tv-token" + token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"] + assert len(token_requests) == 1 + + +@pytest.mark.asyncio +async def test_get_access_token_for_connection_different_connection_not_reused( + mock_discovery, api_client_confidential, httpx_mock +): + """A cached entry for connection A is not returned for connection B.""" + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="tv-token-a"), + ) + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="tv-token-b"), + ) + + token = make_access_token("auth0|user1") + verified = VerifiedToken(access_token=token, claims={"sub": "auth0|user1", "iss": CONFIDENTIAL_ISS}) + + result_a = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, verified=verified + ) + result_b = await api_client_confidential.get_access_token_for_connection( + {"connection": "github", "access_token": token}, verified=verified + ) + + assert result_a["access_token"] == "tv-token-a" + assert result_b["access_token"] == "tv-token-b" + token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"] + assert len(token_requests) == 2 + + +@pytest.mark.asyncio +async def test_get_access_token_for_connection_different_sub_not_reused( + mock_discovery, api_client_confidential, httpx_mock +): + """A cached entry for sub A is not returned for sub B.""" + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="tv-token-user1"), + ) + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="tv-token-user2"), + ) + + token1 = make_access_token("auth0|user1") + token2 = make_access_token("auth0|user2") + + result1 = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token1}, + verified=VerifiedToken(access_token=token1, claims={"sub": "auth0|user1", "iss": CONFIDENTIAL_ISS}), + ) + result2 = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token2}, + verified=VerifiedToken(access_token=token2, claims={"sub": "auth0|user2", "iss": CONFIDENTIAL_ISS}), + ) + + assert result1["access_token"] == "tv-token-user1" + assert result2["access_token"] == "tv-token-user2" + token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"] + assert len(token_requests) == 2 + + +@pytest.mark.asyncio +async def test_get_access_token_for_connection_store_read_failure_falls_back( + mock_discovery, httpx_mock, caplog +): + """A store read failure logs a warning and falls back to a fresh exchange.""" + api_client = ApiClient(ApiClientOptions( + domain="auth0.local", + audience="my-audience", + client_id="cid", + client_secret="csecret", + token_store=RaisingGetTokenStore(), + )) + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="tv-access-token"), + ) + + token = make_access_token("auth0|user1") + caplog.set_level(logging.WARNING) + result = await api_client.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, + verified=VerifiedToken(access_token=token, claims={"sub": "auth0|user1", "iss": CONFIDENTIAL_ISS}), + ) + + assert result["access_token"] == "tv-access-token" + assert any("Token store read failed" in record.message for record in caplog.records) + + +@pytest.mark.asyncio +async def test_get_access_token_for_connection_no_sub_skips_cache( + mock_discovery, api_client_confidential, httpx_mock, caplog +): + """A token without a sub claim skips caching with a warning, so each call re-exchanges.""" + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="tv-token-1"), + ) + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="tv-token-2"), + ) + + token = make_access_token("auth0|user1") + no_sub = VerifiedToken(access_token=token, claims={"iss": CONFIDENTIAL_ISS}) + + caplog.set_level(logging.WARNING) + result1 = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, verified=no_sub + ) + result2 = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, verified=no_sub + ) + + assert result1["access_token"] == "tv-token-1" + assert result2["access_token"] == "tv-token-2" + token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"] + assert len(token_requests) == 2 + assert any("no usable sub" in record.message for record in caplog.records) + + +@pytest.mark.asyncio +async def test_get_access_token_for_connection_non_string_sub_skips_cache( + mock_discovery, api_client_confidential, httpx_mock, caplog +): + """A non-string sub skips caching with a warning instead of failing the exchange.""" + httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="tv-token-1")) + httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="tv-token-2")) + + token = make_access_token("auth0|user1") + bad_sub = VerifiedToken(access_token=token, claims={"sub": 12345, "iss": CONFIDENTIAL_ISS}) + + caplog.set_level(logging.WARNING) + result1 = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, verified=bad_sub + ) + result2 = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, verified=bad_sub + ) + + assert result1["access_token"] == "tv-token-1" + assert result2["access_token"] == "tv-token-2" + assert any("no usable sub" in record.message for record in caplog.records) + + +class _StubMalformedEntryTokenStore(InMemoryTokenStore): + """Token store whose get() returns a fixed entry.""" + + def __init__(self, entry): + super().__init__() + self._entry = entry + + async def get(self, key: str): + return self._entry + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "entry", + [ + {"access_token": "cached", "expires_at": "9999999999"}, + {"access_token": "cached", "expires_at": None}, + {"access_token": "", "expires_at": 9999999999}, + {"access_token": 123, "expires_at": 9999999999}, + ], +) +async def test_get_access_token_for_connection_malformed_entry_is_a_miss( + mock_discovery, httpx_mock, caplog, entry +): + """An entry with a wrong-typed field is treated as a miss and the exchange still succeeds.""" + api_client = ApiClient(ApiClientOptions( + domain="auth0.local", + audience="my-audience", + client_id="cid", + client_secret="csecret", + token_store=_StubMalformedEntryTokenStore(entry), + )) + httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="fresh-tv-token")) + + token = make_access_token("auth0|user1") + caplog.set_level(logging.WARNING) + result = await api_client.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, verified=verified_for(token) + ) + + assert result["access_token"] == "fresh-tv-token" + assert any("malformed entry" in record.message for record in caplog.records) + + +@pytest.mark.asyncio +async def test_get_access_token_for_connection_no_verified_calls_verify( + mock_discovery, api_client_confidential, httpx_mock, monkeypatch +): + """With no verified= param, the client calls verify_access_token before the exchange. + + verify_access_token is called once per invocation even when the second call hits the cache, + because verification precedes the cache lookup. The POST exchange fires only once. + """ + httpx_mock.add_response( + method="POST", + url=TOKEN_ENDPOINT, + json=token_success(access_token="tv-access-token"), + ) + + verify_calls = [] + + async def stub_verify(access_token: str): + verify_calls.append(access_token) + return {"sub": "auth0|user1", "iss": CONFIDENTIAL_ISS} + + monkeypatch.setattr(api_client_confidential, "verify_access_token", stub_verify) + + token = make_access_token("auth0|user1") + result1 = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, + ) + result2 = await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, + ) + + assert result1["access_token"] == "tv-access-token" + assert result2["access_token"] == "tv-access-token" + assert len(verify_calls) == 2 + token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"] + assert len(token_requests) == 1 + + +@pytest.mark.asyncio +async def test_get_access_token_for_connection_verified_mismatch_raises( + api_client_confidential, httpx_mock +): + """A verified token whose access_token differs from the one being exchanged is rejected.""" + token = make_access_token("auth0|user1") + other = make_access_token("auth0|user2") + + with pytest.raises(VerifyAccessTokenError): + await api_client_confidential.get_access_token_for_connection( + {"connection": "google-oauth2", "access_token": token}, + verified=verified_for(other, "auth0|user2"), + ) + + token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"] + assert len(token_requests) == 0 + + # ===== MCD (Multi-Custom Domain) Tests ===== @pytest.mark.asyncio diff --git a/tests/test_token_store.py b/tests/test_token_store.py index c3e68b9..037ff2b 100644 --- a/tests/test_token_store.py +++ b/tests/test_token_store.py @@ -261,15 +261,18 @@ def test_m2m_cache_key_different_inputs_different_key(): def test_token_vault_cache_key_same_inputs_same_key(): """Test that identical inputs produce identical cache keys.""" - assert token_vault_cache_key("sub1", "conn1") == token_vault_cache_key("sub1", "conn1") + assert token_vault_cache_key(sub="sub1", connection="conn1", tenant="", client_id="") == token_vault_cache_key(sub="sub1", connection="conn1", tenant="", client_id="") def test_token_vault_cache_key_different_inputs_different_key(): """Test that a different sub or connection produces a different cache key.""" - base = token_vault_cache_key("sub1", "conn1") + base = token_vault_cache_key(sub="sub1", connection="conn1", tenant="", client_id="") - assert token_vault_cache_key("sub2", "conn1") != base - assert token_vault_cache_key("sub1", "conn2") != base + assert token_vault_cache_key(sub="sub2", connection="conn1", tenant="", client_id="") != base + assert token_vault_cache_key(sub="sub1", connection="conn2", tenant="", client_id="") != base + assert token_vault_cache_key(sub="sub1", connection="conn1", tenant="t1", client_id="") != base + assert token_vault_cache_key(sub="sub1", connection="conn1", tenant="", client_id="c1") != base + assert token_vault_cache_key(sub="sub1", connection="conn1", tenant="", client_id="", login_hint="a@example.com") != base # ===== session_fingerprint =====