diff --git a/docs/TokenStorage.md b/docs/TokenStorage.md index 3abe238..c984740 100644 --- a/docs/TokenStorage.md +++ b/docs/TokenStorage.md @@ -11,6 +11,8 @@ 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. +A cached token is reused only while it has more than 30 seconds left before it expires. A token closer to expiry than that is treated as a miss and a fresh exchange runs, so a token returned from the cache is unlikely to lapse before the caller uses it. A token issued with an `expires_in` of 30 seconds or less is therefore never served from the cache. + ## 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. diff --git a/src/auth0_api_python/_internal/cache_expiry.py b/src/auth0_api_python/_internal/cache_expiry.py new file mode 100644 index 0000000..6952e12 --- /dev/null +++ b/src/auth0_api_python/_internal/cache_expiry.py @@ -0,0 +1,9 @@ +"""Freshness rule shared by every cache of a token the SDK minted.""" + +# A token this close to expiry is treated as expired, so it is unlikely to lapse before the caller uses it. +EXPIRY_BUFFER_SECONDS = 30 + + +def is_fresh(expires_at: int, now: int) -> bool: + """True when a cached token still has more than the expiry buffer left.""" + return expires_at - EXPIRY_BUFFER_SECONDS > now diff --git a/src/auth0_api_python/_internal/obo_cache.py b/src/auth0_api_python/_internal/obo_cache.py index 9fc05e5..be86f16 100644 --- a/src/auth0_api_python/_internal/obo_cache.py +++ b/src/auth0_api_python/_internal/obo_cache.py @@ -11,6 +11,7 @@ VerifiedToken, ) from ..types import OnBehalfOfTokenResult +from .cache_expiry import is_fresh from .cache_keys import ( _normalized_scopes, index_cache_key, @@ -161,7 +162,7 @@ def _usable_entry(cached: Optional[TokenSet], now: int) -> bool: if "access_token" not in cached or "expires_at" not in cached: logger.warning("Token store returned a malformed entry, treating as cache miss") return False - return cached["expires_at"] > now + return is_fresh(cached["expires_at"], now) @staticmethod def _hit(cached: TokenSet, now: int) -> OnBehalfOfTokenResult: @@ -204,7 +205,7 @@ async def _index_lookup( members = await indexed.list_index_members(self._index_key(identity, audience)) candidates = [ m for m in members - if self._well_formed_member(m) and m["expires_at"] > now and is_covered_by(scope, m["granted_scopes"]) + if self._well_formed_member(m) and is_fresh(m["expires_at"], now) and is_covered_by(scope, m["granted_scopes"]) ] except Exception as exc: self._warn_read_failed(exc) diff --git a/src/auth0_api_python/_internal/token_vault_cache.py b/src/auth0_api_python/_internal/token_vault_cache.py index c37a715..5ee5e45 100644 --- a/src/auth0_api_python/_internal/token_vault_cache.py +++ b/src/auth0_api_python/_internal/token_vault_cache.py @@ -5,6 +5,7 @@ from typing import Any, Optional from ..token_store import AbstractTokenStore, TokenSet +from .cache_expiry import is_fresh from .cache_keys import _normalized_scopes, token_vault_cache_key logger = logging.getLogger(__name__) @@ -48,7 +49,7 @@ async def lookup(self, key: str) -> Optional[dict]: logger.warning("Token store returned a malformed entry, treating as cache miss") return None now = int(time.time()) - if expires_at <= now: + if not is_fresh(expires_at, now): return None return { diff --git a/src/auth0_api_python/api_client.py b/src/auth0_api_python/api_client.py index ff4dcde..39110de 100644 --- a/src/auth0_api_python/api_client.py +++ b/src/auth0_api_python/api_client.py @@ -7,6 +7,7 @@ import httpx from authlib.jose import JsonWebKey, JsonWebToken +from ._internal.cache_expiry import is_fresh from ._internal.cache_keys import m2m_cache_key from ._internal.obo_cache import OboCache from ._internal.token_vault_cache import TokenVaultCache @@ -469,7 +470,7 @@ async def verify_access_token( - Fetches OIDC metadata and JWKS if not already cached. - Decodes and validates signature (RS256) with the correct key. - - Checks standard claims: 'iss', 'aud', 'exp', 'iat' + - Checks standard claims: 'iss', 'aud', 'exp', 'nbf', 'iat' - Checks extra required claims if 'required_claims' is provided. - Enforces organization_policy: requires 'org_id' when set to "required", and checks it against organization_id when an allowlist is configured. @@ -621,6 +622,12 @@ async def verify_access_token( now = int(time.time()) 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)): + raise VerifyAccessTokenError("Invalid 'nbf' claim in token") + if now < nbf: + raise VerifyAccessTokenError("Token is not yet valid") if "iat" not in claims: raise VerifyAccessTokenError("Missing 'iat' claim in token") @@ -1223,7 +1230,7 @@ async def get_client_credentials_token( if cached is not None: if "access_token" not in cached or "expires_at" not in cached: logger.warning("Token store returned a malformed entry, treating as cache miss") - elif cached["expires_at"] > int(time.time()): + elif is_fresh(cached["expires_at"], int(time.time())): hit: ClientCredentialsTokenResult = { "access_token": cached["access_token"], "expires_in": cached["expires_at"] - int(time.time()), diff --git a/tests/test_api_client.py b/tests/test_api_client.py index 2392106..5a1e3c8 100644 --- a/tests/test_api_client.py +++ b/tests/test_api_client.py @@ -457,6 +457,71 @@ async def test_verify_access_token_fail_no_exp(httpx_mock: HTTPXMock): assert "exp" in error_str or "missing" in error_str +async def _verify_with_nbf(httpx_mock: HTTPXMock, nbf): + 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]}) + claims = {} if nbf is None else {"nbf": nbf} + access_token = await generate_token( + domain="auth0.local", user_id="user_123", audience="my-audience", claims=claims + ) + api_client = ApiClient(ApiClientOptions(domain="auth0.local", audience="my-audience")) + return await api_client.verify_access_token(access_token=access_token) + + +@pytest.mark.asyncio +async def test_verify_access_token_fail_nbf_in_future(httpx_mock: HTTPXMock): + """A token whose 'nbf' is still in the future is rejected.""" + with pytest.raises(VerifyAccessTokenError) as err: + await _verify_with_nbf(httpx_mock, int(time.time()) + 3600) + + assert "not yet valid" in str(err.value) + + +@pytest.mark.asyncio +async def test_verify_access_token_succeeds_with_past_nbf(httpx_mock: HTTPXMock): + """A token whose 'nbf' has passed is accepted.""" + claims = await _verify_with_nbf(httpx_mock, int(time.time()) - 60) + + assert claims["sub"] == "user_123" + + +@pytest.mark.asyncio +async def test_verify_access_token_succeeds_without_nbf(httpx_mock: HTTPXMock): + """'nbf' is optional, so a token without it is accepted.""" + claims = await _verify_with_nbf(httpx_mock, None) + + assert "nbf" not in claims + + +@pytest.mark.asyncio +@freeze_time("2025-01-01T00:00:00Z") +async def test_verify_access_token_succeeds_when_nbf_equals_now(httpx_mock: HTTPXMock): + """A token whose 'nbf' is exactly the current time is accepted.""" + claims = await _verify_with_nbf(httpx_mock, int(time.time())) + + assert claims["sub"] == "user_123" + + +@pytest.mark.asyncio +@freeze_time("2025-01-01T00:00:00Z") +async def test_verify_access_token_fail_fractional_nbf_in_future(httpx_mock: HTTPXMock): + """A fractional 'nbf' half a second ahead is a valid number and is rejected as not yet valid.""" + with pytest.raises(VerifyAccessTokenError) as err: + await _verify_with_nbf(httpx_mock, time.time() + 0.5) + + assert "not yet valid" in str(err.value) + + +@pytest.mark.asyncio +@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 '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 async def test_verify_access_token_fail_no_audience_config(): """ @@ -4168,6 +4233,36 @@ async def test_get_token_on_behalf_of_expired_store_entry_triggers_fresh_exchang assert len(token_requests) == 2 +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("seconds_left", "expect_exchange"), + [(10, True), (3600, False)], + ids=["within-buffer-is-refreshed", "beyond-buffer-is-reused"], +) +async def test_get_token_on_behalf_of_cache_entry_expiry_buffer( + api_client_confidential, httpx_mock, seconds_left, expect_exchange +): + """A cached entry about to expire is not reused, one with time to spare is.""" + audience = "https://api.backend.com" + access_token = make_access_token("auth0|user1") + await api_client_confidential._token_store.set( + strict_key(access_token, audience=audience, scopes=None), + {"access_token": "cached-token", "expires_at": int(time.time()) + seconds_left}, + ) + if expect_exchange: + httpx_mock.add_response(method="GET", url=DISCOVERY_URL, json={"token_endpoint": TOKEN_ENDPOINT}) + httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="fresh-token")) + + result = await api_client_confidential.get_token_on_behalf_of( + access_token=access_token, + audience=audience, + verified=verified_for(access_token, "auth0|user1"), + ) + + assert result["access_token"] == ("fresh-token" if expect_exchange else "cached-token") + assert len([r for r in httpx_mock.get_requests() if r.method == "POST"]) == int(expect_exchange) + + @pytest.mark.asyncio async def test_get_token_on_behalf_of_corrupt_store_value_treated_as_cache_miss( mock_discovery, httpx_mock @@ -4444,6 +4539,32 @@ async def test_get_client_credentials_token_cache_miss_after_expiry( assert len(token_requests) == 1 +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("seconds_left", "expect_exchange"), + [(10, True), (3600, False)], + ids=["within-buffer-is-refreshed", "beyond-buffer-is-reused"], +) +async def test_get_client_credentials_token_cache_entry_expiry_buffer( + api_client_confidential, httpx_mock, seconds_left, expect_exchange +): + """A cached M2M entry about to expire is not reused, one with time to spare is.""" + audience = "https://billing-api.example.com" + cache_key = m2m_cache_key(tenant="auth0.local", client_id="cid", audience=audience, scopes=None) + await api_client_confidential._token_store.set( + cache_key, + {"access_token": "cached-m2m-token", "expires_at": int(time.time()) + seconds_left}, + ) + if expect_exchange: + httpx_mock.add_response(method="GET", url=DISCOVERY_URL, json={"token_endpoint": TOKEN_ENDPOINT}) + httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="fresh-m2m-token")) + + result = await api_client_confidential.get_client_credentials_token(audience=audience) + + assert result["access_token"] == ("fresh-m2m-token" if expect_exchange else "cached-m2m-token") + assert len([r for r in httpx_mock.get_requests() if r.method == "POST"]) == int(expect_exchange) + + @pytest.mark.asyncio async def test_get_client_credentials_token_expired_entry_from_store_is_not_served( mock_discovery, httpx_mock @@ -4876,6 +4997,39 @@ async def test_nss_index_expired_member_not_reused(mock_discovery, httpx_mock): assert len(post_requests) == 1 +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("seconds_left", "expect_exchange"), + [(10, True), (3600, False)], + ids=["within-buffer-is-refreshed", "beyond-buffer-is-reused"], +) +async def test_nss_index_member_expiry_buffer(httpx_mock, seconds_left, expect_exchange): + """Index: a member about to expire is not reused, one with time to spare is.""" + client = _nss_client() + token = make_access_token("auth0|user1") + audience = "https://api.example.com" + expires_at = int(time.time()) + seconds_left + + token_key = index_token_key(token, audience=audience, scopes="read:x") + await client._token_store.add_index_member(index_key(token, audience=audience), { + "token_key": token_key, + "granted_scopes": "read:x", + "expires_at": expires_at, + }) + await client._token_store.set( + token_key, + {"access_token": "cached-token", "expires_at": expires_at, "granted_scopes": "read:x"}, + ) + if expect_exchange: + httpx_mock.add_response(method="GET", url=DISCOVERY_URL, json={"token_endpoint": TOKEN_ENDPOINT}) + httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="fresh-token", scope="read:x")) + + result = await client.get_token_on_behalf_of(access_token=token, audience=audience, scope="read:x", verified=verified_for(token, "auth0|user1")) + + assert result["access_token"] == ("fresh-token" if expect_exchange else "cached-token") + assert len([r for r in httpx_mock.get_requests() if r.method == "POST"]) == int(expect_exchange) + + @pytest.mark.asyncio async def test_nss_index_list_failure_falls_back_to_exchange(mock_discovery, httpx_mock): """Index: a failing index read is treated as a miss and a fresh exchange runs.""" @@ -5207,6 +5361,34 @@ async def test_get_access_token_for_connection_cache_miss_after_expiry( assert len(token_requests) == 1 +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("seconds_left", "expect_exchange"), + [(10, True), (3600, False)], + ids=["within-buffer-is-refreshed", "beyond-buffer-is-reused"], +) +async def test_get_access_token_for_connection_cache_entry_expiry_buffer( + api_client_confidential, httpx_mock, seconds_left, expect_exchange +): + """A cached entry about to expire is not reused, one with time to spare is.""" + await api_client_confidential._token_store.set( + tv_key("auth0|user1", "google-oauth2"), + {"access_token": "cached-tv-token", "expires_at": int(time.time()) + seconds_left}, + ) + if expect_exchange: + httpx_mock.add_response(method="GET", url=DISCOVERY_URL, json={"token_endpoint": TOKEN_ENDPOINT}) + 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" if expect_exchange else "cached-tv-token") + assert len([r for r in httpx_mock.get_requests() if r.method == "POST"]) == int(expect_exchange) + + @pytest.mark.asyncio async def test_get_access_token_for_connection_different_connection_not_reused( mock_discovery, api_client_confidential, httpx_mock diff --git a/tests/test_cache.py b/tests/test_cache.py index 0da582f..7229965 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -1,5 +1,8 @@ import time +import pytest + +from auth0_api_python._internal.cache_expiry import is_fresh from auth0_api_python.cache import InMemoryCache # ===== InMemoryCache Basic Operations ===== @@ -168,5 +171,12 @@ def test_in_memory_cache_lru_access_order(): assert cache.get("key4") == "value4" +# ===== Expiry Buffer ===== + +@pytest.mark.parametrize(("seconds_left", "expected"), [(29, False), (30, False), (31, True)]) +def test_is_fresh_requires_more_than_the_buffer(seconds_left, expected): + """An entry is fresh only with more than 30 seconds left.""" + now = 1_700_000_000 + assert is_fresh(now + seconds_left, now) is expected