Skip to content

The agent that grows with you

fix(vertex): pick up rotated service-account files — signature-keyed creds cache

kshitijk4poor56a262331670
diff --git a/agent/vertex_adapter.py b/agent/vertex_adapter.py
index 190c4beb352..f9150c5eed4 100644
--- a/agent/vertex_adapter.py
+++ b/agent/vertex_adapter.py
@@ -19,7 +19,7 @@ under the ``vertex:`` section; env vars take precedence over config.yaml.
import logging
import os
import time
-from typing import Optional, Tuple
+from typing import Any, Optional, Tuple
from agent.secret_scope import get_secret as _get_secret, is_multiplex_active
@@ -108,6 +108,30 @@ def _refresh_credentials(creds) -> None:
creds.refresh(auth_req)
+def _creds_cache_key(resolved_path: Optional[str]) -> Tuple[Any, ...]:
+ """Cache key for the Credentials object backing *resolved_path*.
+
+ Keyed on the service-account file's (path, mtime_ns, size) signature —
+ the house idiom (agent/skill_utils.py, hermes_cli/config.py,
+ agent/models_dev.py) — so rotating the file on disk (new key, re-issued
+ service account) is picked up on the next call instead of serving
+ tokens minted from the old identity for the life of the process
+ (Pattern D: stale cache after out-of-band change). ADC has no file to
+ fingerprint; it keeps a plain sentinel key and its existing
+ refresh/expiry handling.
+
+ A stat failure falls back to the bare path: worst case we serve the
+ cached credentials exactly as the pre-signature code did.
+ """
+ if not resolved_path:
+ return ("__adc__",)
+ try:
+ st = os.stat(resolved_path)
+ return (resolved_path, st.st_mtime_ns, st.st_size)
+ except OSError:
+ return (resolved_path,)
+
+
def get_vertex_credentials(credentials_path: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]:
"""Return a (fresh access_token, project_id) pair or (None, None) on failure.
@@ -119,7 +143,7 @@ def get_vertex_credentials(credentials_path: Optional[str] = None) -> Tuple[Opti
return None, None
resolved_path = _resolve_credentials_path(credentials_path)
- cache_key = resolved_path or "__adc__"
+ cache_key = _creds_cache_key(resolved_path)
try:
cached = _creds_cache.get(cache_key)
@@ -153,6 +177,15 @@ def get_vertex_credentials(credentials_path: Optional[str] = None) -> Tuple[Opti
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
_creds_cache[cache_key] = (creds, project_id)
+ # A rotation leaves the old signature's entry behind; drop any
+ # other entries for the same path so the cache holds at most one
+ # Credentials per file (bounded, and stale identities don't
+ # linger for surprise reuse via an old key).
+ for k in [
+ k for k in _creds_cache
+ if k is not cache_key and k != cache_key and k[0] == cache_key[0]
+ ]:
+ _creds_cache.pop(k, None)
else:
creds, project_id = cached
diff --git a/tests/agent/test_vertex_adapter.py b/tests/agent/test_vertex_adapter.py
index e0778ef55c4..67de7df9860 100644
--- a/tests/agent/test_vertex_adapter.py
+++ b/tests/agent/test_vertex_adapter.py
@@ -159,3 +159,57 @@ def test_adc_refuses_foreign_profile_google_application_credentials(
+
+
+# --- Pattern D: credential-file rotation invalidates the cache ---
+
+
+def test_sa_file_rotation_invalidates_creds_cache(vertex_adapter, monkeypatch, tmp_path):
+ """Rotating the service-account file on disk must be picked up on the
+ next call — the pre-signature cache served tokens minted from the OLD
+ identity for the life of the process (Pattern D: stale cache after an
+ out-of-band change)."""
+ import os as _os
+
+ sa_file = tmp_path / "sa.json"
+ sa_file.write_text('{"project_id": "first-identity"}')
+ monkeypatch.setattr(
+ vertex_adapter, "_resolve_credentials_path", lambda explicit=None: str(sa_file)
+ )
+
+ token1, project1 = vertex_adapter.get_vertex_credentials()
+ assert token1 == "ya29.FAKE"
+ assert len(vertex_adapter._creds_cache) == 1
+
+ # Same file untouched: cache hit (same Credentials object).
+ (key1,) = vertex_adapter._creds_cache
+ creds_obj_1 = vertex_adapter._creds_cache[key1][0]
+ vertex_adapter.get_vertex_credentials()
+ (key1b,) = vertex_adapter._creds_cache
+ assert key1b == key1
+ assert vertex_adapter._creds_cache[key1b][0] is creds_obj_1
+
+ # Rotate: rewrite the file with different content and a bumped mtime.
+ sa_file.write_text('{"project_id": "second-identity", "rotated": true}')
+ st = _os.stat(sa_file)
+ _os.utime(sa_file, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000))
+
+ vertex_adapter.get_vertex_credentials()
+ # New signature key replaced the old entry — not appended beside it.
+ (key2,) = vertex_adapter._creds_cache
+ assert key2 != key1
+ assert vertex_adapter._creds_cache[key2][0] is not creds_obj_1
+
+
+def test_creds_cache_stat_failure_falls_back_to_path_key(vertex_adapter, monkeypatch):
+ """If the credentials file cannot be stat'ed the key degrades to the bare
+ path — same behavior as the pre-signature cache, never an exception."""
+ key = vertex_adapter._creds_cache_key("/nonexistent/sa.json")
+ assert key == ("/nonexistent/sa.json",)
+
+
+def test_adc_cache_key_is_stable_sentinel(vertex_adapter):
+ """ADC has no file to fingerprint; both None and empty resolve to the
+ same sentinel so repeated ADC calls share one cache entry."""
+ assert vertex_adapter._creds_cache_key(None) == ("__adc__",)
+ assert vertex_adapter._creds_cache_key("") == ("__adc__",)