Skip to content

The agent that grows with you

fix(gateway): only a session's own route key can refuse its frozen config

Tekniumd16ed1420855
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.py
index 111c1840e4a..ffda879de4a 100644
--- a/gateway/run_turn_persistence.py
+++ b/gateway/run_turn_persistence.py
@@ -572,6 +572,9 @@ class GatewayTurnPersistenceMixin:
status_hint = t("gateway.errors.hint_usage_limit")
elif status_code == 400:
status_hint = t("gateway.errors.hint_rejected")
+ elif getattr(e, "reason", None) == "launch_credentials_unavailable" and getattr(e, "field", None):
+ # The session's own frozen route credential is gone or changed: name it, not the model.
+ status_hint = f" {e.reason} ({e.field}: {e.detail or 'unavailable'})."
from gateway.session_results import record_unexecuted_failure
return record_unexecuted_failure(self._hmwa_add_failed_turn_notice(
t("gateway.errors.generic_failed_with_hint", hint=status_hint), PARTIAL_FAILED_TURN_NOTICE,
diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.py
index 7f247b94777..887478420c9 100644
--- a/gateway/session_policy_credentials.py
+++ b/gateway/session_policy_credentials.py
@@ -24,6 +24,30 @@ def _defined(root, path):
return value
+def _route_paths(policy):
+ """Secret paths the session's own route authenticates with: its ``model:`` block, a direct alias's
+ key (``api_key_from``) and the ``providers:`` / ``custom_providers:`` entry its provider names."""
+ config = json.loads(policy.config_json)
+ model = config.get('model') if isinstance(config.get('model'), dict) else {}
+ paths = {('model', key) for key in model}
+ if isinstance(model.get('api_key_from'), list):
+ paths.add(tuple(model['api_key_from']))
+ name = str(model.get('provider') or '').strip().lower()
+ name = name.removeprefix('custom:')
+
+ def named(value):
+ return str(value or '').strip().lower().replace(' ', '-') == name.replace(' ', '-')
+ providers = config.get('providers')
+ for key, entry in (providers.items() if isinstance(providers, dict) and name else ()):
+ if named(key) or isinstance(entry, dict) and named(entry.get('name')):
+ paths |= {('providers', key, field) for field in (entry if isinstance(entry, dict) else ())}
+ custom = config.get('custom_providers')
+ for index, entry in (enumerate(custom) if isinstance(custom, list) and name else ()):
+ if isinstance(entry, dict) and named(entry.get('name')):
+ paths |= {('custom_providers', index, field) for field in entry}
+ return paths
+
+
def policy_identity(policy):
data = asdict(policy)
data.pop('credential_ref')
@@ -73,6 +97,7 @@ def recover_config_secrets(authority, policy, skip=None):
from gateway.run import _load_gateway_config
entries = [entry for entry in source['entries'] if entry[0][0] not in skip]
config = _load_gateway_config(home / 'config.yaml') if any(path[0] is not None for path, _ in entries) else {}
+ route = _route_paths(policy)
values = {}
for path, fingerprint in entries:
value, lookup = config, path
@@ -80,24 +105,21 @@ def recover_config_secrets(authority, policy, skip=None):
from tools.terminal_scope import build_profile_terminal_scope
value, lookup = build_profile_terminal_scope(home), path[1:]
value = _defined(value, lookup)
- if value is _ABSENT:
- if len(path) > 1:
- raise ValueError('credential removed')
- # One top-level key the profile no longer defines at all: an env-routed setting the
- # user has since moved out of config.yaml (``API_SERVER_KEY`` belongs in .env, where
- # ``hermes config set`` writes it) is not this session's route credential, and the
- # profile has no value left to recover or to substitute. Refusing it used to wedge
- # every read of the chat - its model options, its reasoning picker, its turns - not
- # just the credential it named, so the session simply keeps what the frozen tree
- # already holds (None). A nested path still refuses: it can carry the route's own
- # credential, and a session must never silently take a different endpoint's key.
- logger.warning('Session %s: frozen config secret %s is no longer defined by the '
- 'profile config; skipping it', source.get('session'), path)
- continue
- actual = _fingerprint(value)
+ actual = None if value is _ABSENT else _fingerprint(value)
if actual is None or not hmac.compare_digest(actual, fingerprint):
- raise ValueError('credential changed')
+ if tuple(path) in route:
+ raise RuntimeStoreError('launch_credentials_unavailable',
+ field='.'.join(str(part) for part in path if part is not None),
+ detail=('removed from' if value is _ABSENT else 'changed in')
+ + ' config.yaml since this session started')
+ # Any other secret (an MCP env token, an unused provider's key) is simply no longer
+ # supplied: the frozen tree holds None there, never the profile's new value.
+ logger.warning('Session %s: frozen config secret %s no longer matches the profile '
+ 'config; skipping it', source.get('session'), path)
+ continue
values[tuple(path)] = value
return values
+ except RuntimeStoreError:
+ raise
except (KeyError, TypeError, ValueError, AttributeError, OSError) as exc:
raise RuntimeStoreError('launch_credentials_unavailable') from exc
diff --git a/tests/gateway/fixtures/config_policy_recovery_probe.py b/tests/gateway/fixtures/config_policy_recovery_probe.py
index c32c417cb36..658e138231b 100644
--- a/tests/gateway/fixtures/config_policy_recovery_probe.py
+++ b/tests/gateway/fixtures/config_policy_recovery_probe.py
@@ -61,11 +61,11 @@ def probe(tmp_path):
assert loop.time() < deadline, ('admission never settled', receipt)
await asyncio.sleep(.03)
events = await rpc(ws, 'session.events.since', session_id=sid, last_sequence=0, replay_epoch=epoch)
- if phase == 'denied':
- # This baseline's pre-agent display failure has generic public
- # delivery; the worker lane owns settlement/error projection.
+ if phase == 'denied' and side == 'left':
+ # The refused turn names the credential its own route lost, never the model.
failure = json.dumps(events) + (home / 'restart.log').read_text()
assert 'launch_credentials_unavailable' in failure, failure
+ assert 'launch_credentials_unavailable (providers.left.api_key' in json.dumps(events), events
else:
assert 'LAUNCH_POLICY_OK' in json.dumps(events), events
assert not any(k in json.dumps([created, resumed, events]) for k in keys.values())
@@ -91,13 +91,16 @@ def probe(tmp_path):
requests = [r for r in peer.requests if r['body']['model'] == 'gpt-5-' + side]
assert len(requests) == 2
assert all(r['auth'] == 'Bearer ' + key and r['path'] == '/' + side + '/v1/chat/completions' for r in requests), requests
+ # Rotating one provider's key refuses only the session routed through it, by name (CFG-1):
+ # the other session's route does not need that secret and keeps its own frozen key.
cfg['providers']['left']['api_key'] = 'changed-wrong-credential'
config.write_text(json.dumps(cfg))
with daemon(root, home, env, barrier=False) as (proc, desc):
pids.append(proc.pid)
asyncio.run(pair(desc, 'denied'))
assert policies() == snapshots
- assert len(peer.requests) == 4
+ assert len(peer.requests) == 5, peer.requests
+ assert peer.requests[-1]['auth'] == 'Bearer ' + keys['right'], peer.requests[-1]
# backups/config/ holds byte-exact copies of config.yaml itself (last-known-good recovery,
# #109463); the invariant here is that the DAEMON never persists credentials elsewhere.
backups = home / 'backups' / 'config'
diff --git a/tests/gateway/test_config_policy_recovery.py b/tests/gateway/test_config_policy_recovery.py
index ca2c773d610..fe84748e608 100644
--- a/tests/gateway/test_config_policy_recovery.py
+++ b/tests/gateway/test_config_policy_recovery.py
@@ -99,3 +99,45 @@ def test_dropped_top_level_setting_does_not_wedge_the_session(tmp_path, monkeypa
policy.config(owner())
settings = policy.config(owner(), secrets=False) # a display/model-option read needs no secret
assert settings['model']['provider'] == 'custom' and settings['model']['api_key'] is None
+
+
[email protected]('edit', ['change', 'remove'])
+def test_an_unrelated_secret_edit_keeps_the_route_and_a_gone_route_key_is_named(tmp_path, monkeypatch, edit):
+ """CFG-1: editing ANY config secret (here an MCP server's env token) used to strand every older
+ session after a restart. Only the session's own route credential may refuse, and that refusal
+ names the credential; the unrelated secret is simply no longer supplied, never swapped."""
+ 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': 'route-token', 'base_url': 'http://127.0.0.1:1234/v1'},
+ 'mcp_servers': {'docs': {'command': 'docs-mcp', 'env': {'DOCS_TOKEN': 'old-mcp-token'}}}}
+ config_path = home / 'config.yaml'
+ config_path.write_text(json.dumps(cfg))
+
+ def owner(): # a fresh authority per read, like a restarted 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)
+ policy = bind_launch_key(owner(), 'session', policy, None, config_secrets=private)
+
+ if edit == 'change':
+ cfg['mcp_servers']['docs']['env']['DOCS_TOKEN'] = 'rotated-mcp-token'
+ else:
+ del cfg['mcp_servers']['docs']['env']
+ config_path.write_text(json.dumps(cfg))
+ config = policy.config(owner())
+ assert config['model']['api_key'] == 'route-token'
+ assert config['mcp_servers']['docs']['env'] is None # neither the old nor a swapped-in token
+
+ if edit == 'change':
+ cfg['model']['api_key'] = 'another-route-token'
+ else:
+ del cfg['model']['api_key']
+ config_path.write_text(json.dumps(cfg))
+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable') as refused:
+ policy.config(owner())
+ assert refused.value.field == 'model.api_key'
+ assert 'route-token' not in str(refused.value.detail) and 'another' not in str(refused.value.detail)