The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(vertex): content-digest cache key — stat signature is not credential identity
kshitijk4poor913b910434b3
diff --git a/agent/vertex_adapter.py b/agent/vertex_adapter.pyindex 36f6a9922a2..50747648b09 100644--- a/agent/vertex_adapter.py+++ b/agent/vertex_adapter.py@@ -16,6 +16,8 @@ Non-secret routing settings (project_id, region) also live in config.yamlunder the ``vertex:`` section; env vars take precedence over config.yaml."""+import hashlib+import jsonimport loggingimport osimport time@@ -108,26 +110,44 @@ def _refresh_credentials(creds) -> None:creds.refresh(auth_req)+def _read_sa_file(resolved_path: str) -> Tuple[bytes, Tuple[Any, ...]]:+ """Read the service-account file once, returning (bytes, cache key).++ The cache key fingerprints the file CONTENT (sha256), not stat+ metadata. A (path, mtime_ns, size) signature — the idiom used for+ config caches — is not sufficient here: metadata-preserving atomic+ replacement (deployment tools that restore mtime; equal-length JSON)+ produces a different private key under an identical stat signature,+ and this cache guards an identity, not a parse (review finding on+ #97701, reproduced: inode/content changed, stat key equal). Reading+ the bytes also lets the caller construct credentials from the SAME+ snapshot the key was computed from, closing the stat->read TOCTOU.++ The file is a few KB of JSON; one read + sha256 per cache PROBE is+ noise next to the OAuth token mint the cache exists to avoid.+ """+ with open(resolved_path, "rb") as fh:+ raw = fh.read()+ digest = hashlib.sha256(raw).hexdigest()+ return raw, (resolved_path, digest)++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+ Content-digest keyed via _read_sa_file (see there for why stat+ signatures are not enough for credential identity). ADC has no file+ to fingerprint; it keeps a plain sentinel key and its existingrefresh/expiry handling.- A stat failure falls back to the bare path: worst case we serve the+ A read failure falls back to the bare path: worst case we serve thecached 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)+ _, key = _read_sa_file(resolved_path)+ return keyexcept OSError:return (resolved_path,)@@ -143,16 +163,34 @@ def get_vertex_credentials(credentials_path: Optional[str] = None) -> Tuple[Optireturn None, Noneresolved_path = _resolve_credentials_path(credentials_path)- cache_key = _creds_cache_key(resolved_path)+ sa_raw: Optional[bytes] = None+ if resolved_path:+ try:+ # One read serves both the cache key and (on a miss) credential+ # construction, so the credentials always match the bytes the+ # key fingerprints — no stat/read or read/read TOCTOU.+ sa_raw, cache_key = _read_sa_file(resolved_path)+ except OSError:+ cache_key = (resolved_path,)+ else:+ cache_key = ("__adc__",)try:cached = _creds_cache.get(cache_key)if cached is None:if resolved_path:- creds = service_account.Credentials.from_service_account_file(- resolved_path,- scopes=["https://www.googleapis.com/auth/cloud-platform"],- )+ if sa_raw is not None:+ creds = service_account.Credentials.from_service_account_info(+ json.loads(sa_raw),+ scopes=["https://www.googleapis.com/auth/cloud-platform"],+ )+ else:+ # Unreadable at key time (bare-path key): let the SDK+ # try the file directly — pre-signature behavior.+ creds = service_account.Credentials.from_service_account_file(+ resolved_path,+ scopes=["https://www.googleapis.com/auth/cloud-platform"],+ )project_id = creds.project_idelse:# google.auth.default() reads GOOGLE_APPLICATION_CREDENTIALSdiff --git a/tests/agent/test_vertex_adapter.py b/tests/agent/test_vertex_adapter.pyindex 4910ca13c5c..145ccc7d84c 100644--- a/tests/agent/test_vertex_adapter.py+++ b/tests/agent/test_vertex_adapter.py@@ -52,6 +52,12 @@ def _install_fake_google_auth(monkeypatch, *, adc_ok=True, adc_project="adc-projc.project_id = sa_projectreturn c+ @staticmethod+ def from_service_account_info(info, scopes=None):+ c = _Creds()+ c.project_id = sa_project+ return c+gsa.Credentials = _SAgo.service_account = gsagp.auth = ga@@ -242,3 +248,36 @@ def test_adc_failure_retries_with_late_added_sa_file(vertex_adapter, monkeypatchassert token == "ya29.FAKE"assert project == "sa-project"assert calls["n"] >= 2+++def test_metadata_preserving_rotation_invalidates_creds_cache(vertex_adapter, monkeypatch, tmp_path):+ """Atomic replacement that keeps SIZE and MTIME identical (deployment+ tools that restore metadata; equal-length JSON) must still be picked up.+ Review finding on #97701: a (path, mtime_ns, size) stat signature keyed+ the cache, so this replacement served the old private key; the key is+ now a content digest."""+ import os as _os++ sa_file = tmp_path / "sa.json"+ sa_file.write_text('{"project_id": "AAAA-identity"}')+ monkeypatch.setattr(+ vertex_adapter, "_resolve_credentials_path", lambda explicit=None: str(sa_file)+ )++ vertex_adapter.get_vertex_credentials()+ (key1,) = vertex_adapter._creds_cache+ creds_obj_1 = vertex_adapter._creds_cache[key1][0]++ # Same-length content, mtime restored, atomic replace.+ st = _os.stat(sa_file)+ new = tmp_path / "sa.json.new"+ new.write_text('{"project_id": "BBBB-identity"}') # equal length+ _os.utime(new, ns=(st.st_atime_ns, st.st_mtime_ns))+ _os.replace(new, sa_file)+ st2 = _os.stat(sa_file)+ assert st2.st_size == st.st_size and st2.st_mtime_ns == st.st_mtime_ns++ vertex_adapter.get_vertex_credentials()+ (key2,) = vertex_adapter._creds_cache+ assert key2 != key1, "content change must produce a new cache key"+ assert vertex_adapter._creds_cache[key2][0] is not creds_obj_1