Skip to content

Commit bc252de

Browse files
committed
fix(sts): fail closed on a raising get_subject_token and gate the cache sweep
A caller-supplied get_subject_token that raises no longer aborts the agent run; token propagation is skipped instead. The expired-token sweep stays global, since scoping it to the running session would keep the entries of sessions that never run again forever, but it is now gated on the earliest expiry in the cache so a growing cache is only walked when there is something to evict. Signed-off-by: QuentinBisson <[email protected]>
1 parent e4fb32e commit bc252de

2 files changed

Lines changed: 105 additions & 8 deletions

File tree

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

Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ def __init__(
151151
self.audience = audience
152152
self.token_cache: Dict[str, _TokenCacheEntry] = {}
153153
self.actor_token_cache: Optional[_TokenCacheEntry] = None
154+
# Earliest expiry across token_cache; None when no cached token expires.
155+
self._earliest_expiry: Optional[int] = None
154156

155157
def add_to_agent(self, agent: BaseAgent):
156158
"""
@@ -240,17 +242,26 @@ async def before_run_callback(
240242
token=subject_token,
241243
expiry=expiry,
242244
)
245+
self._earliest_expiry = _earlier_expiry(self._earliest_expiry, expiry)
243246
logger.debug("Cached new subject token")
244247
return None
245248

246249
def _read_subject_token(self, state: dict) -> Optional[str]:
247-
"""Resolve the acting caller's subject token from session state."""
250+
"""Resolve the acting caller's subject token from session state.
251+
252+
get_subject_token is caller-supplied, so a raising implementation fails
253+
closed (no token propagated) instead of aborting the agent run.
254+
"""
248255
get_subject_token = (
249256
self.sts_integration.get_subject_token
250257
if self.sts_integration and self.sts_integration.get_subject_token
251258
else _default_get_subject_token
252259
)
253-
return get_subject_token(state)
260+
try:
261+
return get_subject_token(state)
262+
except Exception as e:
263+
logger.warning(f"Failed to read subject token from session state: {e}")
264+
return None
254265

255266
def _cache_key_for(self, session_id: str, subject_token: Optional[str]) -> str:
256267
return f"{session_id}\0{_subject_key(subject_token)}"
@@ -314,12 +325,7 @@ async def after_run_callback(
314325
invocation_context: InvocationContext,
315326
) -> Optional[dict]:
316327
"""Clean up expired tokens after run, preserving valid tokens."""
317-
# A session now holds one entry per subject, and only the acting
318-
# subject's key is derivable here, so sweep every expired entry rather
319-
# than leaving the other subjects' behind.
320-
for key in [key for key, entry in self.token_cache.items() if _has_token_expired(entry.expiry)]:
321-
logger.debug("Removing expired subject token from cache")
322-
self.token_cache.pop(key, None)
328+
self._sweep_expired_subject_tokens()
323329

324330
# Clean up expired actor token cache
325331
if self.actor_token_cache and _has_token_expired(self.actor_token_cache.expiry):
@@ -328,6 +334,37 @@ async def after_run_callback(
328334

329335
return None
330336

337+
def _sweep_expired_subject_tokens(self) -> None:
338+
"""Drop every expired subject token from the cache.
339+
340+
A session holds one entry per subject and only the acting subject's key
341+
is derivable here, so entries belonging to other subjects and other
342+
sessions are swept too; scoping the sweep to the current session would
343+
keep the entries of sessions that never run again forever. The earliest
344+
expiry gates the scan, so a growing cache is only walked when there is
345+
something to evict.
346+
"""
347+
if self._earliest_expiry is None or not _has_token_expired(self._earliest_expiry):
348+
return
349+
350+
earliest_expiry: Optional[int] = None
351+
for key, entry in list(self.token_cache.items()):
352+
if _has_token_expired(entry.expiry):
353+
logger.debug("Removing expired subject token from cache")
354+
self.token_cache.pop(key, None)
355+
continue
356+
earliest_expiry = _earlier_expiry(earliest_expiry, entry.expiry)
357+
self._earliest_expiry = earliest_expiry
358+
359+
360+
def _earlier_expiry(current: Optional[int], candidate: Optional[int]) -> Optional[int]:
361+
"""Return the earlier of two expiries; None means "does not expire"."""
362+
if candidate is None:
363+
return current
364+
if current is None:
365+
return candidate
366+
return min(current, candidate)
367+
331368

332369
def _has_token_expired(expiry: Optional[int], buffer_seconds: int = 5) -> bool:
333370
"""Check if a token has expired or will expire soon.

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

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -831,6 +831,66 @@ async def async_fetch_token():
831831
# Fetch should not be called again
832832
assert fetch_count == 1
833833

834+
@pytest.mark.asyncio
835+
async def test_subject_token_callback_failure_does_not_abort_run(self):
836+
"""Case: a raising get_subject_token fails closed instead of breaking the run."""
837+
838+
def raising_get_subject_token(state):
839+
raise RuntimeError("callback exploded")
840+
841+
sts = Mock(spec=ADKSTSIntegration)
842+
sts.get_subject_token = raising_get_subject_token
843+
sts.fetch_actor_token = None
844+
sts._actor_token = "static-actor"
845+
sts.exchange_token = AsyncMock()
846+
847+
plugin = ADKTokenPropagationPlugin(sts)
848+
ic = self._make_invocation_context("sess-raise", headers={"Authorization": "Bearer subject-token"})
849+
850+
assert await plugin.before_run_callback(invocation_context=ic) is None
851+
assert plugin.token_cache == {}
852+
sts.exchange_token.assert_not_awaited()
853+
assert plugin.header_provider(self._make_readonly_context(ic)) == {}
854+
855+
@pytest.mark.asyncio
856+
async def test_after_run_callback_sweeps_expired_tokens_of_other_sessions(self):
857+
"""Case: the sweep is not scoped to the running session, so entries of
858+
sessions that never run again cannot pile up."""
859+
past_expiry = int(time.time()) - 100
860+
future_expiry = int(time.time()) + 3600
861+
862+
plugin = ADKTokenPropagationPlugin()
863+
expired_ic = self._make_invocation_context("sess-expired", headers={"Authorization": "Bearer AAA"})
864+
live_ic = self._make_invocation_context("sess-live", headers={"Authorization": "Bearer BBB"})
865+
running_ic = self._make_invocation_context("sess-running", headers={"Authorization": "Bearer CCC"})
866+
867+
with patch("agentsts.adk._base._extract_jwt_expiry", return_value=past_expiry):
868+
await plugin.before_run_callback(invocation_context=expired_ic)
869+
with patch("agentsts.adk._base._extract_jwt_expiry", return_value=future_expiry):
870+
await plugin.before_run_callback(invocation_context=live_ic)
871+
await plugin.before_run_callback(invocation_context=running_ic)
872+
873+
await plugin.after_run_callback(invocation_context=running_ic)
874+
875+
assert plugin.cache_key(expired_ic) not in plugin.token_cache
876+
assert plugin.cache_key(live_ic) in plugin.token_cache
877+
assert plugin.cache_key(running_ic) in plugin.token_cache
878+
879+
@pytest.mark.asyncio
880+
async def test_after_run_callback_skips_scan_until_something_expires(self):
881+
"""Case: the cache is only walked once the earliest expiry is reached."""
882+
plugin = ADKTokenPropagationPlugin()
883+
ic = self._make_invocation_context("sess-gate", headers={"Authorization": "Bearer AAA"})
884+
885+
with patch("agentsts.adk._base._extract_jwt_expiry", return_value=int(time.time()) + 3600):
886+
await plugin.before_run_callback(invocation_context=ic)
887+
888+
with patch.object(plugin, "token_cache", wraps=plugin.token_cache) as cache_spy:
889+
await plugin.after_run_callback(invocation_context=ic)
890+
cache_spy.items.assert_not_called()
891+
892+
assert plugin.cache_key(ic) in plugin.token_cache
893+
834894
def test_extract_jwt_from_headers_success(self):
835895
"""Test successful JWT extraction from headers."""
836896
headers = {"Authorization": "Bearer jwt-token-123"}

0 commit comments

Comments
 (0)