The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: recover frozen local config credentials from their profile source
Tekniumf1da7833aad1
diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex 0d2fd76bbdd..d1a96dc2620 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -27,9 +27,8 @@ class LocalSessionPolicy:def config(self, authority=None):config = json.loads(self.config_json)if self.config_secret_ref is not None and authority is not None:- secrets = getattr(authority, '_local_config_secrets', {}).get(self.config_secret_ref)- if secrets is None:- raise RuntimeStoreError('launch_credentials_unavailable')+ from gateway.session_policy_credentials import recover_config_secrets+ secrets = recover_config_secrets(authority, self)for path, value in secrets.items():target = configfor key in path[:-1]:@@ -169,14 +168,18 @@ def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=Noconfigs = getattr(authority, '_local_config_secrets', None)if configs is None:configs = authority._local_config_secrets = {}- if ref in configs and configs[ref] != config_secrets:+ config_ref = ref+ if config_secrets and getattr(authority, 'db', None) is not None:+ from gateway.session_policy_credentials import config_reference+ config_ref = config_reference(authority, session_id, policy, config_secrets)+ if config_ref in configs and configs[config_ref] != config_secrets:raise RuntimeStoreError('admission_conflict')if config_secrets:- configs[ref] = dict(config_secrets)+ configs[config_ref] = dict(config_secrets)if api_key is not None:keys[ref] = api_keyreturn replace(policy, credential_ref=ref if api_key is not None else None,- config_secret_ref=ref if config_secrets else None)+ config_secret_ref=config_ref if config_secrets else None)def launch_key(authority, policy):diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.pynew file mode 100644index 00000000000..338b5ffe466--- /dev/null+++ b/gateway/session_policy_credentials.py@@ -0,0 +1,58 @@+"""Borrow frozen config credentials from the existing profile source, not a vault."""+import hashlib+import hmac+import json+from dataclasses import asdict+from pathlib import Path++from agent.credential_persistence import fingerprint_secret_value+from hermes_state_runtime import RuntimeStoreError++PREFIX = 'profile-config-v1:'+++def policy_identity(policy):+ data = asdict(policy)+ data.pop('credential_ref')+ data.pop('config_secret_ref')+ return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()+++def config_reference(authority, session_id, policy, secrets):+ home = Path(authority.db.db_path).resolve().parent+ return PREFIX + json.dumps({'home': str(home), 'profile': authority.profile_id,+ 'session': session_id, 'policy': policy_identity(policy),+ 'entries': [[list(path), fingerprint_secret_value(value)] for path, value in secrets.items()]},+ sort_keys=True)+++def recover_config_secrets(authority, policy):+ ref = policy.config_secret_ref+ if not ref.startswith(PREFIX):+ values = getattr(authority, '_local_config_secrets', {}).get(ref)+ if values is None:+ raise RuntimeStoreError('launch_credentials_unavailable')+ return values+ try:+ source = json.loads(ref[len(PREFIX):])+ home = Path(authority.db.db_path).resolve().parent+ if (source['home'] != str(home) or source['profile'] != authority.profile_id+ or source['policy'] != policy_identity(policy)):+ raise ValueError('scope mismatch')+ cached = getattr(authority, '_local_config_secrets', {}).get(ref)+ if cached is not None:+ return cached+ from gateway.run import _load_gateway_config+ config = _load_gateway_config(home / 'config.yaml')+ values = {}+ for path, fingerprint in source['entries']:+ value = config+ for key in path:+ value = value[key]+ actual = fingerprint_secret_value(value)+ if actual is None or not hmac.compare_digest(actual, fingerprint):+ raise ValueError('credential changed')+ values[tuple(path)] = value+ return values+ except (KeyError, TypeError, ValueError, AttributeError, OSError) as exc:+ raise RuntimeStoreError('launch_credentials_unavailable') from excdiff --git a/tests/gateway/test_config_policy_recovery.py b/tests/gateway/test_config_policy_recovery.pynew file mode 100644index 00000000000..35844848cdf--- /dev/null+++ b/tests/gateway/test_config_policy_recovery.py@@ -0,0 +1,34 @@+"""Config credentials borrow only their frozen profile source across restart."""+import json+from dataclasses import asdict, replace+from types import SimpleNamespace++import pytest+++def test_config_credentials_recover_only_exact_source(tmp_path, monkeypatch):+ from gateway.session_policy import build_policy, bind_launch_key+ from hermes_state_runtime import RuntimeStoreError+ home = tmp_path / 'profile'+ home.mkdir()+ monkeypatch.setenv('HERMES_HOME', str(home))+ cfg = {'model': {'provider': 'custom', 'api_key': 'owned-config-token',+ 'base_url': 'http://127.0.0.1:1234/v1'}}+ (home / 'config.yaml').write_text(json.dumps(cfg))+ def owner(path=home, profile='owned', instance='new'):+ return SimpleNamespace(db=SimpleNamespace(db_path=path / 'state.db'),+ profile_id=profile, instance_id=instance, epoch=2)+ private = {}+ policy = build_policy({'cwd': str(home), 'model': 'frozen'}, cfg, private_secrets=private)+ policy = bind_launch_key(owner(instance='old'), 'session', policy, None, config_secrets=private)+ assert policy.config(owner())['model']['api_key'] == cfg['model']['api_key']+ assert cfg['model']['api_key'] not in json.dumps(asdict(policy))+ for wrong in (owner(profile='wrong'), owner(path=tmp_path)):+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable'):+ policy.config(wrong)+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable'):+ replace(policy, model='other-policy').config(owner())+ cfg['model']['api_key'] = 'changed-unrelated-token'+ (home / 'config.yaml').write_text(json.dumps(cfg))+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable'):+ policy.config(owner())