Skip to content

The agent that grows with you

test(child-env): real children per spawn site; guard catches **os.environ spreads

John Paul Soliva8ffcd78aff0e
diff --git a/tests/agent/test_subprocess_env_guard.py b/tests/agent/test_subprocess_env_guard.py
index a904c319951..f0f0396f6ee 100644
--- a/tests/agent/test_subprocess_env_guard.py
+++ b/tests/agent/test_subprocess_env_guard.py
@@ -1,4 +1,4 @@
-"""Lint guard: no new raw ``os.environ.copy()`` spawn-env sites.
+"""Lint guard: no new raw ``os.environ.copy()`` / ``**os.environ`` spawn-env sites.
Every child-process env in the codebase must be built through
``tools.environments.local.build_subprocess_env`` (or its sibling
@@ -7,8 +7,8 @@ wraps) so profile-home propagation and secret-scrubbing have a single owner.
History: ~11 commits over 6 months each fixed one more spawn site that missed
``HERMES_HOME`` or secret-scrub propagation.
-This test greps the source tree for ``os.environ.copy()`` appearing within
-``PROXIMITY_LINES`` lines of a spawn call (``Popen`` / ``subprocess.run`` /
+This test greps the source tree for ``os.environ.copy()`` or a ``{**os.environ, ...}``
+spread appearing within ``PROXIMITY_LINES`` lines of a spawn call (``Popen`` / ``subprocess.run`` /
``create_subprocess*`` / ``PtyProcess.spawn`` / ``execvpe``) and asserts every
hit is in the explicit allowlist below. If you are adding a new spawn site:
@@ -24,7 +24,7 @@ from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
# Directories that make up the shipped source tree.
-SCAN_DIRS = ("agent", "hermes_cli", "tools", "gateway", "cron", "tui_gateway")
+SCAN_DIRS = ("agent", "hermes_cli", "tools", "gateway", "cron", "tui_gateway", "plugins")
SCAN_ROOT_FILES = ("cli.py", "hermes_constants.py")
# How many lines around an `os.environ.copy()` we look for a spawn call.
@@ -34,7 +34,8 @@ SPAWN_RE = re.compile(
r"\bPopen\b|\bsubprocess\.run\b|\bcreate_subprocess|\bPtyProcess\.spawn\b"
r"|\bexecvpe\b|\bptyprocess\.PtyProcess\b|\bspawn\("
)
-COPY_RE = re.compile(r"\bos\.environ\.copy\(\)")
+# A spread placed after the scrub restores everything it removed (#122751 review B1).
+COPY_RE = re.compile(r"\bos\.environ\.copy\(\)|\*\*os\.environ\b")
# ---------------------------------------------------------------------------
# ALLOWLIST — intentionally-raw sites. Each entry is a relative posix path.
@@ -49,6 +50,21 @@ ALLOWED_RAW_SPAWN_ENV_FILES = {
# only raw copy is the except-fallback for when the tools package itself
# cannot be imported, so the user's typed command still runs.
"hermes_cli/bang_shell.py",
+ # These children are Hermes itself and need its full environment: the gateway respawn
+ # watcher (generated script source), the launchd stderr-timestamp wrapper around the
+ # gateway command, and the skills sync that seeds a new profile.
+ "hermes_cli/gateway.py",
+ "hermes_cli/stderr_timestamp.py",
+ "hermes_cli/profiles.py",
+ # apt/dpkg run as root: sudo resets the environment, and the scrub helpers would point
+ # TMPDIR into HERMES_HOME's scratch dir, leaving root-owned files there.
+ "tools/bot_desktop/install.py",
+ # The docker/ssh CLIENT process: same as inheriting (``None``) plus the forwarded values;
+ # what may be forwarded is decided by the backend's forward/passthrough policy.
+ "tools/environments/remote_common.py",
+ # openviking-server is the user's own memory server and may read their provider keys for
+ # its embedding/VLM models; only the Hermes PYTHONPATH is removed (#78153).
+ "plugins/memory/openviking/__init__.py",
}
@@ -94,7 +110,7 @@ def test_no_new_raw_environ_copy_spawn_sites():
if rel not in ALLOWED_RAW_SPAWN_ENV_FILES
]
assert not offenders, (
- "New raw os.environ.copy() spawn-env site(s) found:\n "
+ "New raw os.environ.copy() / **os.environ spawn-env site(s) found:\n "
+ "\n ".join(offenders)
+ "\nUse tools.environments.local.build_subprocess_env() instead "
"(scrub_secrets=False, inherit_profile_home=False preserves exact "
diff --git a/tests/tools/test_spawn_site_child_env.py b/tests/tools/test_spawn_site_child_env.py
new file mode 100644
index 00000000000..45dc1cc04ae
--- /dev/null
+++ b/tests/tools/test_spawn_site_child_env.py
@@ -0,0 +1,92 @@
+"""Real children started by the production spawn sites observe the secret scrub."""
+
+import asyncio
+import json
+import sys
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from tests.tools._child_env_fixtures import child_env # noqa: F401
+
+_TIER1 = ("TELEGRAM_BOT_TOKEN", "GATEWAY_RELAY_SECRET")
+_PROVIDER = "OPENAI_API_KEY"
+
+
+def _plant(monkeypatch):
+ for name in (*_TIER1, _PROVIDER):
+ monkeypatch.setenv(name, f"fake-{name.lower()}")
+
+
+def _probe_script(path: Path, out: Path, names) -> Path:
+ path.write_text(
+ f"#!{sys.executable}\nimport json, os\n"
+ f"open({str(out)!r}, 'w').write(json.dumps({{n: os.environ.get(n) for n in {list(names)!r}}}))\n",
+ encoding="utf-8")
+ path.chmod(0o755)
+ return path
+
+
+def test_compute_host_child_keeps_provider_keys_but_never_tier1_secrets(child_env, monkeypatch):
+ from tui_gateway.host_supervisor import HostSupervisor
+
+ _plant(monkeypatch)
+ names = [*_TIER1, _PROVIDER, "HERMES_COMPUTE_HOST_HEARTBEAT_SECS"]
+ hello = ("import json, os, sys; print(json.dumps({'type': 'hello', 'seen': "
+ f"{{n: os.environ.get(n) for n in {names!r}}}}}), flush=True); sys.stdin.readline()")
+ sup = HostSupervisor(registry_path=child_env / "host.json", argv=[sys.executable, "-c", hello],
+ cwd=child_env, expected_build_sha="unknown", autostart=False)
+ try:
+ sup.start()
+ seen = sup._hello["seen"]
+ finally:
+ sup.shutdown()
+ assert seen == {"TELEGRAM_BOT_TOKEN": None, "GATEWAY_RELAY_SECRET": None,
+ # The turn process drives the model, so provider keys pass by design.
+ _PROVIDER: "fake-openai_api_key", "HERMES_COMPUTE_HOST_HEARTBEAT_SECS": "15"}
+
+
[email protected]("posix") # the stand-in binaries are shebang scripts
[email protected]("site", ["lsp_server", "lsp_go_install", "raft_bridge", "buzz_cli"])
+def test_third_party_children_never_see_hermes_credentials(child_env, monkeypatch, site):
+ _plant(monkeypatch)
+ out = child_env / "seen.json"
+ own = {"lsp_server": "LSP_OWN_SETTING", "lsp_go_install": "GOBIN", "raft_bridge": "RAFT_CHANNEL_TOKEN",
+ "buzz_cli": "BUZZ_PRIVATE_KEY"}[site]
+ probe = _probe_script(child_env / "probe", out, [*_TIER1, _PROVIDER, own])
+
+ if site == "lsp_server":
+ from agent.lsp.client import LSPClient
+
+ async def _run():
+ client = LSPClient(server_id="probe", workspace_root=str(child_env), command=[str(probe)],
+ env={"LSP_OWN_SETTING": "kept"})
+ await client._spawn()
+ await client._proc.wait()
+ for task in (client._reader_task, client._stderr_task):
+ task.cancel()
+ asyncio.run(_run())
+ elif site == "lsp_go_install":
+ from agent.lsp import install
+
+ with patch.object(install.shutil, "which", return_value=str(probe)):
+ install._install_go("example.com/probe@latest", "probe")
+ elif site == "buzz_cli":
+ from plugins.platforms.buzz.adapter import _exec_buzz
+
+ asyncio.run(_exec_buzz(str(probe), [], relay_url="wss://relay.invalid", private_key="buzz-own"))
+ else:
+ from gateway.config import PlatformConfig
+ from plugins.platforms.raft.adapter import RaftAdapter
+
+ monkeypatch.setenv("RAFT_PROFILE", "probe")
+ config = PlatformConfig(enabled=True, extra={"bridge_token": "bridge-own", "runtime_session": "default", "port": 0})
+ adapter = RaftAdapter(config)
+ with patch("plugins.platforms.raft.adapter.shutil.which", return_value=str(probe)):
+ adapter._spawn_bridge(4321)
+ adapter._bridge_process.wait(timeout=30)
+
+ seen = json.loads(out.read_text(encoding="utf-8"))
+ assert {k: seen[k] for k in (*_TIER1, _PROVIDER)} == dict.fromkeys((*_TIER1, _PROVIDER))
+ assert seen[own] # the child's own configuration still arrives