The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(profile-scope): bind home and secret tokens inside the try that resets them
beardthelion6aaa1c480bbe
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 22d51f3e7e6..4a9ea985b96 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -3662,13 +3662,14 @@ def _run_external_worker_payload(payload_path: Path, ack_path: Path) -> bool:set_hermes_home_override,)- home_token = set_hermes_home_override(profile_home)previous_multiplex = is_multiplex_active()- multiplex_active = bool(payload.get("multiplex_active", False))- set_multiplex_active(multiplex_active)- hydrate_profile_secret_sources(profile_home)- secret_token = set_secret_scope(build_profile_secret_scope(profile_home), profile_home=str(profile_home))+ home_token = secret_token = Nonetry:+ home_token = set_hermes_home_override(profile_home)+ multiplex_active = bool(payload.get("multiplex_active", False))+ set_multiplex_active(multiplex_active)+ hydrate_profile_secret_sources(profile_home)+ secret_token = set_secret_scope(build_profile_secret_scope(profile_home), profile_home=str(profile_home))with use_cron_store(profile_home):if adopt_claimed_execution(execution_id) is None:logger.error(@@ -3717,9 +3718,11 @@ def _run_external_worker_payload(payload_path: Path, ack_path: Path) -> bool:with contextlib.suppress(OSError):ack_path.with_suffix(".stderr").unlink(missing_ok=True)finally:- reset_secret_scope(secret_token)+ if secret_token is not None:+ reset_secret_scope(secret_token)set_multiplex_active(previous_multiplex)- reset_hermes_home_override(home_token)+ if home_token is not None:+ reset_hermes_home_override(home_token)def _notify_provider_jobs_changed() -> None:diff --git a/gateway/run.py b/gateway/run.pyindex 9ec33b16c70..714df2fdb0f 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -1813,25 +1813,28 @@ def _profile_runtime_scope(from hermes_constants import set_hermes_home_override, reset_hermes_home_overridefrom agent.secret_scope import set_secret_scope, reset_secret_scope- home_token = set_hermes_home_override(str(profile_home))- if prepared_secret_scope is not None:- secrets = prepared_secret_scope- elif hydrate_secrets:- secrets = _load_profile_secret_scope(Path(profile_home))- else:- from agent.secret_scope import build_profile_secret_scope # caller already hydrated off-loop- secrets = build_profile_secret_scope(Path(profile_home))- secret_token = set_secret_scope(secrets, profile_home=str(profile_home))- # Install the routed profile's COMPLETE terminal policy, never ambient TERMINAL_* a prior turn set.- # Without it terminal_tool reads the process-global TERMINAL_* vars a previous profile's turn may have- # pinned (first-writer-wins backend leak; #68559).- from tools.terminal_scope import install_and_reset_profile_terminal_scope-- with install_and_reset_profile_terminal_scope(Path(profile_home)):- try:+ home_token = secret_token = None+ try:+ home_token = set_hermes_home_override(str(profile_home))+ if prepared_secret_scope is not None:+ secrets = prepared_secret_scope+ elif hydrate_secrets:+ secrets = _load_profile_secret_scope(Path(profile_home))+ else:+ from agent.secret_scope import build_profile_secret_scope # caller already hydrated off-loop+ secrets = build_profile_secret_scope(Path(profile_home))+ secret_token = set_secret_scope(secrets, profile_home=str(profile_home))+ # Install the routed profile's COMPLETE terminal policy, never ambient TERMINAL_* a prior turn set.+ # Without it terminal_tool reads the process-global TERMINAL_* vars a previous profile's turn may have+ # pinned (first-writer-wins backend leak; #68559).+ from tools.terminal_scope import install_and_reset_profile_terminal_scope++ with install_and_reset_profile_terminal_scope(Path(profile_home)):yield- finally:+ finally:+ if secret_token is not None:reset_secret_scope(secret_token)+ if home_token is not None:reset_hermes_home_override(home_token)diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex 91d80951dc2..8d6d74fb670 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -2599,18 +2599,20 @@ def _worker_profile_scope(hermes_home: str, *, bind_home: bool = True):home = Path(hermes_home)is_launch_home = str(home.resolve()) == str(Path(get_process_hermes_home()).resolve())- home_token = set_hermes_home_override(str(home)) if bind_home else None- secret_token = set_secret_scope(- launch_secret_scope(home) if is_launch_home else build_profile_secret_scope(home),- profile_home=str(home))- terminal_token = install_profile_terminal_scope(- home, env_overlay=launch_terminal_env() if is_launch_home else None) if bind_home else None+ home_token = secret_token = terminal_token = Nonetry:+ home_token = set_hermes_home_override(str(home)) if bind_home else None+ secret_token = set_secret_scope(+ launch_secret_scope(home) if is_launch_home else build_profile_secret_scope(home),+ profile_home=str(home))+ terminal_token = install_profile_terminal_scope(+ home, env_overlay=launch_terminal_env() if is_launch_home else None) if bind_home else Noneyieldfinally:if terminal_token is not None:reset_terminal_scope(terminal_token)- reset_secret_scope(secret_token)+ if secret_token is not None:+ reset_secret_scope(secret_token)if home_token is not None:reset_hermes_home_override(home_token)diff --git a/hermes_cli/web_server_mcp.py b/hermes_cli/web_server_mcp.pyindex 1cdbe5e97b3..98c6af570f7 100644--- a/hermes_cli/web_server_mcp.py+++ b/hermes_cli/web_server_mcp.py@@ -126,10 +126,11 @@ def _run_dashboard_mcp_oauth(flow, cfg: dict) -> None:from tools.mcp_oauth import HermesTokenStorage, force_interactive_oauth, login_connect_timeoutfrom tools.mcp_oauth_manager import get_manager- home_token = set_hermes_home_override(flow.hermes_home)- secret_token = set_secret_scope(- build_profile_secret_scope(Path(flow.hermes_home)), profile_home=flow.hermes_home)+ home_token = secret_token = Nonetry:+ home_token = set_hermes_home_override(flow.hermes_home)+ secret_token = set_secret_scope(+ build_profile_secret_scope(Path(flow.hermes_home)), profile_home=flow.hermes_home)transaction = _mcp_oauth_transaction(flow)with transaction, force_interactive_oauth(), dashboard_oauth_flow(flow):manager = get_manager()@@ -158,8 +159,10 @@ def _run_dashboard_mcp_oauth(flow, cfg: dict) -> None:manager.restore_entry(flow.server_name, previous_entry, hermes_home=flow.hermes_home)raisefinally:- reset_secret_scope(secret_token)- reset_hermes_home_override(home_token)+ if secret_token is not None:+ reset_secret_scope(secret_token)+ if home_token is not None:+ reset_hermes_home_override(home_token)except Exception as exc:from tools.mcp_dashboard_oauth import exception_messagediff --git a/tests/agent/test_secret_scope.py b/tests/agent/test_secret_scope.pyindex b812b38db5f..ba6b0934ef7 100644--- a/tests/agent/test_secret_scope.py+++ b/tests/agent/test_secret_scope.py@@ -204,6 +204,66 @@ class TestRoutedForeignHomeScope:assert ss.get_secret("ASSIGNEE_KEY") == "from-assignee"+class TestScopeSetupRecovery:+ """A raise mid-scope-setup must release whatever was already bound — a leaked+ HERMES_HOME override or secret scope silently re-homes every later read in+ the caller's context."""++ def test_profile_runtime_scope_setup_failure_restores_override(self, monkeypatch, tmp_path):+ from gateway.run import _profile_runtime_scope+ from hermes_constants import get_hermes_home_override++ foreign = tmp_path / "profiles" / "b"+ foreign.mkdir(parents=True)++ def boom(home):+ raise RuntimeError("corrupt profile home")++ monkeypatch.setattr("agent.secret_scope.build_profile_secret_scope", boom)+ with pytest.raises(RuntimeError):+ with _profile_runtime_scope(foreign, hydrate_secrets=False):+ pass+ assert get_hermes_home_override() is None+ assert ss.current_secret_scope() is None++ def test_worker_profile_scope_setup_failure_restores_override(self, monkeypatch, tmp_path):+ from hermes_cli.kanban_db_dispatch import _worker_profile_scope+ from hermes_constants import get_hermes_home_override++ foreign = tmp_path / "profiles" / "assignee"+ foreign.mkdir(parents=True)++ def boom(home):+ raise RuntimeError("corrupt profile home")++ monkeypatch.setattr("agent.secret_scope.build_profile_secret_scope", boom)+ with pytest.raises(RuntimeError):+ with _worker_profile_scope(str(foreign), bind_home=True):+ pass+ assert get_hermes_home_override() is None+ assert ss.current_secret_scope() is None++ def test_model_switch_bind_releases_partial_scopes_on_raise(self, monkeypatch, tmp_path):+ """The scopes object never reaches the caller when the bind raises, so the+ bind must release what it already bound (home override + secret scope).+ Driven through ``server`` — the split module's functions run rebound on+ server.py's globals (``bind_module``)."""+ from tui_gateway import server+ from hermes_constants import get_hermes_home_override++ home = tmp_path / "profiles" / "b"+ home.mkdir(parents=True)++ def boom(home, env_overlay=None):+ raise RuntimeError("terminal policy unreadable")++ monkeypatch.setattr("tools.terminal_scope.install_profile_terminal_scope", boom)+ with pytest.raises(RuntimeError):+ server._profile_runtime_scope_tokens(home, hydrate_secrets=False)+ assert get_hermes_home_override() is None+ assert ss.current_secret_scope() is None++class TestScopeIsolation:"""Two scopes never see each other's secrets."""diff --git a/tests/tools/test_mcp_multiplex_connection_keys.py b/tests/tools/test_mcp_multiplex_connection_keys.pyindex faaa0aad7ef..940864eade4 100644--- a/tests/tools/test_mcp_multiplex_connection_keys.py+++ b/tests/tools/test_mcp_multiplex_connection_keys.py@@ -346,3 +346,32 @@ def test_launch_profile_pruning_a_server_keeps_served_profiles_same_named_connecassert core._server_scope_keys[(scope_b, "x")] == scope_bassert closed == ["x"]assert core._orphaned_adopters == {"c": {"x"}}+++def test_adopter_scope_setup_failure_leaks_no_override_and_continues(two_profiles, monkeypatch):+ """A corrupt/removed adopter home raising inside ``build_profile_secret_scope`` must+ not leak that adopter's HERMES_HOME override into the caller's context, and the+ remaining adopters still get their re-registration pass."""+ import agent.secret_scope as ss+ import tools.mcp_tool as core+ from tools import mcp_tool_discovery as disc, mcp_tool_lifecycle as lifecycle++ core._orphaned_adopters.update({"/nonexistent/bad-home": {"x"}, "/nonexistent/good-home": {"x"}})++ def flaky_build(home):+ if "bad-home" in str(home):+ raise RuntimeError("corrupt profile home")+ return {}++ monkeypatch.setattr(ss, "build_profile_secret_scope", flaky_build)+ monkeypatch.setattr("tools.mcp_tool_config._load_mcp_config",+ lambda: {"x": {"url": "https://mcp.example/x"}})+ registered = []+ monkeypatch.setattr(disc, "register_mcp_servers", lambda servers: registered.append(dict(servers)))++ lifecycle._reregister_orphaned_adopters()++ from hermes_constants import get_hermes_home_override+ assert get_hermes_home_override() is None+ assert ss.current_secret_scope() is None+ assert registered == [{"x": {"url": "https://mcp.example/x"}}]diff --git a/tools/connectors/mcp_oauth.py b/tools/connectors/mcp_oauth.pyindex e9c29b79651..af702cf17c9 100644--- a/tools/connectors/mcp_oauth.py+++ b/tools/connectors/mcp_oauth.py@@ -162,18 +162,21 @@ def run_worker(build_profile_secret_scope, reset_secret_scope, set_secret_scope)from tools.mcp_dashboard_oauth import dashboard_oauth_flowfrom tools.mcp_oauth import force_interactive_oauth- home_token = set_hermes_home_override(hermes_home)- secret_token = set_secret_scope(- {**build_profile_secret_scope(Path(hermes_home)), **(env or {})}, profile_home=hermes_home)+ home_token = secret_token = Nonetry:+ home_token = set_hermes_home_override(hermes_home)+ secret_token = set_secret_scope(+ {**build_profile_secret_scope(Path(hermes_home)), **(env or {})}, profile_home=hermes_home)if not (reuse_saved and flow is not Noneand _reuse_saved_authorization(server_name, cfg, flow, on_commit)):with force_interactive_oauth(), dashboard_oauth_flow(flow):probe_with_rollback(server_name, cfg, hermes_home, flow, reconnect_live, on_commit=on_commit)finally:- reset_secret_scope(secret_token)- reset_hermes_home_override(home_token)+ if secret_token is not None:+ reset_secret_scope(secret_token)+ if home_token is not None:+ reset_hermes_home_override(home_token)except Exception as exc:from tools.mcp_dashboard_oauth import exception_messagemsg = exception_message(exc)diff --git a/tools/mcp_tool_lifecycle.py b/tools/mcp_tool_lifecycle.pyindex a727395fe08..54967febc2c 100644--- a/tools/mcp_tool_lifecycle.py+++ b/tools/mcp_tool_lifecycle.py@@ -114,17 +114,20 @@ def _reregister_orphaned_adopters() -> None:from tools import mcp_tool_discovery as _discoveryfrom tools.mcp_tool_config import _load_mcp_configfor adopter, names in pending.items():- home_token = set_hermes_home_override(adopter)- secret_token = set_secret_scope(build_profile_secret_scope(Path(adopter)), profile_home=adopter)+ home_token = secret_token = Nonetry:+ home_token = set_hermes_home_override(adopter)+ secret_token = set_secret_scope(build_profile_secret_scope(Path(adopter)), profile_home=adopter)servers = {n: c for n, c in (_load_mcp_config() or {}).items() if n in names}if servers:_discovery.register_mcp_servers(servers)except Exception:logger.debug("MCP: re-registration for profile scope %s failed", adopter, exc_info=True)finally:- reset_secret_scope(secret_token)- reset_hermes_home_override(home_token)+ if secret_token is not None:+ reset_secret_scope(secret_token)+ if home_token is not None:+ reset_hermes_home_override(home_token)def shutdown_mcp_servers(*, scope: Optional[str] = None, names: Optional[set] = None,diff --git a/tui_gateway/launch_profile_policy.py b/tui_gateway/launch_profile_policy.pyindex a613a09e1e9..e984d4486fc 100644--- a/tui_gateway/launch_profile_policy.py+++ b/tui_gateway/launch_profile_policy.py@@ -166,15 +166,19 @@ def launch_profile_runtime_scope(launch_home: "str | Path") -> Iterator[None]:from tools.terminal_scope import install_profile_terminal_scope, reset_terminal_scopehome = Path(launch_home)- home_token = set_hermes_home_override(str(home))- secret_token = set_secret_scope(launch_secret_scope(home), profile_home=str(home))- terminal_token = install_profile_terminal_scope(home, env_overlay=launch_terminal_env())+ home_token = secret_token = terminal_token = Nonetry:+ home_token = set_hermes_home_override(str(home))+ secret_token = set_secret_scope(launch_secret_scope(home), profile_home=str(home))+ terminal_token = install_profile_terminal_scope(home, env_overlay=launch_terminal_env())yieldfinally:- reset_terminal_scope(terminal_token)- reset_secret_scope(secret_token)- reset_hermes_home_override(home_token)+ if terminal_token is not None:+ reset_terminal_scope(terminal_token)+ if secret_token is not None:+ reset_secret_scope(secret_token)+ if home_token is not None:+ reset_hermes_home_override(home_token)def launch_profile_scope_if_multiplexed():diff --git a/tui_gateway/model_switch.py b/tui_gateway/model_switch.pyindex 04015895607..01c6f766945 100644--- a/tui_gateway/model_switch.py+++ b/tui_gateway/model_switch.py@@ -68,35 +68,41 @@ def _profile_runtime_scope_tokens(profile_home, *, hydrate_secrets: bool = True)"""from agent.secret_scope import is_multiplex_activescopes = _TurnScopes()- if profile_home:- home = Path(profile_home)- # External sources first: the requested profile may never have been served in this process.- if hydrate_secrets:- from hermes_cli.env_loader import hydrate_profile_secret_sources- hydrate_profile_secret_sources(home)- secrets = build_profile_secret_scope(home)- overlay = None- scopes.home = set_hermes_home_override(str(home))- else:- # The launch home IS get_hermes_home() (``_profile_home`` answers None for "already the- # launch profile"); single-profile, only its secrets need binding. Once multiplexing is- # active the override is bound too: an unset override is the "unbound context" signal- # plugin runtime bindings and per-home slots fail closed on (#118538).- from tui_gateway.launch_profile_policy import launch_secret_scope, launch_terminal_env- home = Path(_hermes_home)- secrets = launch_secret_scope(home)- scopes.secret = set_secret_scope(secrets, profile_home=str(home))- if not is_multiplex_active():- return scopes- scopes.home = set_hermes_home_override(str(home))- overlay = launch_terminal_env()- if scopes.secret is None:- scopes.secret = set_secret_scope(secrets, profile_home=str(home))- # Same terminal policy the gateway binds per turn: a docker-configured profile- # must never resolve the launch process's pinned env. Failure → refusal scope.- from tools.terminal_scope import install_profile_terminal_scope- scopes.terminal = install_profile_terminal_scope(home, env_overlay=overlay)- return scopes+ try:+ if profile_home:+ home = Path(profile_home)+ # External sources first: the requested profile may never have been served in this process.+ if hydrate_secrets:+ from hermes_cli.env_loader import hydrate_profile_secret_sources+ hydrate_profile_secret_sources(home)+ secrets = build_profile_secret_scope(home)+ overlay = None+ scopes.home = set_hermes_home_override(str(home))+ else:+ # The launch home IS get_hermes_home() (``_profile_home`` answers None for "already the+ # launch profile"); single-profile, only its secrets need binding. Once multiplexing is+ # active the override is bound too: an unset override is the "unbound context" signal+ # plugin runtime bindings and per-home slots fail closed on (#118538).+ from tui_gateway.launch_profile_policy import launch_secret_scope, launch_terminal_env+ home = Path(_hermes_home)+ secrets = launch_secret_scope(home)+ scopes.secret = set_secret_scope(secrets, profile_home=str(home))+ if not is_multiplex_active():+ return scopes+ scopes.home = set_hermes_home_override(str(home))+ overlay = launch_terminal_env()+ if scopes.secret is None:+ scopes.secret = set_secret_scope(secrets, profile_home=str(home))+ # Same terminal policy the gateway binds per turn: a docker-configured profile+ # must never resolve the launch process's pinned env. Failure → refusal scope.+ from tools.terminal_scope import install_profile_terminal_scope+ scopes.terminal = install_profile_terminal_scope(home, env_overlay=overlay)+ return scopes+ except Exception:+ # A raise mid-bind leaves no return value for the caller to release —+ # undo whatever was bound before propagating.+ _release_profile_runtime_scope_tokens(scopes)+ raisedef _release_profile_runtime_scope_tokens(scopes: "_TurnScopes | None") -> None: