Skip to content

The agent that grows with you

fix(gateway): bind config secrets to their resolved endpoint; keep the legacy endpoint guard

Teknium6f29de984541
diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.py
index 028c9937156..55c4dfb60e0 100644
--- a/gateway/session_policy_credentials.py
+++ b/gateway/session_policy_credentials.py
@@ -57,7 +57,7 @@ class RecoveredSecrets(dict):
session = None
-def policy_identity(policy):
+def policy_identity(policy, unhashed=()):
data = asdict(policy)
data.pop('credential_ref')
data.pop('config_secret_ref')
@@ -71,23 +71,65 @@ def policy_identity(policy):
data.pop(name, None)
if not data.get('client_env_remote'):
data.pop('client_env_remote', None)
+ for name in unhashed: # _legacy_identities: a field the stamping gateway did not have yet
+ data.pop(name, None)
return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
+# Policy fields a release added after frozen config secrets shipped, hashed unconditionally by the
+# gateway that added them. A reference an older gateway stamped never hashed them; at their defaults
+# they carry nothing that gateway could have seen, so the same policy without them is its policy.
+_LATER_POLICY_FIELDS = (('skills_prompt', None), ('kanban_json', None), ('safe_mode', False),
+ ('ignore_user_config', False))
+
+
+def _legacy_identities(policy):
+ """Every whole-policy hash a gateway older than ``bound`` could have stamped for *policy*: the
+ current hash, plus each subset of the later fields dropped while they are at their defaults."""
+ from itertools import combinations
+ unset = [name for name, default in _LATER_POLICY_FIELDS if getattr(policy, name) == default]
+ return {policy_identity(policy, dropped)
+ for size in range(len(unset) + 1) for dropped in combinations(unset, size)}
+
+
def _fingerprint(value):
return fingerprint_secret_value(value if isinstance(value, str) else json.dumps(value, sort_keys=True))
# What a frozen secret authenticates: the endpoint fields of the block that holds it (``model:``, a
-# ``providers:`` entry, an MCP server). A secret is bound to these, never to the rest of the policy.
-_ENDPOINT_KEYS = ('provider', 'base_url', 'url', 'command', 'args', 'api_mode')
+# ``providers:`` entry, an MCP server), plus the endpoint its route RESOLVES to when that lives in another
+# block. A secret is bound to these, never to the rest of the policy. ``api`` is an entry's URL field
+# (runtime_provider_custom._entry_url reads it before ``url``/``base_url``).
+_ENDPOINT_KEYS = ('provider', 'base_url', 'api', 'url', 'command', 'args', 'api_mode')
+_ROUTE_SECTIONS = ('model', 'fallback_model', 'fallback_providers')
+_ENTRY_SECTIONS = ('providers', 'custom_providers')
+
+
+def _owner_block(config, path):
+ """The config path of the block whose endpoint the secret at *path* authenticates: a route block
+ (``model``, a fallback entry) or a provider entry as a whole, else the secret's own parent block."""
+ if path[0] in _ENTRY_SECTIONS or path[0] == 'fallback_providers':
+ return tuple(path[:2])
+ if path[0] == 'fallback_model' and isinstance(config.get('fallback_model'), list):
+ return tuple(path[:2])
+ if path[0] in _ROUTE_SECTIONS:
+ return tuple(path[:1])
+ return tuple(path[:-1])
def _binding(config, path):
"""Digest of the endpoint the secret at *path* authenticates in the frozen *config* (a terminal-scope
secret, ``path[0] is None``, authenticates no endpoint)."""
- block = _defined(config, path[:-1]) if path and path[0] is not None else _ABSENT
+ owner = _owner_block(config, path) if path and path[0] is not None else None
+ block = _defined(config, owner) if owner else _ABSENT
endpoint = {k: block[k] for k in _ENDPOINT_KEYS if k in block} if isinstance(block, dict) else {}
+ if isinstance(block, dict) and path[0] in _ROUTE_SECTIONS:
+ # A route's key authenticates what it resolves to: a named ``providers:`` entry's URL included.
+ from gateway.session_route_identity import resolved_route
+ endpoint['resolved'] = list(resolved_route(block, config))
+ elif isinstance(block, dict) and path[0] in _ENTRY_SECTIONS:
+ from hermes_cli.runtime_provider_custom import _entry_url
+ endpoint['resolved'] = str(_entry_url(block) or '')
return hashlib.sha256(json.dumps([list(path), endpoint], sort_keys=True).encode()).hexdigest()
@@ -116,12 +158,12 @@ def _check_scope(authority, source, policy, home, skip):
raise RuntimeStoreError('launch_credentials_unavailable', field=name,
detail=f'the frozen config credentials belong to another {name}')
if 'bound' not in source:
- # Stamped before ``bound``: its whole-policy hash also covers fields an older gateway did not
- # know and settings no secret depends on, so a mismatch alone proves no credential change. The
- # per-entry fingerprints below still gate every value; the next re-bind writes ``bound``.
- if source['policy'] != policy_identity(policy):
- logger.warning('Session %s: frozen config reference predates scoped credential binding; '
- 'verifying its entries by fingerprint', source.get('session'))
+ # Stamped before ``bound``: its whole-policy hash is its only endpoint guard, so it must still
+ # match -- allowing for the policy fields added since, at their defaults (_legacy_identities).
+ # The next re-bind writes ``bound``.
+ if source['policy'] not in _legacy_identities(policy):
+ raise RuntimeStoreError('launch_credentials_unavailable', field='config_secret_ref',
+ detail='stamped by an older gateway for another session policy')
return
config = json.loads(policy.config_json)
for path, digest in source['bound']:
diff --git a/tests/gateway/test_config_secret_scope.py b/tests/gateway/test_config_secret_scope.py
index d766353bac5..a66914fbd3a 100644
--- a/tests/gateway/test_config_secret_scope.py
+++ b/tests/gateway/test_config_secret_scope.py
@@ -219,3 +219,82 @@ def test_a_secret_paired_with_a_moved_endpoint_is_refused_by_name(tmp_path, monk
with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable') as refused:
replace(policy, config_json=json.dumps(config)).config(owner())
assert refused.value.field == field and 'endpoint' in refused.value.detail
+
+
+def _bind(tmp_path, monkeypatch, cfg):
+ from gateway.session_policy import bind_launch_key, build_policy
+ home = tmp_path / 'profile'
+ home.mkdir(exist_ok=True)
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ (home / 'config.yaml').write_text(json.dumps(cfg))
+
+ def owner():
+ return SimpleNamespace(db=SimpleNamespace(db_path=home / 'state.db'), profile_id='owned',
+ instance_id='new', epoch=2)
+ private = {}
+ policy = build_policy({'cwd': str(home), 'model': 'frozen'}, cfg, private_secrets=private)
+ return owner, bind_launch_key(owner(), 'session', policy, None, config_secrets=private)
+
+
+def _repointed(policy, mutate):
+ config = json.loads(policy.config_json)
+ mutate(config)
+ return replace(policy, config_json=json.dumps(config))
+
+
+# Each secret authenticates the endpoint its route RESOLVES to, which can live in another block: a keyless
+# ``providers:`` entry the ``model:`` route names, a fallback's provider entry, an entry's ``api`` URL.
+_ROUTED = {
+ 'entry_api_url': ({'model': {'provider': 'p2', 'default': 'm'},
+ 'providers': {'p2': {'api': 'http://good.invalid/v1', 'api_key': 'K-p2'}}},
+ lambda c: c['providers']['p2'].__setitem__('api', 'http://evil.invalid/v1'),
+ 'providers.p2.api_key'),
+ 'model_key_keyless_entry': ({'model': {'provider': 'myprov', 'default': 'm', 'api_key': 'K-model'},
+ 'providers': {'myprov': {'base_url': 'http://good.invalid/v1'}}},
+ lambda c: c['providers']['myprov'].__setitem__('base_url', 'http://evil.invalid/v1'),
+ 'model.api_key'),
+ 'fallback_key_via_entry': ({'model': {'provider': 'custom', 'default': 'm', 'base_url': 'http://good.invalid/v1'},
+ 'providers': {'fb': {'base_url': 'http://good-fb.invalid/v1'}},
+ 'fallback_providers': [{'provider': 'fb', 'model': 'x', 'api_key': 'K-fb'}]},
+ lambda c: c['providers']['fb'].__setitem__('base_url', 'http://evil.invalid/v1'),
+ 'fallback_providers.0.api_key'),
+}
+
+
[email protected]('case', sorted(_ROUTED))
+def test_a_secret_is_bound_to_the_endpoint_its_route_resolves_to(tmp_path, monkeypatch, case):
+ """Independent review P2-2: moving the URL the secret actually authenticates, even when it lives in
+ another block or under ``api``, refuses the secret by name instead of pairing it with the new URL."""
+ from hermes_state_runtime import RuntimeStoreError
+ cfg, mutate, field = _ROUTED[case]
+ owner, policy = _bind(tmp_path, monkeypatch, cfg)
+ assert policy.config(owner()) # the unmoved policy recovers
+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable') as refused:
+ _repointed(policy, mutate).config(owner())
+ assert refused.value.field == field and 'endpoint' in refused.value.detail
+
+
+def _legacy(policy):
+ """*policy*'s reference as an older gateway wrote it: no ``bound``, the policy hash over the fields it had."""
+ from gateway.session_policy_credentials import PREFIX
+ source = json.loads(policy.config_secret_ref[len(PREFIX):])
+ data = {k: v for k, v in asdict(policy).items()
+ if k not in ('credential_ref', 'config_secret_ref', *_LATER_FIELDS)}
+ source['policy'] = hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
+ source.pop('bound', None)
+ return replace(policy, config_secret_ref=PREFIX + json.dumps(source, sort_keys=True))
+
+
+def test_a_legacy_reference_keeps_the_endpoint_guard(tmp_path, monkeypatch):
+ """Independent review P2-3: a reference without ``bound`` still matches its own policy (the later
+ fields at their defaults are not hashed), but a moved endpoint, or any other policy rewrite its whole-
+ policy hash covers, is refused instead of degrading to the fingerprints alone."""
+ from hermes_state_runtime import RuntimeStoreError
+ _home_dir, _cfg, owner, policy = _bound_policy(tmp_path, monkeypatch)
+ legacy = _legacy(policy)
+ assert legacy.config(owner())['model']['api_key'] == 'route-token'
+ for moved in (_repointed(legacy, lambda c: c['model'].__setitem__('base_url', 'http://evil.invalid/v1')),
+ replace(legacy, skills_prompt='set after the stamp')):
+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable') as refused:
+ moved.config(owner())
+ assert refused.value.field == 'config_secret_ref' and refused.value.detail