Skip to content

Commit 6471f57

Browse files
committed
fix(sts): bound cache entries without an expiry and fail closed without a context
Keying the cache by (session, subject) multiplies entries per session, so an entry whose token carries no exp claim now pins one slot per caller instead of one per session. Give those a bounded lifetime so every entry stays evictable, which also arms the sweep gate that a None expiry left unset. header_provider runs on every tool call and dereferenced a private attribute of an optional argument; it now returns no headers instead of raising into the invocation. An issuer-less token leaves sub unqualified; those partition by token hash rather than by a key two issuers could both produce. Signed-off-by: Quentin Bisson <[email protected]>
1 parent 42befc8 commit 6471f57

2 files changed

Lines changed: 67 additions & 11 deletions

File tree

‎python/packages/agentsts-adk/src/agentsts/adk/_base.py‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@
3232

3333
HEADERS_KEY = "headers"
3434

35+
# Bounds an entry whose token carries no usable expiry. The cache holds one entry
36+
# per (session, subject), so a token without an expiry would otherwise pin an
37+
# entry per caller for the lifetime of the process.
38+
MAX_CACHE_TTL_SECONDS = 300
39+
3540

3641
def _default_get_subject_token(state: dict) -> Optional[str]:
3742
"""Default subject token retrieval from Authorization header in session state."""
@@ -43,8 +48,10 @@ def _subject_key(token: Optional[str]) -> str:
4348
"""Derive a stable per-principal cache discriminator from a bearer token.
4449
4550
Prefers the issuer-scoped ``sub`` claim. ``sub`` is unique only within an
46-
issuer, so it is paired with ``iss``. Opaque or sub-less tokens fall back to
47-
a hash of the raw token so they still partition per principal.
51+
issuer, so it is paired with ``iss``. Opaque, sub-less and issuer-less tokens
52+
fall back to a hash of the raw token so they still partition per principal:
53+
an absent ``iss`` leaves ``sub`` unqualified, which two issuers that both omit
54+
it could collide on.
4855
4956
NOTE: this parses the token without verification and uses it only to
5057
partition the cache. On a cache hit the key selects which cached delegated
@@ -59,8 +66,9 @@ def _subject_key(token: Optional[str]) -> str:
5966
except Exception:
6067
claims = {}
6168
sub = claims.get("sub")
62-
if sub:
63-
return f"{claims.get('iss', '')}\0{sub}"
69+
iss = claims.get("iss")
70+
if sub and iss:
71+
return f"{iss}\0{sub}"
6472
return "h:" + hashlib.sha256(token.encode()).hexdigest()
6573

6674

@@ -177,8 +185,14 @@ def add_to_agent(self, agent: BaseAgent):
177185
logger.debug(f"add_to_agent: updated MCP tool's header provider for agent {agent_name}")
178186

179187
def header_provider(self, readonly_context: Optional[ReadonlyContext]) -> Dict[str, str]:
180-
# access saved token
181-
cache_entry = self.token_cache.get(self.cache_key(readonly_context._invocation_context))
188+
# Runs on every tool call, so it fails closed rather than raising into the
189+
# invocation: without a context there is no acting subject to key on.
190+
invocation_context = getattr(readonly_context, "_invocation_context", None)
191+
if invocation_context is None:
192+
logger.debug("no invocation context for tool call, leaving existing headers in place")
193+
return {}
194+
195+
cache_entry = self.token_cache.get(self.cache_key(invocation_context))
182196
if not cache_entry:
183197
return {}
184198

@@ -234,8 +248,11 @@ async def before_run_callback(
234248
logger.warning(f"STS token exchange failed: {e}")
235249
return None
236250

237-
# Extract expiry from the token
251+
# Extract expiry from the token, bounding tokens that carry none so every
252+
# entry stays evictable.
238253
expiry = _extract_jwt_expiry(subject_token)
254+
if expiry is None:
255+
expiry = int(time.time()) + MAX_CACHE_TTL_SECONDS
239256

240257
# Cache the token with metadata
241258
self.token_cache[cache_key] = _TokenCacheEntry(

‎python/packages/agentsts-adk/tests/test_adk_integration.py‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset
1111

1212
from agentsts.adk import ADKSTSIntegration, ADKTokenPropagationPlugin
13-
from agentsts.adk._base import HEADERS_KEY
13+
from agentsts.adk._base import HEADERS_KEY, MAX_CACHE_TTL_SECONDS
1414
from agentsts.adk._base import _extract_jwt_expiry as extract_jwt_expiry
1515
from agentsts.adk._base import _extract_jwt_from_headers as extract_jwt_from_headers
1616
from agentsts.adk._base import _has_token_expired as has_token_expired
@@ -767,7 +767,11 @@ async def test_subject_token_reexchanged_after_expiry(self):
767767

768768
@pytest.mark.asyncio
769769
async def test_subject_token_cache_no_expiry(self):
770-
"""Case: subject token without expiry is cached indefinitely and reused."""
770+
"""Case: subject token without expiry is given a bounded lifetime and reused.
771+
772+
The cache holds one entry per (session, subject), so an entry that never
773+
expires would pin a slot per caller for the lifetime of the process.
774+
"""
771775
sts = Mock(spec=ADKSTSIntegration)
772776
sts.get_subject_token = None
773777
sts.fetch_actor_token = None
@@ -782,9 +786,11 @@ async def test_subject_token_cache_no_expiry(self):
782786
# First call
783787
await plugin.before_run_callback(invocation_context=ic)
784788
assert sts.exchange_token.call_count == 1
785-
assert plugin.token_cache[plugin.cache_key(ic)].expiry is None
789+
expiry = plugin.token_cache[plugin.cache_key(ic)].expiry
790+
assert expiry is not None
791+
assert expiry <= int(time.time()) + MAX_CACHE_TTL_SECONDS
786792

787-
# after_run_callback should preserve it (no expiry)
793+
# after_run_callback preserves it until the bounded lifetime elapses
788794
await plugin.after_run_callback(invocation_context=ic)
789795
assert plugin.cache_key(ic) in plugin.token_cache
790796

@@ -1169,6 +1175,39 @@ def test_subject_key_falls_back_to_hash_for_opaque_tokens(self):
11691175
assert subject_key("opaque-a").startswith("h:")
11701176
assert subject_key(None) == ""
11711177

1178+
def test_subject_key_without_issuer_uses_token_hash(self):
1179+
"""Case: an absent iss leaves sub unqualified, so those partition by hash."""
1180+
import jwt as pyjwt
1181+
1182+
secret = "test-signing-key-of-at-least-32-bytes!"
1183+
no_iss = pyjwt.encode({"sub": "alice"}, secret, algorithm="HS256")
1184+
other_no_iss = pyjwt.encode({"sub": "alice", "jti": "second-issuer"}, secret, algorithm="HS256")
1185+
1186+
assert subject_key(no_iss).startswith("h:")
1187+
assert subject_key(no_iss) != subject_key(other_no_iss)
1188+
1189+
@pytest.mark.asyncio
1190+
async def test_token_without_expiry_stays_evictable(self):
1191+
"""Case: a token carrying no exp is given a bounded lifetime, not an immortal entry."""
1192+
plugin = ADKTokenPropagationPlugin(sts_integration=None)
1193+
ic = self._make_invocation_context("sess-ttl", headers={"Authorization": "Bearer opaque-token"})
1194+
1195+
with patch("agentsts.adk._base._extract_jwt_expiry", return_value=None):
1196+
await plugin.before_run_callback(invocation_context=ic)
1197+
1198+
entry = plugin.token_cache[plugin.cache_key(ic)]
1199+
assert entry.expiry is not None
1200+
assert entry.expiry <= int(time.time()) + MAX_CACHE_TTL_SECONDS
1201+
# The bounded expiry also arms the sweep gate, which a None expiry leaves unset.
1202+
assert plugin._earliest_expiry == entry.expiry
1203+
1204+
def test_header_provider_without_context_fails_closed(self):
1205+
"""Case: a tool call with no invocation context gets no header instead of raising."""
1206+
plugin = ADKTokenPropagationPlugin(sts_integration=None)
1207+
1208+
assert plugin.header_provider(None) == {}
1209+
assert plugin.header_provider(self._make_readonly_context(None)) == {}
1210+
11721211
@pytest.mark.asyncio
11731212
async def test_after_run_sweeps_other_subjects_expired_entries(self):
11741213
"""Case: expired entry for a subject other than the acting one is still evicted."""

0 commit comments

Comments
 (0)