The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(multiplex): routed children never inherit launch-only credentials, with or without the multiplex flag
teknium13fe8e5e443d1
diff --git a/tests/tui_gateway/test_served_profile_child_env_authority.py b/tests/tui_gateway/test_served_profile_child_env_authority.pynew file mode 100644index 00000000000..e1303003cf5--- /dev/null+++ b/tests/tui_gateway/test_served_profile_child_env_authority.py@@ -0,0 +1,98 @@+"""A routed profile's child never receives a launch-profile credential — whatever its provenance.++Two authority edges of ``served_profile_child_env`` (review of #111617):++* a credential injected into the LAUNCH process by systemd / Compose / the shell is in no ``.env``+ and no source snapshot, so a name-based strip cannot see it; the child for routed profile B must+ still not carry it when B does not define the same name (``get_secret``'s multiplex contract:+ a scoped miss is *no credential*, never ambient fallback);+* the Desktop/dashboard backend serves ``?profile=B`` by installing a HERMES_HOME override WITHOUT+ the gateway-wide multiplex flag — the strip must key on "this task serves a routed home", not on+ that flag; the browser passthrough must not fall through to the launch key on a B miss either.+"""++import os+import sys+from pathlib import Path++import pytest++from agent.secret_scope import UnscopedSecretError, set_multiplex_active+from hermes_constants import reset_hermes_home_override, set_hermes_home_override+from tools.environments.local import served_profile_child_env+++def homes(tmp_path, monkeypatch):+ """Launch home A (its .env in os.environ) plus an AMBIENT-only OPENAI key A never wrote to a file;+ served home B defines neither."""+ a = tmp_path / ".hermes"+ b = a / "profiles" / "b"+ b.mkdir(parents=True)+ (a / ".env").write_text("A_MARKER=a\nHERMES_MODEL=a-model\nFIRECRAWL_API_KEY=a-fc\n", encoding="utf-8")+ (b / ".env").write_text("B_MARKER=b\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(a))+ for key, val in (("A_MARKER", "a"), ("HERMES_MODEL", "a-model"), ("FIRECRAWL_API_KEY", "a-fc"),+ ("OPENAI_API_KEY", "sk-ambient-launch-only")):+ monkeypatch.setenv(key, val)+ monkeypatch.delenv("B_MARKER", raising=False)+ set_multiplex_active(False)+ try:+ yield a, b+ finally:+ set_multiplex_active(False)+++def test_ambient_only_launch_credential_never_reaches_a_routed_child(homes):+ """Multiplex on: A's ambient OPENAI_API_KEY (not in A's .env) is absent from B's credential-bearing+ child while B's own secrets are present; with no target and no scope bound the builder refuses."""+ a, b = homes+ set_multiplex_active(True)+ env = served_profile_child_env(target_home=b, inherit_credentials=True)+ assert env["HERMES_HOME"] == str(b) and env["B_MARKER"] == "b"+ assert "OPENAI_API_KEY" not in env and "A_MARKER" not in env and "FIRECRAWL_API_KEY" not in env+ # The raw-environ base used by the relay delivery child is scrubbed the same way.+ env = served_profile_child_env(base=os.environ, target_home=b, inherit_credentials=True)+ assert "OPENAI_API_KEY" not in env and env["B_MARKER"] == "b"+ # The launch profile's own child keeps its env (ambient injection is A's legitimate credential).+ assert served_profile_child_env(target_home=a, inherit_credentials=True)["OPENAI_API_KEY"] == "sk-ambient-launch-only"+ with pytest.raises(UnscopedSecretError):+ served_profile_child_env(inherit_credentials=True)+++def test_routed_home_with_multiplex_flag_off_gets_no_launch_residue(homes, monkeypatch):+ """Desktop/dashboard topology: B served via the HERMES_HOME override only. The slash-worker /+ helper child sees B's env, and the browser passthrough resolves B's (absent) key as no key."""+ from tools.browser_tool import _build_browser_env++ a, b = homes+ token = set_hermes_home_override(str(b))+ try:+ env = served_profile_child_env(inherit_credentials=True)+ assert env["HERMES_HOME"] == str(b) and env["B_MARKER"] == "b"+ assert "A_MARKER" not in env and "HERMES_MODEL" not in env and "OPENAI_API_KEY" not in env+ browser_env = _build_browser_env()+ assert "FIRECRAWL_API_KEY" not in browser_env and browser_env["HERMES_HOME"] == str(b)+ finally:+ reset_hermes_home_override(token)+ # Control: the launch profile's own browser keeps its key and its settings.+ assert _build_browser_env()["FIRECRAWL_API_KEY"] == "a-fc"+ assert served_profile_child_env(inherit_credentials=True)["HERMES_MODEL"] == "a-model"+++def test_real_child_observes_only_the_routed_profile(homes):+ """Observed from inside a real child spawned for B with the flag off."""+ import json+ import subprocess++ a, b = homes+ token = set_hermes_home_override(str(b))+ try:+ env = served_profile_child_env(inherit_credentials=True)+ finally:+ reset_hermes_home_override(token)+ probe = "import json,os;print(json.dumps({k:os.environ.get(k) for k in ('HERMES_HOME','A_MARKER','B_MARKER','OPENAI_API_KEY')}))"+ out = subprocess.run([sys.executable, "-c", probe], env=env, capture_output=True, text=True, timeout=60)+ seen = json.loads(out.stdout.strip().splitlines()[-1])+ assert seen == {"HERMES_HOME": str(b), "A_MARKER": None, "B_MARKER": "b", "OPENAI_API_KEY": None}+ assert Path(seen["HERMES_HOME"]) == bdiff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex d6a7cb4a158..b8576e4f615 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -40,17 +40,19 @@ def _build_browser_env() -> dict:harnesses stub the ``tools`` package). The passthrough keys are re-added from the activeprofile's secret scope, never ``os.environ``: under multiplex that holds the LAUNCH profile'sBrowserbase/Firecrawl keys, and a served profile's browser must run on its own (or none)."""- from agent.secret_scope import UnscopedSecretError, get_secret+ from agent.secret_scope import current_secret_scope, get_secret, serves_routed_profilefrom tools.environments.local import served_profile_child_envfrom agent.proxy_bypass import add_loopback_no_proxyenv = served_profile_child_env(inherit_credentials=False)+ # A routed profile (multiplex, or a Desktop/dashboard backend serving ``?profile=B`` with the+ # flag off) resolves from its bound scope only — a miss is "no key", never the launch profile's+ # ``os.environ`` value that ``get_secret`` falls through to while multiplexing is inactive.+ routed = serves_routed_profile()+ scope = (current_secret_scope() or {}) if routed else Nonefor key in _BROWSER_PASSTHROUGH_KEYS:- try:- value = get_secret(key)- except UnscopedSecretError:- value = None # multiplex, no scope bound: no key rather than a sibling profile's+ value = scope.get(key) if routed else get_secret(key)if value is not None:env[key] = value# The Browser Use harness dials the resolved local CDP URL over ``websockets``; without adiff --git a/tools/environments/local.py b/tools/environments/local.pyindex d38c6361675..6a826376165 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -306,7 +306,13 @@ def hermes_subprocess_env(*, inherit_credentials: bool = False) -> dict[str, strprovider/tool blocklist) unless ``inherit_credentials`` — pass that **only** forchildren that legitimately need LLM credentials (user-blessed claude/codex/geminiCLI, TUI Node host). Terminal/execute_code use ``_sanitize_subprocess_env``."""- env = os.environ.copy()+ env = _scrub_credentials(os.environ.copy(), inherit_credentials=inherit_credentials)+ env.setdefault("PYTHONUTF8", "1") # Windows UTF-8 safety for spawned processes+ return _finalize_child_env(env)+++def _scrub_credentials(env: dict, *, inherit_credentials: bool) -> dict:+ """Tier 1 (always) and, unless ``inherit_credentials``, Tier 2 provider/tool credentials, in place."""strip = _ALWAYS_STRIP_KEYS | _plugin_terminal_env_strip_keys()if not inherit_credentials:strip |= _HERMES_PROVIDER_ENV_BLOCKLIST@@ -314,8 +320,7 @@ def hermes_subprocess_env(*, inherit_credentials: bool = False) -> dict[str, strif (key in strip or key.startswith(_HERMES_PROVIDER_ENV_FORCE_PREFIX)or _is_hermes_internal_secret(key)):del env[key]- env.setdefault("PYTHONUTF8", "1") # Windows UTF-8 safety for spawned processes- return _finalize_child_env(env)+ return envdef build_subprocess_env(@@ -342,44 +347,69 @@ def served_profile_child_env(inherit_credentials: bool = False,) -> dict[str, str]:"""Child env for a process that acts FOR the active (possibly served) profile: ``hermes -p X``- workers, ``key_cmd`` helpers, browser drivers. The process env is the LAUNCH profile's, so its- ``.env`` residue and bridged ``TERMINAL_*`` are dropped (``strip_launch_profile_env``; no-op- outside multiplex) and the target home is pinned. ``inherit_credentials=True`` is for children- that legitimately run with the profile's credentials (they run the agent or mint its token): the- target profile's own secrets (its ``.env`` + hydrated sources, i.e. what a standalone- ``hermes -p X`` loads itself) are overlaid — never a sibling profile's. ``False`` keeps the- provider scrub; the caller re-adds the few keys the child needs via ``get_secret``.- ``target_home`` defaults to the active override; ``base`` replaces the ``hermes_subprocess_env``- snapshot."""- from agent.secret_scope import build_profile_secret_scope, current_secret_scope+ workers, ``key_cmd`` helpers, browser drivers. The process env is the LAUNCH profile's. When the+ target is a ROUTED home (not the launch profile's — under multiplex or a Desktop/dashboard backend+ serving ``?profile=`` with the flag off) the launch ``.env`` residue and bridged ``TERMINAL_*`` are+ dropped (``strip_launch_profile_env``) AND every provider/tool credential is scrubbed from the base+ regardless of provenance: a key systemd / Compose / the shell injected into the launch process was+ never recorded in ``.env`` or a source snapshot, so a name-based strip cannot see it and the target+ overlay cannot remove it. ``inherit_credentials=True`` is for children that legitimately run with+ the profile's credentials (they run the agent or mint its token): the target profile's own secrets+ (its ``.env`` + hydrated sources, what a standalone ``hermes -p X`` loads itself) are overlaid — never+ a sibling profile's. Under multiplex with neither a target nor a bound scope the call raises+ (``get_secret``'s fail-closed contract): minting with the launch environ would sign in as the wrong+ profile. ``False`` keeps the provider scrub; the caller re-adds the few keys the child needs via+ ``get_secret``. ``target_home`` defaults to the active override; ``base`` replaces the+ ``hermes_subprocess_env`` snapshot."""+ from agent.secret_scope import (+ UnscopedSecretError, build_profile_secret_scope, current_secret_scope, is_multiplex_active)from hermes_constants import get_hermes_home_overrideenv = dict(base) if base is not None else hermes_subprocess_env(inherit_credentials=inherit_credentials)target = str(target_home or get_hermes_home_override() or "")if target:env["HERMES_HOME"] = target- strip_launch_profile_env(env, target)+ if _is_routed_home(target):+ strip_launch_profile_env(env, target)+ _scrub_credentials(env, inherit_credentials=False)if inherit_credentials:- secrets = build_profile_secret_scope(Path(target)) if target else (current_secret_scope() or {})- env.update((k, v) for k, v in secrets.items() if v is not None)+ if target:+ secrets = build_profile_secret_scope(Path(target))+ else:+ secrets = current_secret_scope()+ if secrets is None and is_multiplex_active():+ raise UnscopedSecretError(+ "", "served_profile_child_env(inherit_credentials=True) called with no target home and "+ "no profile secret scope bound while multiplexing is on; the child would inherit the "+ "launch profile's credentials. Bind the profile scope (or pass target_home) at the spawn site.")+ env.update((k, v) for k, v in (secrets or {}).items() if v is not None)return env+def _is_routed_home(target_home: "str | Path") -> bool:+ """True when ``target_home`` is not the process's own (launch) home."""+ from hermes_constants import get_process_hermes_home+ try:+ return Path(target_home).resolve() != get_process_hermes_home().resolve()+ except OSError:+ return True++def strip_launch_profile_env(env: dict, target_home: "str | Path | None" = None) -> dict:"""Drop the LAUNCH profile's residue from a child env built for another served profile.``os.environ`` holds the default profile's ``.env`` and its bridged ``TERMINAL_*`` settings;the secret scrub removes credentials but not settings (``HERMES_MODEL``, ``TERMINAL_ENV``,``HERMES_LANGUAGE``...), so a standalone ``hermes -p X`` worker and a served one saw differentenvs. The child re-loads X's own ``.env`` and bridges X's config itself. ``target_home``- defaults to the active home override; no-op outside multiplex or when the target IS the- launch profile."""- from agent.secret_scope import _is_global_env, is_multiplex_active, load_env_file+ defaults to the active home override; no-op when there is no target or the target IS the+ launch profile. The authority test is "does this task serve a routed home", not "is the+ gateway-wide multiplex flag on": the Desktop/dashboard backend serves ``?profile=B`` by+ installing a HERMES_HOME override without that flag."""+ from agent.secret_scope import _is_global_env, load_env_filefrom hermes_constants import get_hermes_home_override, get_process_hermes_hometarget = target_home or get_hermes_home_override()- if not is_multiplex_active() or not target:+ if not target or not _is_routed_home(target):return envlaunch_home = get_process_hermes_home()- if Path(target).resolve() == launch_home.resolve():- return envfrom hermes_cli.config import TERMINAL_CONFIG_ENV_MAPfor key in set(load_env_file(launch_home / ".env")) | set(TERMINAL_CONFIG_ENV_MAP.values()):if not _is_global_env(key) or key.startswith("TERMINAL_"):