Skip to content

Commit a941898

Browse files
fix(token-vault): address review feedback on connection token caching
- Return scope on every cache hit so it matches a fresh result - Include login_hint in the cache key - Skip the cache for a non-string sub and treat wrongly typed stored entries as a miss - Document the organization errors and fix the VerifiedToken usage in the examples
1 parent d75882f commit a941898

7 files changed

Lines changed: 154 additions & 23 deletions

File tree

‎EXAMPLES.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,10 +161,10 @@ async with httpx.AsyncClient() as client:
161161

162162
### With caching
163163

164-
Pass a `token_store` to cache the connection token. The SDK caches by `sub` (caller) and `connection`, skipping the exchange on repeat calls for the same user and provider. Pass `verified=` with the result of `verify_access_token()` to reuse that verification rather than running it again inside the exchange.
164+
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.
165165

166166
```python
167-
from auth0_api_python import ApiClient, ApiClientOptions
167+
from auth0_api_python import ApiClient, ApiClientOptions, VerifiedToken
168168

169169
# token_store is your AbstractTokenStore implementation.
170170
# See docs/TokenStorage.md for how to build one and for encryption details.
@@ -179,11 +179,11 @@ api_client = ApiClient(ApiClientOptions(
179179
incoming_access_token = "incoming-auth0-access-token"
180180

181181
# Verify once, then pass the result to avoid a second verification inside the exchange.
182-
verified = await api_client.verify_access_token(access_token=incoming_access_token)
182+
claims = await api_client.verify_access_token(access_token=incoming_access_token)
183183

184184
result = await api_client.get_access_token_for_connection(
185185
{"connection": "google-oauth2", "access_token": incoming_access_token},
186-
verified=verified,
186+
verified=VerifiedToken(access_token=incoming_access_token, claims=claims),
187187
)
188188
```
189189

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ async def main():
122122
asyncio.run(main())
123123
```
124124

125-
When a `token_store` is configured on `ApiClientOptions`, the connection token is cached by caller and connection, skipping the exchange on repeat calls. Pass `verified=` to reuse an already-verified token 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.
125+
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.
126126

127127
More info https://auth0.com/docs/secure/tokens/token-vault
128128

‎src/auth0_api_python/_internal/cache_keys.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,9 @@ def m2m_cache_key(*, tenant: str, client_id: str, audience: str, scopes: Optiona
143143
return hashlib.sha256(fields.encode()).hexdigest()
144144

145145

146-
def token_vault_cache_key(*, sub: str, connection: str, tenant: str, client_id: str) -> str:
147-
"""Cache key for a Token Vault exchange, scoped to tenant, client, caller, and connection."""
148-
fields = _FIELD_SEPARATOR.join(["token_vault", tenant, client_id, sub, connection])
146+
def token_vault_cache_key(
147+
*, sub: str, connection: str, tenant: str, client_id: str, login_hint: Optional[str] = None
148+
) -> str:
149+
"""Cache key for a Token Vault exchange, scoped to tenant, client, caller, connection, and login hint."""
150+
fields = _FIELD_SEPARATOR.join(["token_vault", tenant, client_id, sub, connection, login_hint or ""])
149151
return hashlib.sha256(fields.encode()).hexdigest()

‎src/auth0_api_python/_internal/token_vault_cache.py‎

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import logging
44
import time
5-
from typing import Optional
5+
from typing import Any, Optional
66

77
from ..token_store import AbstractTokenStore, TokenSet
88
from .cache_keys import _normalized_scopes, token_vault_cache_key
@@ -20,12 +20,16 @@ class TokenVaultCache:
2020
def __init__(self, token_store: AbstractTokenStore) -> None:
2121
self._store = token_store
2222

23-
def cache_key(self, tenant: str, client_id: str, sub: Optional[str], connection: str) -> Optional[str]:
24-
"""Return the cache key, or None when sub is absent (cache skipped with a warning)."""
25-
if not sub:
23+
def cache_key(
24+
self, tenant: str, client_id: str, sub: Any, connection: str, login_hint: Optional[str] = None
25+
) -> Optional[str]:
26+
"""Return the cache key, or None when sub is not a usable string (cache skipped with a warning)."""
27+
if not isinstance(sub, str) or not sub:
2628
logger.warning("Access token has no usable sub claim, skipping Token Vault cache")
2729
return None
28-
return token_vault_cache_key(sub=sub, connection=connection, tenant=tenant, client_id=client_id)
30+
return token_vault_cache_key(
31+
sub=sub, connection=connection, tenant=tenant, client_id=client_id, login_hint=login_hint
32+
)
2933

3034
async def lookup(self, key: str) -> Optional[dict]:
3135
"""Return a live cached token or None. Miss cases: absent, malformed, expired."""
@@ -38,21 +42,21 @@ async def lookup(self, key: str) -> Optional[dict]:
3842

3943
if cached is None:
4044
return None
41-
if "access_token" not in cached or "expires_at" not in cached:
45+
access_token = cached.get("access_token")
46+
expires_at = cached.get("expires_at")
47+
if not isinstance(access_token, str) or not access_token or not isinstance(expires_at, int):
4248
logger.warning("Token store returned a malformed entry, treating as cache miss")
4349
return None
44-
if cached["expires_at"] <= int(time.time()):
50+
now = int(time.time())
51+
if expires_at <= now:
4552
return None
4653

47-
result = {
48-
"access_token": cached["access_token"],
49-
"expires_in": cached["expires_at"] - int(time.time()),
50-
"expires_at": cached["expires_at"],
54+
return {
55+
"access_token": access_token,
56+
"expires_in": expires_at - now,
57+
"expires_at": expires_at,
58+
"scope": cached.get("granted_scopes") or "",
5159
}
52-
granted = cached.get("granted_scopes")
53-
if granted:
54-
result["scope"] = granted
55-
return result
5660

5761
async def write(self, key: str, result: dict) -> None:
5862
"""Store a freshly exchanged connection token. Failures are logged and swallowed."""

‎src/auth0_api_python/api_client.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -752,6 +752,8 @@ async def get_access_token_for_connection(
752752
GetAccessTokenForConnectionError: If there was an issue requesting the access token.
753753
ApiError: If the token exchange endpoint returns an error.
754754
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.
755+
MissingOrganizationError: If a store is configured, verified is omitted, organization_policy is "required" and the token has no org_id claim.
756+
OrganizationNotAllowedError: If a store is configured, verified is omitted and the token's org_id is not in the organization_id allowlist.
755757
756758
Returns:
757759
Dictionary containing the token response with access_token, expires_in, and scope.
@@ -789,6 +791,7 @@ async def get_access_token_for_connection(
789791
client_id=self.options.client_id or "",
790792
sub=verified.claims.get("sub"),
791793
connection=connection,
794+
login_hint=options.get("login_hint"),
792795
)
793796

794797
if cache_key is not None:

‎tests/test_api_client.py‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5096,6 +5096,59 @@ async def test_get_access_token_for_connection_cache_hit(
50965096
assert len(token_requests) == 1
50975097

50985098

5099+
@pytest.mark.asyncio
5100+
@pytest.mark.parametrize("exchange_scope", [{"scope": "read:calendar"}, {}])
5101+
async def test_get_access_token_for_connection_cache_hit_matches_fresh_result(
5102+
mock_discovery, api_client_confidential, httpx_mock, exchange_scope
5103+
):
5104+
"""A cache hit carries the same keys as a fresh result, with or without a scope in the exchange response."""
5105+
httpx_mock.add_response(
5106+
method="POST",
5107+
url=TOKEN_ENDPOINT,
5108+
json=token_success(access_token="tv-access-token", **exchange_scope),
5109+
)
5110+
5111+
token = make_access_token("auth0|user1")
5112+
verified = verified_for(token)
5113+
options = {"connection": "google-oauth2", "access_token": token}
5114+
5115+
fresh = await api_client_confidential.get_access_token_for_connection(options, verified=verified)
5116+
hit = await api_client_confidential.get_access_token_for_connection(options, verified=verified)
5117+
5118+
assert hit.keys() == fresh.keys()
5119+
assert hit["scope"] == fresh["scope"]
5120+
assert hit["expires_at"] == fresh["expires_at"]
5121+
assert 0 < hit["expires_in"] <= fresh["expires_in"]
5122+
token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"]
5123+
assert len(token_requests) == 1
5124+
5125+
5126+
@pytest.mark.asyncio
5127+
async def test_get_access_token_for_connection_different_login_hint_not_reused(
5128+
mock_discovery, api_client_confidential, httpx_mock
5129+
):
5130+
"""Two linked accounts on one connection each get their own token, and each hint then hits its own entry."""
5131+
httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="tv-account-a"))
5132+
httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="tv-account-b"))
5133+
5134+
token = make_access_token("auth0|user1")
5135+
verified = verified_for(token)
5136+
5137+
def options(hint):
5138+
return {"connection": "google-oauth2", "access_token": token, "login_hint": hint}
5139+
5140+
a1 = await api_client_confidential.get_access_token_for_connection(options("a@example.com"), verified=verified)
5141+
b1 = await api_client_confidential.get_access_token_for_connection(options("b@example.com"), verified=verified)
5142+
a2 = await api_client_confidential.get_access_token_for_connection(options("a@example.com"), verified=verified)
5143+
b2 = await api_client_confidential.get_access_token_for_connection(options("b@example.com"), verified=verified)
5144+
5145+
assert [a1["access_token"], b1["access_token"]] == ["tv-account-a", "tv-account-b"]
5146+
assert a2["access_token"] == "tv-account-a"
5147+
assert b2["access_token"] == "tv-account-b"
5148+
token_requests = [r for r in httpx_mock.get_requests() if r.method == "POST"]
5149+
assert len(token_requests) == 2
5150+
5151+
50995152
@pytest.mark.asyncio
51005153
async def test_get_access_token_for_connection_cache_miss_after_expiry(
51015154
mock_discovery, api_client_confidential, httpx_mock
@@ -5253,6 +5306,74 @@ async def test_get_access_token_for_connection_no_sub_skips_cache(
52535306
assert any("no usable sub" in record.message for record in caplog.records)
52545307

52555308

5309+
@pytest.mark.asyncio
5310+
async def test_get_access_token_for_connection_non_string_sub_skips_cache(
5311+
mock_discovery, api_client_confidential, httpx_mock, caplog
5312+
):
5313+
"""A non-string sub skips caching with a warning instead of failing the exchange."""
5314+
httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="tv-token-1"))
5315+
httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="tv-token-2"))
5316+
5317+
token = make_access_token("auth0|user1")
5318+
bad_sub = VerifiedToken(access_token=token, claims={"sub": 12345, "iss": CONFIDENTIAL_ISS})
5319+
5320+
caplog.set_level(logging.WARNING)
5321+
result1 = await api_client_confidential.get_access_token_for_connection(
5322+
{"connection": "google-oauth2", "access_token": token}, verified=bad_sub
5323+
)
5324+
result2 = await api_client_confidential.get_access_token_for_connection(
5325+
{"connection": "google-oauth2", "access_token": token}, verified=bad_sub
5326+
)
5327+
5328+
assert result1["access_token"] == "tv-token-1"
5329+
assert result2["access_token"] == "tv-token-2"
5330+
assert any("no usable sub" in record.message for record in caplog.records)
5331+
5332+
5333+
class _StubMalformedEntryTokenStore(InMemoryTokenStore):
5334+
"""Token store whose get() returns a fixed entry."""
5335+
5336+
def __init__(self, entry):
5337+
super().__init__()
5338+
self._entry = entry
5339+
5340+
async def get(self, key: str):
5341+
return self._entry
5342+
5343+
5344+
@pytest.mark.asyncio
5345+
@pytest.mark.parametrize(
5346+
"entry",
5347+
[
5348+
{"access_token": "cached", "expires_at": "9999999999"},
5349+
{"access_token": "cached", "expires_at": None},
5350+
{"access_token": "", "expires_at": 9999999999},
5351+
{"access_token": 123, "expires_at": 9999999999},
5352+
],
5353+
)
5354+
async def test_get_access_token_for_connection_malformed_entry_is_a_miss(
5355+
mock_discovery, httpx_mock, caplog, entry
5356+
):
5357+
"""An entry with a wrong-typed field is treated as a miss and the exchange still succeeds."""
5358+
api_client = ApiClient(ApiClientOptions(
5359+
domain="auth0.local",
5360+
audience="my-audience",
5361+
client_id="cid",
5362+
client_secret="csecret",
5363+
token_store=_StubMalformedEntryTokenStore(entry),
5364+
))
5365+
httpx_mock.add_response(method="POST", url=TOKEN_ENDPOINT, json=token_success(access_token="fresh-tv-token"))
5366+
5367+
token = make_access_token("auth0|user1")
5368+
caplog.set_level(logging.WARNING)
5369+
result = await api_client.get_access_token_for_connection(
5370+
{"connection": "google-oauth2", "access_token": token}, verified=verified_for(token)
5371+
)
5372+
5373+
assert result["access_token"] == "fresh-tv-token"
5374+
assert any("malformed entry" in record.message for record in caplog.records)
5375+
5376+
52565377
@pytest.mark.asyncio
52575378
async def test_get_access_token_for_connection_no_verified_calls_verify(
52585379
mock_discovery, api_client_confidential, httpx_mock, monkeypatch

‎tests/test_token_store.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,7 @@ def test_token_vault_cache_key_different_inputs_different_key():
272272
assert token_vault_cache_key(sub="sub1", connection="conn2", tenant="", client_id="") != base
273273
assert token_vault_cache_key(sub="sub1", connection="conn1", tenant="t1", client_id="") != base
274274
assert token_vault_cache_key(sub="sub1", connection="conn1", tenant="", client_id="c1") != base
275+
assert token_vault_cache_key(sub="sub1", connection="conn1", tenant="", client_id="", login_hint="a@example.com") != base
275276

276277

277278
# ===== session_fingerprint =====

0 commit comments

Comments
 (0)