The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a rotated MCP secret commits a policy generation
unsupportedpastelsb0e255f10f30
diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.pyindex f377da7f5d9..0e889bd985f 100644--- a/gateway/session_policy_credentials.py+++ b/gateway/session_policy_credentials.py@@ -86,6 +86,16 @@ def config_reference(authority, session_id, policy, secrets):sort_keys=True)+def secrets_moved(ref, secrets, sections):+ """Whether *secrets* (the private values of *sections*, as the profile has them now) differ from the ones+ the durable reference *ref* froze there, by fingerprint. Unknown for an in-memory reference: False."""+ if ref is not None and not ref.startswith(PREFIX):+ return False+ entries = json.loads(ref[len(PREFIX):])['entries'] if ref else []+ frozen = {tuple(path): fingerprint for path, fingerprint in entries if path[0] in sections}+ return frozen != {path: _fingerprint(value) for path, value in secrets.items()}++def recover_config_secrets(authority, policy, skip=None):"""The frozen config secrets; entries under a *skip* section are neither re-read nor checked. Everycaller of a following session skips its followed sections: the live profile supplies them, so a keydiff --git a/gateway/session_policy_refresh.py b/gateway/session_policy_refresh.pyindex 214958d9c17..8db265be5cf 100644--- a/gateway/session_policy_refresh.py+++ b/gateway/session_policy_refresh.py@@ -29,8 +29,9 @@ def refreshed_policy(policy, live, terminal, *, picked=(), mcp_only=False):config) and *terminal* (its terminal scope), or only its MCP servers (*mcp_only*); explicit picks (launchflags, the *picked* policy edits) stay. *secrets* are the refreshed sections' private values, *replaced*the sections (``None``: terminal) whose stored private values they supersede. *policy* itself when- nothing moved."""+ nothing moved; a rotated private value alone (its redacted tree unchanged) moves it."""from gateway.session_policy import _extract_config_secrets, present_sections+ from gateway.session_policy_credentials import secrets_movedold, config = json.loads(policy.config_json), json.loads(policy.config_json)live, secrets, replaced = present_sections(live), {}, set()if mcp_only:@@ -41,7 +42,8 @@ def refreshed_policy(policy, live, terminal, *, picked=(), mcp_only=False):_extract_config_secrets(terminal, secrets, (None,))replaced.add(None)toolsets = _mcp_servers(policy, config, live, toolsets, secrets, replaced)- if config == old and toolsets == policy.toolsets and terminal == json.loads(policy.terminal_json):+ if (config == old and toolsets == policy.toolsets and terminal == json.loads(policy.terminal_json)+ and not secrets_moved(policy.config_secret_ref, secrets, replaced)):return policy, {}, set()policy = replace(policy, toolsets=toolsets, config_json=json.dumps(config), terminal_json=json.dumps(terminal))return policy, secrets, replaced@@ -128,16 +130,17 @@ def _prepare(authority, session_id, mcp_only=False):terminal = {} if mcp_only else build_profile_terminal_scope(home)policy, secrets, replaced = refreshed_policy(old, _load_gateway_config(home / 'config.yaml'), terminal,picked=policy_picks(authority.db, session_id), mcp_only=mcp_only)- return None if policy == old else (stored, old, policy, secrets, replaced, generation)+ return None if policy is old else (stored, old, policy, secrets, replaced, generation)def _rebind(authority, session_id, old, policy, fresh, replaced):"""Re-bind the private values like a policy mutation: policy identity covers config and terminal, and the- refreshed sections' private values are the profile's current ones."""- from gateway.session_policy import bind_launch_key, launch_key+ refreshed sections' private values are the profile's current ones (the stored ones there are neither+ re-read nor checked: a rotated key is what the refresh picks up, not a revoked credential)."""+ from gateway.session_policy import FOLLOW_SECTIONS, bind_launch_key, launch_keyfrom gateway.session_policy_credentials import recover_config_secrets- secrets = recover_config_secrets(authority, old) if old.config_secret_ref else {}- secrets = {path: value for path, value in secrets.items() if path[0] not in replaced}+ skip = (*(FOLLOW_SECTIONS if old.follows_profile else ()), *replaced)+ secrets = recover_config_secrets(authority, old, skip) if old.config_secret_ref else {}secrets.update(fresh)return bind_launch_key(authority, session_id, policy, launch_key(authority, old), config_secrets=secrets)diff --git a/tests/gateway/test_mcp_reload_new_server.py b/tests/gateway/test_mcp_reload_new_server.pyindex c432d137e2d..2f7c193bc8c 100644--- a/tests/gateway/test_mcp_reload_new_server.py+++ b/tests/gateway/test_mcp_reload_new_server.py@@ -207,6 +207,54 @@ async def test_an_admission_queued_during_a_reload_commit_keeps_the_old_servers(store.close_all_db_handles()+def _state_bytes(store):+ path = store._db.db_path+ return b''.join(p.read_bytes() for p in (path, path.with_name(path.name + '-wal')) if p.exists())+++async def test_a_rotated_mcp_secret_commits_a_generation_with_the_new_value(tmp_path, monkeypatch):+ """An edit that only rotates a server's ``env`` token leaves the redacted config as it was. The refresh+ compares the private values' fingerprints too: ``reload.mcp`` and a resume (also after an owner restart)+ commit it, and the next turn's worker gets the new token, which never reaches state.db."""+ from gateway.session_authority import initialize_session_authority+ from hermes_state_local import local_receipt+ home = _home(monkeypatch)+ (home / 'config.yaml').write_text(ADDED)+ monkeypatch.setattr('gateway.session_policy.launch_key', lambda authority, policy: None)+ store, authority = await _owner_authority(home)+ _reloadable(authority, monkeypatch)+ owner = _connect(authority)+ cold = viewer = None+ try:+ sid = (await _call(owner, 'session.create', request_id='a', source='cli', cwd=str(tmp_path)))['session_id']+ other = (await _call(owner, 'session.create', request_id='b', source='cli', cwd=str(tmp_path)))['session_id']+ generations = {key: _generation(store, key) for key in (sid, other)}+ ref = local_receipt(store._db, sid)['policy']['config_secret_ref']+ (home / 'config.yaml').write_text(ADDED.replace('FIXT_TOKEN: sekret', 'FIXT_TOKEN: rotated-sekret'))+ result = await _call(owner, 'reload.mcp', session_id=sid, confirm=True)+ assert result['session'] == 'applied' and _generation(store, sid) == generations[sid] + 1, result+ assert local_receipt(store._db, sid)['policy']['config_secret_ref'] != ref+ servers, _ = _worker_servers(_worker_frame(authority, sid, monkeypatch), monkeypatch)+ assert servers['fixt']['env'] == {'FIXT_TOKEN': 'rotated-sekret'}+ # Nothing else moved: the next reload commits nothing.+ assert (await _call(owner, 'reload.mcp', session_id=sid, confirm=True))['session'] == 'unchanged'+ await owner.close()+ # An owner restart has no cached values: the stored reference still names the old token.+ cold = await initialize_session_authority(_runner(store), profile_id=str(home), instance_id='restarted')+ viewer = _connect(cold)+ await _call(viewer, 'session.resume', session_id=other)+ assert _generation(store, other) == generations[other] + 1+ servers, _ = _worker_servers(_worker_frame(cold, other, monkeypatch), monkeypatch)+ assert servers['fixt']['env'] == {'FIXT_TOKEN': 'rotated-sekret'}+ assert b'rotated-sekret' not in _state_bytes(store)+ finally:+ await owner.close()+ if viewer is not None:+ await viewer.close()+ store.close_all_db_handles()++@pytest.mark.asyncioasync def test_a_server_that_fails_to_start_is_unavailable_on_every_reload(tmp_path, monkeypatch):"""A stdio server whose ``command`` is missing parks after its first connect: discovery keeps the parked