The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(profiles): a child spawned for another profile no longer inherits the spawner's authorization gates
teknium13ed40556cea1
diff --git a/hermes_cli/update_restart_recovery.py b/hermes_cli/update_restart_recovery.pyindex 547b7bb06e9..7add7fe0f07 100644--- a/hermes_cli/update_restart_recovery.py+++ b/hermes_cli/update_restart_recovery.py@@ -89,18 +89,39 @@ def _succeeded(result: Any) -> bool:return result is not None and getattr(result, "returncode", 1) == 0-def _child_environment() -> dict[str, str]:- """Return an environment that cannot self-identify as the gateway owner."""+def _launch_profile() -> str:+ """Profile this recovery process was launched as: ``<root>/profiles/<name>`` in ``HERMES_HOME`` names it,+ anything else is the default profile. Mirrors ``hermes_cli.profiles.profile_root_for_env_home`` without+ importing it — this module stays stdlib-only at import time."""+ home = os.environ.get("HERMES_HOME", "").strip()+ if home:+ path = os.path.normpath(home)+ if os.path.basename(os.path.dirname(path)) == "profiles":+ return os.path.basename(path)+ return "default"+++def _child_environment(profile: str | None = None) -> dict[str, str]:+ """Return an environment that cannot self-identify as the gateway owner.++ One updater environment relaunches EVERY profile, so a child for another profile would inherit+ this process's authorization gates (``DISCORD_ALLOWED_CHANNELS``, ``GATEWAY_ALLOW_ALL_USERS`` ...)+ and enforce them as its own — its ``.env`` only overwrites the keys it defines (#113270). Gates are+ dropped when *profile* is not the launch profile; a same-profile child keeps an operator export.+ """env = os.environ.copy()for marker in _GATEWAY_MARKERS:env.pop(marker, None)env[_RECOVERY_ENV] = "1"+ if profile is not None and profile != _launch_profile():+ from tools.environments.local_env_policy import strip_profile_gate_env+ strip_profile_gate_env(env)return envdef _run_profile_restart(profile: str, *, run: Callable[..., Any]) -> bool:"""Run one profile restart without inheriting the updater's process state."""- kwargs: dict[str, Any] = {"stdin": subprocess.DEVNULL, "env": _child_environment()}+ kwargs: dict[str, Any] = {"stdin": subprocess.DEVNULL, "env": _child_environment(profile)}if os.name == "nt":kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) | getattr(subprocess, "DETACHED_PROCESS", 0)else:diff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.pyindex cc9c94ab5a3..41c5c14354e 100644--- a/hermes_cli/web_server_gateway.py+++ b/hermes_cli/web_server_gateway.py@@ -362,7 +362,7 @@ def _profile_action_environment()from hermes_cli.web_server_profiles import _resolve_profile_dirfrom hermes_constants import apply_subprocess_home_env, get_default_hermes_root- from tools.environments.local import build_subprocess_env+ from tools.environments.local import build_subprocess_env, strip_launch_profile_envtarget_home = _resolve_profile_dir(profile)action_env = build_subprocess_env(base=os.environ, scrub_secrets=True)@@ -379,6 +379,10 @@ def _profile_action_environment(profile_keys.update(get_secret_source_values(source_home).keys())for key in profile_keys:action_env.pop(key, None)+ # Authorization gates that reached this process outside any dotenv (unit-file+ # ``Environment=``, an operator export) are not in ``profile_keys``; the target+ # profile's ``.env`` rarely defines them, so they would survive into the child (#113270).+ strip_launch_profile_env(action_env, target_home)# Pin the child before import-time startup runs; the explicit -p flag stays authoritative# and resolves to the same validated directory.diff --git a/tests/tools/test_profile_gate_env_isolation.py b/tests/tools/test_profile_gate_env_isolation.pynew file mode 100644index 00000000000..e0d5b23f5af--- /dev/null+++ b/tests/tools/test_profile_gate_env_isolation.py@@ -0,0 +1,69 @@+"""A child spawned FOR another profile never inherits this process's authorization gates (#113270).++``DISCORD_ALLOWED_CHANNELS`` / ``TELEGRAM_GROUP_ALLOWED_CHATS`` / ``GATEWAY_ALLOW_ALL_USERS``-class names+decide WHO may talk to the agent. They are not credentials (no secret scrub sees them), a unit-file+``Environment=`` or operator export never appears in the launch ``.env`` (no name list sees them), and+the target profile's own ``.env`` rarely defines them (its dotenv load never overwrites them) — so a+``hermes -p B`` child built from profile A's process enforced A's channel list as its own.+"""++import json+import os+import subprocess+import sys++import pytest++from tools.environments.local import served_profile_child_env++# Gates injected outside any dotenv — the shape a name-list scrub cannot see. Mix of allowlist,+# deny list, allow-all opt-in, bot policy, channel scoping and a plugin adapter's gate.+_GATES = {+ "DISCORD_ALLOWED_CHANNELS": "111", "DISCORD_ALLOWED_ROLES": "r1", "DISCORD_IGNORED_CHANNELS": "222",+ "DISCORD_ALLOW_BOTS": "all", "TELEGRAM_GROUP_ALLOWED_CHATS": "-100", "SLACK_ALLOWED_CHANNELS": "C1",+ "WHATSAPP_GROUP_ALLOW_FROM": "+1555", "GATEWAY_ALLOW_ALL_USERS": "true",+}+_PROBE = "import json,os;print(json.dumps({k:os.environ.get(k) for k in %r}))" % sorted(_GATES)+++def _seen_by_child(env: dict) -> set[str]:+ out = subprocess.run([sys.executable, "-c", _PROBE], env=env, capture_output=True,+ text=True, encoding="utf-8", errors="replace", timeout=60)+ return {k for k, v in json.loads(out.stdout.strip().splitlines()[-1]).items() if v is not None}+++def homes(tmp_path, monkeypatch):+ """Launch home A (the process's HERMES_HOME) and routed home B; gates in the process env only."""+ a = tmp_path / ".hermes"+ b = a / "profiles" / "b"+ b.mkdir(parents=True)+ (a / ".env").write_text("A_MARKER=a\n", encoding="utf-8")+ (b / ".env").write_text("B_MARKER=b\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(a))+ for key, value in _GATES.items():+ monkeypatch.setenv(key, value)+ return a, b+++def test_routed_child_drops_gates_and_same_home_child_keeps_them(homes):+ """The seam every served-profile spawn funnels through: routed target → no gate reaches the child+ (observed from INSIDE a real child); same-home target → an operator export is preserved."""+ a, b = homes+ assert _seen_by_child(served_profile_child_env(base=os.environ, target_home=b)) == set()+ assert _seen_by_child(served_profile_child_env(base=os.environ, target_home=a)) == set(_GATES)+++def test_update_recovery_child_env_drops_gates_only_for_other_profiles(homes):+ """The updater relaunches EVERY profile from one environment; the per-profile child env must+ strip gates for a foreign profile and keep them for the profile the updater itself runs as."""+ from hermes_cli import update_restart_recovery as recovery++ routed = recovery._child_environment("b")+ same = recovery._child_environment("default")+ assert not any(key in routed for key in _GATES)+ assert all(same[key] == value for key, value in _GATES.items())+ # The recovery marker and the gateway-owner scrub are unchanged on both.+ for env in (routed, same):+ assert env[recovery._RECOVERY_ENV] == "1"+ assert not any(marker in env for marker in recovery._GATEWAY_MARKERS)diff --git a/tools/environments/local.py b/tools/environments/local.pyindex 5cede7739a2..d165ce61077 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -23,7 +23,7 @@ from hermes_cli._subprocess_compat import windows_hide_flagsfrom tools.environments.local_env_policy import (_ALWAYS_STRIP_KEYS, _HERMES_PROVIDER_ENV_BLOCKLIST, _HERMES_PROVIDER_ENV_FORCE_PREFIX,_is_hermes_internal_secret, _is_terminal_first_party_env,- _matches_terminal_first_party_prefix, _plugin_terminal_env_strip_keys)+ _matches_terminal_first_party_prefix, _plugin_terminal_env_strip_keys, strip_profile_gate_env)from tools.environments.local_gitbash_probe import (_bash_probe_details_cache, _bash_starts, _git_bash_aslr_help,_looks_like_msys_spawn_failure, _mandatory_aslr_enabled)@@ -426,7 +426,10 @@ def strip_launch_profile_env(env: dict, target_home: "str | Path | None" = None)for 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_"):env.pop(key, None)- return env+ # Authorization gates are the one residue a name list cannot see: a unit-file ``Environment=``+ # or an operator export never appears in the launch ``.env``, the secret scrub ignores+ # non-credentials, and the target's own ``.env`` rarely defines the key to overwrite it (#113270).+ return strip_profile_gate_env(env)# --- Shell discovery ---diff --git a/tools/environments/local_env_policy.py b/tools/environments/local_env_policy.pyindex d11d2f45d4c..f392a8c5386 100644--- a/tools/environments/local_env_policy.py+++ b/tools/environments/local_env_policy.py@@ -181,6 +181,37 @@ def _is_hermes_internal_secret(key: str) -> bool:return upper.startswith("GATEWAY_RELAY_") and upper.endswith(("_SECRET", "_KEY", "_TOKEN"))+# Authorization gates: the env names platform adapters read to decide WHO may talk to the+# agent (allow/deny lists, allow-all opt-ins, bot policy, channel scoping). Not credentials, so+# no secret scrub touches them, and most profiles' ``.env`` files do not define them, so the+# child's own dotenv load never overwrites an inherited value: a child spawned FOR profile B+# from a process that loaded profile A's gates (or a unit-file ``Environment=``) would enforce+# A's channel/user/role list as its own (#113270). Matched by shape so a gate added to any+# adapter is covered without a second edit; ``HERMES_*`` never counts (``HERMES_MEDIA_ALLOW_DIRS``,+# ``HERMES_ALLOW_PRIVATE_URLS`` are process settings, not adapter gates).+_PROFILE_GATE_ENV_MARKERS = (+ "_ALLOWED_", "_ALLOW_ALL_", "_ALLOW_FROM", "_ALLOW_BOTS", "_ALLOW_PUBLIC_", "_IGNORED_CHANNELS",+ "_NO_THREAD_CHANNELS", "_FREE_RESPONSE_CHANNELS", "_BACKFILL_CHANNELS", "_GROUP_ALLOWED",+)+++def is_profile_gate_env(name: str) -> bool:+ """True for a platform authorization gate (``DISCORD_ALLOWED_CHANNELS``, ``TELEGRAM_ALLOW_ALL_USERS``,+ ``GATEWAY_ALLOWED_USERS``, ``WHATSAPP_GROUP_ALLOW_FROM`` ...) — profile-scoped policy a child acting+ for ANOTHER profile must never inherit."""+ upper = name.upper()+ if upper.startswith("HERMES_") or upper.startswith("_"):+ return False+ return any(marker in upper for marker in _PROFILE_GATE_ENV_MARKERS)+++def strip_profile_gate_env(env: dict) -> dict:+ """Drop every authorization gate from *env* in place (see :func:`is_profile_gate_env`)."""+ for key in [k for k in env if is_profile_gate_env(k)]:+ del env[key]+ return env++def _plugin_terminal_env_strip_keys() -> frozenset:"""Credential env keys owned by plugin-registered terminal backends (Tier-1:stripped from every spawned subprocess). Computed at call time because pluginsdiff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.mdindex 38d9345eb8e..a872af36007 100644--- a/website/docs/user-guide/multi-profile-gateways.md+++ b/website/docs/user-guide/multi-profile-gateways.md@@ -465,6 +465,7 @@ profile and never shares with the default or any sibling:| MCP connections in the Desktop/dashboard backend and the per-profile cron ticker | Keyed per served profile even with `gateway.multiplex_profiles` off — same rule as the multiplexer | A same-named `mcp_servers` entry with other credentials is its own connection; a served profile never calls a server as another profile || Dashboard actions (`hermes -p <name> …` spawned by the Desktop/dashboard) | A scrubbed child env pinned to that profile's `HERMES_HOME` | The child loads its own `.env`; the dashboard profile's tokens and ports are not inherited || Every child that acts for a served profile (slash worker, Bot Chat delivery, A2A forward, `key_cmd` helper, browser driver) | That profile's own `.env` + secret sources over a credential-scrubbed base — with or without `gateway.multiplex_profiles` (the Desktop/dashboard `?profile=` route counts) | Absent from the child — a key that reached the launch process only through systemd / Compose / the shell is never inherited by another profile's child |+| Authorization gates in a child spawned for another profile (`*_ALLOWED_USERS` / `*_ALLOWED_CHANNELS` / `*_IGNORED_CHANNELS` / `*_ALLOW_ALL_USERS` / `*_ALLOW_BOTS`, `GATEWAY_ALLOW*`) — dashboard `hermes -p <name>` actions, kanban workers, Bot Chat delivery, the post-update per-profile `gateway restart` | The child's own `.env` / `config.yaml`, loaded by the child itself | Closed (the adapter's documented default) — a gate exported into the spawning process by a unit file or the shell is dropped before the child starts, so profile B never enforces profile A's channel or user list; a same-profile child keeps it || The launch (default) profile's own credentials in a `hermes serve` / dashboard process that also serves another profile | Its `.env` + secret sources over the process env **frozen the moment the first other profile is served**; not re-read afterwards | A credential rotated only in the process env (`systemctl set-environment`, a refreshed `op run` wrapper that did not re-exec) is not picked up until the process restarts — put rotating keys in `.env` or a secret source, or restart after rotating || Cron `.env` tuning (`HERMES_CRON_TIMEOUT`, `HERMES_MODEL` fallback, `HERMES_CRON_MAX_PARALLEL`, prefill file), worker / Bot Chat child env | The profile's own `.env`; children never inherit the default profile's `.env` settings or bridged `TERMINAL_*` policy | Cron defaults / model refusal, exactly as a standalone `hermes -p <name> gateway run` || Kanban workers and notifications for a profile's tasks | The assignee's `.env` + `config.yaml` (toolset pin, terminal backend, media policy, display language) | — |