Skip to content

The agent that grows with you

test: replace child environment ladders with process contracts

ethernet975572451ff9
diff --git a/tests/tools/_child_env_fixtures.py b/tests/tools/_child_env_fixtures.py
new file mode 100644
index 00000000000..233f35c6cee
--- /dev/null
+++ b/tests/tools/_child_env_fixtures.py
@@ -0,0 +1,104 @@
+"""Isolated, real processes for the child-environment contract tests."""
+
+import json
+import os
+import shlex
+import subprocess
+import sys
+import venv
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+
+def child_env(monkeypatch, tmp_path):
+ # Never dump the operator's environment or source their shell startup files.
+ names = (
+ "PATH", "SYSTEMROOT", "SYSTEMDRIVE", "WINDIR", "COMSPEC", "PATHEXT",
+ "TEMP", "TMP", "OS", "PROCESSOR_ARCHITECTURE", "NUMBER_OF_PROCESSORS",
+ )
+ seed = {k: v for k, v in os.environ.items() if k.upper() in names}
+ seed.update(HOME=str(tmp_path), USERPROFILE=str(tmp_path), USER="env-test",
+ HERMES_HOME=str(tmp_path / "hermes"),
+ HERMES_RUNTIME_DIR=str(tmp_path / "runtime"),
+ TERMINAL_ENV="local", TERMINAL_CWD=str(tmp_path), LANG="C.UTF-8")
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ from tools import env_passthrough
+ from tools.environments import local
+ monkeypatch.setattr(local, "_read_terminal_shell_init_config", lambda: ([], False))
+ monkeypatch.setattr(env_passthrough, "_config_passthrough", {})
+ token = env_passthrough._allowed_env_vars_var.set(set())
+ with patch.dict(os.environ, seed, clear=True):
+ try:
+ yield tmp_path
+ finally:
+ from tools.code_kernel import shutdown_all_kernels
+ shutdown_all_kernels()
+ env_passthrough._allowed_env_vars_var.reset(token)
+
+
+def project_python(child_env):
+ root = child_env / "project-venv"
+ # A symlink to the parent binary triggers realpath's same-env shortcut;
+ # copies=True semantics are essential to distinguish both interpreters.
+ venv.EnvBuilder(with_pip=False, symlinks=False).create(root)
+ python = root / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+ result = subprocess.run(
+ [str(python), "-c", "import sys,sysconfig,json; print(json.dumps([sys.prefix,sysconfig.get_path('purelib')]))"],
+ env=dict(os.environ), stdin=subprocess.DEVNULL, capture_output=True,
+ text=True, check=True, timeout=30,
+ )
+ prefix, site = json.loads(result.stdout)
+ assert Path(prefix).resolve() == root.resolve()
+ assert Path(prefix).resolve() != Path(sys.prefix).resolve()
+ assert python.resolve() != Path(sys.executable).resolve()
+ Path(site, "project_only_probe.py").write_text("VALUE = 'project-only → 雪'\n", encoding="utf-8")
+ return python, root
+
+
+def run_code(code, mode="project", enabled_tools=("read_file",), reset=True):
+ from tools.code_execution_tool import execute_code
+ with patch("tools.code_execution_tool._load_config", return_value={"mode": mode}):
+ result = json.loads(execute_code(code=code, task_id="child-env-test",
+ enabled_tools=list(enabled_tools), reset=reset))
+ assert result["status"] == "success", result
+ return json.loads(result["output"])
+
+
+def observe_terminal(env, names):
+ code = "import json,os; print(json.dumps({k:os.environ.get(k) for k in " + repr(list(names)) + "}))"
+ command = shlex.join([Path(sys.executable).as_posix(), "-c", code])
+ result = env.execute(command)
+ assert result["returncode"] == 0, result
+ return json.loads(result["output"])
+
+
+def observe_child(env, names):
+ code = "import json,os; print(json.dumps({k:os.environ.get(k) for k in " + repr(list(names)) + "}))"
+ result = subprocess.run([sys.executable, "-c", code], env=env, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, check=True, timeout=30)
+ return json.loads(result.stdout)
+
+
+class RunToCompletionEnv:
+ """Real shell transport for the remote file-RPC path; no remote service."""
+
+ def __init__(self, root):
+ import shutil
+ self.root = root
+ self.bash = shutil.which("bash")
+ assert self.bash, "bash is required for the POSIX file-RPC transport"
+ self.env = dict(os.environ)
+ self.env["PATH"] = os.pathsep.join([str(Path(sys.executable).parent), self.env["PATH"]])
+
+ def get_temp_dir(self):
+ return str(self.root)
+
+ def execute(self, command, cwd=None, timeout=30):
+ result = subprocess.run([self.bash, "-c", command], cwd=cwd or self.root,
+ env=self.env, stdin=subprocess.DEVNULL, timeout=timeout,
+ capture_output=True, text=True, encoding="utf-8")
+ return {"returncode": result.returncode, "output": result.stdout + result.stderr}
diff --git a/tests/tools/test_build_subprocess_env.py b/tests/tools/test_build_subprocess_env.py
index 9ec57d7424d..a6687398045 100644
--- a/tests/tools/test_build_subprocess_env.py
+++ b/tests/tools/test_build_subprocess_env.py
@@ -1,107 +1,44 @@
-"""Tests for tools.environments.local.build_subprocess_env — the single
-factory for child-process environments (profile-home + secret-scrub owner).
-"""
+"""Real children observe factory scrubbing, overrides and routed profile homes."""
import os
-import subprocess
-import sys
import pytest
+from tests.tools._child_env_fixtures import child_env, observe_child # noqa: F401
from tools.environments.local import build_subprocess_env
-# ---------------------------------------------------------------------------
-# Unit: scrub path delegates to _sanitize_subprocess_env semantics
-# ---------------------------------------------------------------------------
-
-def test_scrub_on_strips_provider_key(monkeypatch):
- monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-secret")
- env = build_subprocess_env()
- assert "ANTHROPIC_API_KEY" not in env
-
-
-def test_scrub_on_strips_dynamic_internal_secret(monkeypatch):
- monkeypatch.setenv("AUXILIARY_VISION_API_KEY", "sk-aux")
- monkeypatch.setenv("GATEWAY_RELAY_FOO_TOKEN", "tok")
- env = build_subprocess_env()
- assert "AUXILIARY_VISION_API_KEY" not in env
- assert "GATEWAY_RELAY_FOO_TOKEN" not in env
-
-
-def test_scrub_on_forwards_extra_like_sanitize_extra_env(monkeypatch):
- env = build_subprocess_env(extra={"MY_HARMLESS_VAR": "1"})
- assert env.get("MY_HARMLESS_VAR") == "1"
- # extra still goes through the blocklist on the scrub path
- env2 = build_subprocess_env(extra={"ANTHROPIC_API_KEY": "sk"})
- assert "ANTHROPIC_API_KEY" not in env2
-
-
-# ---------------------------------------------------------------------------
-# Unit: no-scrub path preserves content exactly
-# ---------------------------------------------------------------------------
-
-
-def test_no_scrub_inherit_profile_home_bridges_context_override(tmp_path):
[email protected]("scrub,inherit_home", [(True, True), (True, False), (False, True), (False, False)])
+def test_factory_child_policy_and_profile_home(child_env, monkeypatch, scrub, inherit_home):
from hermes_constants import set_hermes_home_override, reset_hermes_home_override
-
- token = set_hermes_home_override(str(tmp_path))
+ routed = child_env / "profiles/coder"
+ routed.mkdir(parents=True)
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "fake-parent-secret")
+ monkeypatch.setenv("AUXILIARY_FAKE_API_KEY", "fake-auxiliary")
+ monkeypatch.setenv("GATEWAY_RELAY_FOO_TOKEN", "fake-relay")
+ before = dict(os.environ)
+ token = set_hermes_home_override(str(routed))
try:
- env = build_subprocess_env(
- {"PATH": "/bin"}, scrub_secrets=False, inherit_profile_home=True
- )
+ env = build_subprocess_env(scrub_secrets=scrub, inherit_profile_home=inherit_home,
+ extra={"MY_HARMLESS_VAR": "caller", "ANTHROPIC_API_KEY": "fake-extra"})
+ result = observe_child(env, ["HERMES_HOME", "ANTHROPIC_API_KEY", "AUXILIARY_FAKE_API_KEY",
+ "GATEWAY_RELAY_FOO_TOKEN", "MY_HARMLESS_VAR"])
finally:
reset_hermes_home_override(token)
- assert env["HERMES_HOME"] == str(tmp_path)
-
-
-# ---------------------------------------------------------------------------
-# E2E: real subprocess sees the factory's contract
-# ---------------------------------------------------------------------------
-
-def test_e2e_child_sees_hermes_home_and_no_planted_secret(tmp_path, monkeypatch):
- """A real child spawned with a factory-built env must see HERMES_HOME
- propagated and (with scrub on) a planted provider-style key absent."""
- hermes_home = tmp_path / "hermes-home"
- hermes_home.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
- monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-FAKE-planted")
- monkeypatch.setenv("AUXILIARY_FAKE_API_KEY", "sk-FAKE-aux")
-
- env = build_subprocess_env() # scrub on (default)
-
- code = (
- "import os, json; "
- "print(json.dumps({'home': os.environ.get('HERMES_HOME'), "
- "'k1': 'ANTHROPIC_API_KEY' in os.environ, "
- "'k2': 'AUXILIARY_FAKE_API_KEY' in os.environ}))"
- )
- out = subprocess.run(
- [sys.executable, "-c", code],
- env=env, capture_output=True, text=True, timeout=60, check=True,
- )
- import json
-
- result = json.loads(out.stdout)
- assert result["home"] == str(hermes_home)
- assert result["k1"] is False
- assert result["k2"] is False
-
-
-def test_e2e_no_scrub_child_keeps_planted_secret(tmp_path, monkeypatch):
- monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-FAKE-planted")
- env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
- out = subprocess.run(
- [sys.executable, "-c",
- "import os; print(os.environ.get('ANTHROPIC_API_KEY', ''))"],
- env=env, capture_output=True, text=True, timeout=60, check=True,
- )
- assert out.stdout.strip() == "sk-FAKE-planted"
-
-
-# ---------------------------------------------------------------------------
-# E2E regression (#93082): cron/no_agent children keep bare `hermes` on PATH
-# ---------------------------------------------------------------------------
+ assert result == {
+ "HERMES_HOME": str(routed) if scrub or inherit_home else before["HERMES_HOME"],
+ "ANTHROPIC_API_KEY": None if scrub else "fake-extra",
+ "AUXILIARY_FAKE_API_KEY": None if scrub else "fake-auxiliary",
+ "GATEWAY_RELAY_FOO_TOKEN": None if scrub else "fake-relay", "MY_HARMLESS_VAR": "caller",
+ }
+ assert dict(os.environ) == before
+
+
+def test_no_scrub_is_byte_preserving_except_explicit_extra():
+ base = {"PATH": "/bin", "PYTHONHOME": "/poison", "VIRTUAL_ENV": "/venv",
+ "CONDA_PREFIX": "/conda", "SERVICE_TOKEN": "fake", "HERMES_HOME": "/original"}
+ assert build_subprocess_env(base, scrub_secrets=False, inherit_profile_home=False) == base
+ assert build_subprocess_env(base, scrub_secrets=False, extra={"HERMES_HOME": "/caller"})["HERMES_HOME"] == "/caller"
def test_e2e_scrubbed_env_resolves_bare_hermes_under_minimal_parent_path(monkeypatch):
diff --git a/tests/tools/test_code_execution_modes.py b/tests/tools/test_code_execution_modes.py
index ac1298b7f64..50dacb1a169 100644
--- a/tests/tools/test_code_execution_modes.py
+++ b/tests/tools/test_code_execution_modes.py
@@ -1,630 +1,155 @@
-#!/usr/bin/env python3
-"""Tests for execute_code's strict / project execution modes.
-
-The mode switch controls two things:
- - working directory: staging tmpdir (strict) vs session CWD (project)
- - interpreter: sys.executable (strict) vs active venv's python (project)
-
-Security-critical invariants — env scrubbing, tool whitelist, resource caps —
-must apply identically in both modes. These tests guard all three layers.
-
-Mode is sourced exclusively from ``code_execution.mode`` in config.yaml —
-there is no env-var override. Tests patch ``_load_config`` directly.
-"""
+"""Real interpreter, environment and RPC contracts for both execution modes."""
import json
import os
import subprocess
import sys
-import time
-import unittest
-import unittest.mock
-from contextlib import contextmanager, ExitStack
+from pathlib import Path
from unittest.mock import patch
import pytest
-os.environ["TERMINAL_ENV"] = "local"
-
-
[email protected](autouse=True)
-def _force_local_terminal(monkeypatch):
- """Mirror test_code_execution.py — guarantee local backend."""
- monkeypatch.setenv("TERMINAL_ENV", "local")
-
-
[email protected](autouse=True)
-def _fresh_kernel_registry():
- """Session kernels are always on: dispose them per-test so a lingering
- kernel child can't outlive the run (hangs pytest at exit) or leak one
- test's interpreter state into the next."""
- from tools.code_kernel import shutdown_all_kernels
-
- shutdown_all_kernels()
- yield
- shutdown_all_kernels()
-
-
-from tools.code_execution_env import (
- _is_usable_python,
- _python_environment_prefix,
- _python_prefix_cache,
- _resolve_child_cwd,
- _resolve_child_python,
- _usable_python_cache,
- _uses_hermes_python_environment,
-)
-from tools.code_execution_tool import (
- SANDBOX_ALLOWED_TOOLS,
- DEFAULT_EXECUTION_MODE,
- EXECUTION_MODES,
- _get_execution_mode,
- build_execute_code_schema,
- execute_code,
-)
-
-
-@contextmanager
-def _mock_mode(mode):
- """Context manager that pins code_execution.mode to the given value."""
- with patch("tools.code_execution_tool._load_config",
- return_value={"mode": mode}):
- yield
-
-
-def _mock_handle_function_call(function_name, function_args, task_id=None, user_task=None):
- """Minimal mock dispatcher reused across tests."""
- if function_name == "terminal":
- return json.dumps({"output": "mock", "exit_code": 0})
- if function_name == "read_file":
- return json.dumps({"content": "line1\n", "total_lines": 1})
- return json.dumps({"error": f"Unknown tool: {function_name}"})
-
-
-# ---------------------------------------------------------------------------
-# Mode resolution
-# ---------------------------------------------------------------------------
-
-class TestGetExecutionMode(unittest.TestCase):
- """_get_execution_mode reads config.yaml only (no env var surface)."""
-
- def test_default_is_project(self):
- self.assertEqual(DEFAULT_EXECUTION_MODE, "project")
-
- def test_config_project(self):
- with patch("tools.code_execution_tool._load_config",
- return_value={"mode": "project"}):
- self.assertEqual(_get_execution_mode(), "project")
-
-
- def test_execution_modes_tuple(self):
- """Canonical set of modes — tests + config layer rely on this shape."""
- self.assertEqual(set(EXECUTION_MODES), {"project", "strict"})
-
-
-# ---------------------------------------------------------------------------
-# Interpreter resolver
-# ---------------------------------------------------------------------------
-
-class TestResolveChildPython(unittest.TestCase):
- """_resolve_child_python — picks the right interpreter per mode."""
-
- def test_strict_always_sys_executable(self):
- """Strict mode never leaves sys.executable, even if venv is set."""
- with patch.dict(os.environ, {"VIRTUAL_ENV": "/some/venv"}):
- self.assertEqual(_resolve_child_python("strict"), sys.executable)
-
- def test_project_with_no_venv_falls_back(self):
- """Project mode without VIRTUAL_ENV or CONDA_PREFIX → sys.executable."""
- env = {k: v for k, v in os.environ.items()
- if k not in {"VIRTUAL_ENV", "CONDA_PREFIX"}}
- with patch.dict(os.environ, env, clear=True):
- self.assertEqual(_resolve_child_python("project"), sys.executable)
-
-
- def test_is_usable_python_accepts_real_python(self):
- _usable_python_cache.clear()
- self.assertTrue(_is_usable_python(sys.executable))
-
- def test_is_usable_python_failure_is_not_cached(self):
- """A transient probe failure must not stick — the next call retries.
-
- A sticky cached False would silently pin project mode to
- sys.executable for the process lifetime.
- """
- _usable_python_cache.clear()
- try:
- with patch("subprocess.run",
- side_effect=subprocess.TimeoutExpired(cmd=[], timeout=5)) as mock_run:
- self.assertFalse(_is_usable_python("/flaky/python"))
- self.assertEqual(mock_run.call_count, 1)
- with patch("subprocess.run") as mock_run:
- mock_run.return_value = unittest.mock.MagicMock(returncode=0)
- self.assertTrue(_is_usable_python("/flaky/python"))
- self.assertEqual(mock_run.call_count, 1,
- "probe must be retried after a failure")
- finally:
- _usable_python_cache.clear()
-
-
-# ---------------------------------------------------------------------------
-# CWD resolver
-# ---------------------------------------------------------------------------
-
-class TestResolveChildCwd(unittest.TestCase):
-
- def test_strict_uses_staging_dir(self):
- self.assertEqual(_resolve_child_cwd("strict", "/tmp/staging"), "/tmp/staging")
-
- def test_project_without_terminal_cwd_uses_getcwd(self):
- env = {k: v for k, v in os.environ.items() if k != "TERMINAL_CWD"}
- with patch.dict(os.environ, env, clear=True):
- self.assertEqual(_resolve_child_cwd("project", "/tmp/staging"), os.getcwd())
-
-
- def test_project_stale_record_falls_through_to_override(self):
- """A recorded directory that no longer exists is skipped; the
- registered override is the next rung."""
- import tempfile
- import tools.terminal_tool as terminal_tool
-
- with tempfile.TemporaryDirectory() as reg:
- task_id = "stale-record-test"
- with patch.dict(os.environ, {"TERMINAL_CWD": "/does/not/exist"}):
- with patch.object(terminal_tool, "_task_env_overrides", {}, create=False), \
- patch.object(terminal_tool, "_session_cwd", {}, create=False):
- terminal_tool.register_task_env_overrides(task_id, {"cwd": reg})
- terminal_tool.record_session_cwd(task_id, "/deleted/dir/gone")
- self.assertEqual(
- _resolve_child_cwd("project", "/tmp/staging", task_id=task_id), reg
- )
-
-
-# ---------------------------------------------------------------------------
-# Schema description
-# ---------------------------------------------------------------------------
-
-class TestModeAwareSchema(unittest.TestCase):
-
- def test_strict_description_mentions_temp_dir(self):
- desc = build_execute_code_schema(mode="strict")["description"]
- self.assertIn("temp dir", desc)
-
-
- def test_neither_description_uses_sandbox_language(self):
- """REGRESSION GUARD for commit 39b83f34.
-
- Agents on local backends falsely believed they were sandboxed and
- refused networking tasks. Do not reintroduce any 'sandbox' /
- 'isolated' / 'cloud' language in the tool description.
- """
- for mode in EXECUTION_MODES:
- desc = build_execute_code_schema(mode=mode)["description"].lower()
- for forbidden in ("sandbox", "isolated", "cloud"):
- self.assertNotIn(forbidden, desc,
- f"mode={mode}: '{forbidden}' leaked into description")
-
-
- def test_default_mode_reads_config(self):
- """build_execute_code_schema() with mode=None reads config.yaml."""
- with _mock_mode("strict"):
- desc = build_execute_code_schema()["description"]
- self.assertIn("temp dir", desc)
- with _mock_mode("project"):
- desc = build_execute_code_schema()["description"]
- self.assertIn("session", desc)
-
-
-# ---------------------------------------------------------------------------
-# Integration: what actually happens when execute_code runs per mode
-# (host-neutral: strict tmpdir + venv interpreter resolve fine on Windows'
-# Scripts/python.exe layout; no POSIX-only layout is asserted)
-# ---------------------------------------------------------------------------
-
-class TestExecuteCodeModeIntegration(unittest.TestCase):
- """End-to-end: verify the subprocess actually runs where we expect."""
-
- def _run(self, code, mode, enabled_tools=None, extra_env=None):
- env_overrides = extra_env or {}
- with _mock_mode(mode):
- with patch.dict(os.environ, env_overrides):
- with patch("model_tools.handle_function_call",
- side_effect=_mock_handle_function_call):
- # reset=True: kernel cwd/interpreter are frozen at spawn
- # (like env), so mode-resolution rules are only
- # observable on a fresh kernel.
- raw = execute_code(
- code=code,
- task_id=f"test-{mode}",
- enabled_tools=enabled_tools or list(SANDBOX_ALLOWED_TOOLS),
- reset=True,
- )
- return json.loads(raw)
-
- def test_strict_mode_runs_in_tmpdir(self):
- """Strict mode: script's os.getcwd() is a staging tmpdir, never the
- session cwd. Behavior contract, not a prefix snapshot: the per-call
- path stages in hermes_sandbox_*, the session kernel in
- hermes_kernel_* — either satisfies strict mode's isolation promise."""
- result = self._run("import os; print(os.getcwd())", mode="strict")
- self.assertEqual(result["status"], "success")
- cwd = result["output"].strip()
- self.assertTrue(
- "hermes_sandbox_" in cwd or "hermes_kernel_" in cwd,
- f"strict-mode cwd is not a staging tmpdir: {cwd!r}",
- )
- self.assertNotEqual(os.path.realpath(cwd), os.path.realpath(os.getcwd()))
-
-
- def test_project_mode_interpreter_is_venv_python(self):
- """Project mode: sys.executable inside the child is the venv's python
- when VIRTUAL_ENV is set to a real venv."""
- # The hermes-agent venv is always active during tests, so this also
- # happens to equal sys.executable of the parent. What we're asserting
- # is: resolver picked a venv-bin/python path, not that it differs
- # from sys.executable.
- result = self._run("import sys; print(sys.executable)", mode="project")
- self.assertEqual(result["status"], "success")
- # Either VIRTUAL_ENV-bin/python or sys.executable fallback, both OK.
- output = result["output"].strip()
- ve = os.environ.get("VIRTUAL_ENV", "").strip()
- if ve:
- self.assertTrue(
- output.startswith(ve) or output == sys.executable,
- f"project-mode python should be under VIRTUAL_ENV={ve} or sys.executable={sys.executable}, got {output}",
- )
-
- def test_project_mode_can_still_import_hermes_tools(self):
- """Regression: hermes_tools still importable from non-tmpdir CWD.
-
- This is the PYTHONPATH fix — without it, switching to session CWD
- breaks `from hermes_tools import terminal`.
- """
- import shutil
- import tempfile
- from tools.code_kernel import shutdown_all_kernels
-
- td = tempfile.mkdtemp(prefix="hermes_test_cwd_")
- try:
- code = (
- "from hermes_tools import terminal\n"
- "r = terminal('echo x')\n"
- "print(r.get('output', 'MISSING'))\n"
- )
- result = self._run(code, mode="project", extra_env={"TERMINAL_CWD": td})
- self.assertEqual(result["status"], "success")
- self.assertIn("mock", result["output"])
- finally:
- # Release the child's cwd even when an assertion failed.
- shutdown_all_kernels()
- deadline = time.monotonic() + 10
- while True:
- try:
- shutil.rmtree(td)
- break
- except (PermissionError, FileNotFoundError):
- if time.monotonic() >= deadline:
- raise
- time.sleep(0.2)
-
- def test_strict_mode_can_still_import_hermes_tools(self):
- """Regression: strict mode's tmpdir CWD still works for imports."""
- code = (
- "from hermes_tools import terminal\n"
- "r = terminal('echo x')\n"
- "print(r.get('output', 'MISSING'))\n"
- )
- result = self._run(code, mode="strict")
- self.assertEqual(result["status"], "success")
- self.assertIn("mock", result["output"])
-
-
-# ---------------------------------------------------------------------------
-# SECURITY-CRITICAL regression guards
-#
-# These MUST pass in both strict and project mode. The whole tiered-mode
-# proposition rests on the claim that switching from strict to project only
-# changes CWD + interpreter, not the security posture.
-# Host-neutral: env scrubbing and whitelist enforcement run identically on
-# Windows — nothing here depends on POSIX venv layout.
-# ---------------------------------------------------------------------------
-
-class TestSecurityInvariantsAcrossModes(unittest.TestCase):
-
- def _run(self, code, mode):
- with _mock_mode(mode):
- with patch("model_tools.handle_function_call",
- side_effect=_mock_handle_function_call):
- raw = execute_code(
- code=code,
- task_id=f"test-sec-{mode}",
- enabled_tools=list(SANDBOX_ALLOWED_TOOLS),
- )
- return json.loads(raw)
-
- def test_api_keys_scrubbed_in_strict_mode(self):
- code = (
- "import os\n"
- "print('KEY=' + os.environ.get('OPENAI_API_KEY', 'MISSING'))\n"
- "print('TOK=' + os.environ.get('ANTHROPIC_API_KEY', 'MISSING'))\n"
- )
- with patch.dict(os.environ, {
- "OPENAI_API_KEY": "sk-should-not-leak",
- "ANTHROPIC_API_KEY": "ant-should-not-leak",
- }):
- result = self._run(code, mode="strict")
- self.assertEqual(result["status"], "success")
- self.assertIn("KEY=MISSING", result["output"])
- self.assertIn("TOK=MISSING", result["output"])
- self.assertNotIn("sk-should-not-leak", result["output"])
- self.assertNotIn("ant-should-not-leak", result["output"])
-
- def test_api_keys_scrubbed_in_project_mode(self):
- """CRITICAL: the project-mode default does NOT leak user credentials."""
- code = (
- "import os\n"
- "print('KEY=' + os.environ.get('OPENAI_API_KEY', 'MISSING'))\n"
- "print('TOK=' + os.environ.get('ANTHROPIC_API_KEY', 'MISSING'))\n"
- "print('SEC=' + os.environ.get('GITHUB_TOKEN', 'MISSING'))\n"
- )
- with patch.dict(os.environ, {
- "OPENAI_API_KEY": "sk-should-not-leak",
- "ANTHROPIC_API_KEY": "ant-should-not-leak",
- "GITHUB_TOKEN": "ghp-should-not-leak",
- }):
- result = self._run(code, mode="project")
- self.assertEqual(result["status"], "success")
- for needle in ("KEY=MISSING", "TOK=MISSING", "SEC=MISSING"):
- self.assertIn(needle, result["output"])
- for leaked in ("sk-should-not-leak", "ant-should-not-leak", "ghp-should-not-leak"):
- self.assertNotIn(leaked, result["output"])
-
- def test_secret_substrings_scrubbed_in_project_mode(self):
- """SECRET/PASSWORD/CREDENTIAL/PASSWD/AUTH filters still apply."""
- code = (
- "import os\n"
- "for k in ('MY_SECRET', 'DB_PASSWORD', 'VAULT_CREDENTIAL', "
- "'LDAP_PASSWD', 'AUTH_TOKEN'):\n"
- " print(f'{k}=' + os.environ.get(k, 'MISSING'))\n"
- )
- with patch.dict(os.environ, {
- "MY_SECRET": "secret-should-not-leak",
- "DB_PASSWORD": "password-should-not-leak",
- "VAULT_CREDENTIAL": "cred-should-not-leak",
- "LDAP_PASSWD": "passwd-should-not-leak",
- "AUTH_TOKEN": "auth-should-not-leak",
- }):
- result = self._run(code, mode="project")
- self.assertEqual(result["status"], "success")
- for leaked in ("secret-should-not-leak", "password-should-not-leak",
- "cred-should-not-leak", "passwd-should-not-leak",
- "auth-should-not-leak"):
- self.assertNotIn(leaked, result["output"])
-
- def test_tool_whitelist_enforced_in_strict_mode(self):
- """A script cannot RPC-call tools outside SANDBOX_ALLOWED_TOOLS."""
- # execute_code is NOT in SANDBOX_ALLOWED_TOOLS (no recursion)
- self.assertNotIn("execute_code", SANDBOX_ALLOWED_TOOLS)
- code = (
- "import hermes_tools as ht\n"
- "print('execute_code_available:', hasattr(ht, 'execute_code'))\n"
- "print('delegate_task_available:', hasattr(ht, 'delegate_task'))\n"
- )
- result = self._run(code, mode="strict")
- self.assertEqual(result["status"], "success")
- self.assertIn("execute_code_available: False", result["output"])
- self.assertIn("delegate_task_available: False", result["output"])
-
- def test_tool_whitelist_enforced_in_project_mode(self):
- """CRITICAL: project mode does NOT widen the tool whitelist."""
- code = (
- "import hermes_tools as ht\n"
- "print('execute_code_available:', hasattr(ht, 'execute_code'))\n"
- "print('delegate_task_available:', hasattr(ht, 'delegate_task'))\n"
- )
- result = self._run(code, mode="project")
- self.assertEqual(result["status"], "success")
- self.assertIn("execute_code_available: False", result["output"])
- self.assertIn("delegate_task_available: False", result["output"])
-
-
-# ---------------------------------------------------------------------------
-# _python_environment_prefix / _uses_hermes_python_environment
-# ---------------------------------------------------------------------------
-
-class TestPythonEnvironmentPrefix(unittest.TestCase):
- """Unit tests for the helper that queries sys.prefix of an interpreter."""
-
- def setUp(self):
- _python_prefix_cache.clear()
-
- def tearDown(self):
- _python_prefix_cache.clear()
-
- def test_returns_realpath_of_current_interpreter_prefix(self):
- """Happy path: sys.executable reports its own prefix."""
- prefix = _python_environment_prefix(sys.executable)
- self.assertEqual(prefix, os.path.realpath(sys.prefix))
-
- def test_returns_empty_string_for_nonexistent_path(self):
- """A path that doesn't exist → OSError → empty string."""
- result = _python_environment_prefix("/nonexistent/python-does-not-exist")
- self.assertEqual(result, "")
-
- def test_returns_empty_string_when_subprocess_times_out(self):
- with patch("subprocess.run", side_effect=subprocess.TimeoutExpired(cmd=[], timeout=5)):
- result = _python_environment_prefix("/some/python")
- self.assertEqual(result, "")
-
- def test_returns_empty_string_on_nonzero_exit(self):
- mock_result = unittest.mock.MagicMock()
- mock_result.returncode = 1
- mock_result.stdout = ""
- with patch("subprocess.run", return_value=mock_result):
- result = _python_environment_prefix("/bad/python")
- self.assertEqual(result, "")
-
- def test_returns_empty_string_when_stdout_is_blank(self):
- mock_result = unittest.mock.MagicMock()
- mock_result.returncode = 0
- mock_result.stdout = " \n"
- with patch("subprocess.run", return_value=mock_result):
- result = _python_environment_prefix("/blank/python")
- self.assertEqual(result, "")
-
- def test_result_is_cached(self):
- """Second call returns cached value without spawning another process."""
- with patch("subprocess.run") as mock_run:
- mock_run.return_value = unittest.mock.MagicMock(
- returncode=0, stdout="/fake/prefix\n"
- )
- _python_environment_prefix("/cached/python")
- _python_environment_prefix("/cached/python")
- self.assertEqual(mock_run.call_count, 1)
-
- def test_failure_is_not_cached(self):
- """A transient probe failure must not stick — the next call retries.
-
- A sticky cached failure would silently drop the hermes root from
- every subsequent execute_code call in the process.
- """
- with patch("subprocess.run",
- side_effect=subprocess.TimeoutExpired(cmd=[], timeout=5)) as mock_run:
- self.assertEqual(_python_environment_prefix("/flaky/python"), "")
- self.assertEqual(mock_run.call_count, 1)
- with patch("subprocess.run") as mock_run:
- mock_run.return_value = unittest.mock.MagicMock(
- returncode=0, stdout="/recovered/prefix\n"
- )
- result = _python_environment_prefix("/flaky/python")
- self.assertEqual(mock_run.call_count, 1, "probe must be retried after a failure")
- self.assertEqual(result, os.path.realpath("/recovered/prefix"))
-
-
-class TestUsesHermesPythonEnvironment(unittest.TestCase):
- """Unit tests for _uses_hermes_python_environment."""
-
- def setUp(self):
- _python_prefix_cache.clear()
-
- def tearDown(self):
- _python_prefix_cache.clear()
-
- def test_true_for_current_interpreter(self):
- """sys.executable always belongs to the current environment."""
- self.assertTrue(_uses_hermes_python_environment(sys.executable))
-
- def test_true_for_current_interpreter_without_probe(self):
- """sys.executable short-circuits — no subprocess probe on the default path.
-
- Guards the strict-mode invariant: a flaky probe (timeout under load)
- must never drop the hermes root for the interpreter Hermes itself runs.
- """
- with patch("subprocess.run",
- side_effect=subprocess.TimeoutExpired(cmd=[], timeout=5)) as mock_run:
- self.assertTrue(_uses_hermes_python_environment(sys.executable))
- mock_run.assert_not_called()
-
- def test_false_for_different_prefix(self):
- """An interpreter reporting a different prefix is external."""
- with patch("tools.code_execution_env._python_environment_prefix",
- return_value="/some/other/venv"):
- self.assertFalse(_uses_hermes_python_environment("/other/python"))
-
- def test_false_when_prefix_is_empty(self):
- """If prefix cannot be determined (error path), treat as external."""
- with patch("tools.code_execution_env._python_environment_prefix",
- return_value=""):
- self.assertFalse(_uses_hermes_python_environment("/bad/python"))
-
- def test_true_when_prefix_matches_sys_prefix(self):
- hermes_prefix = os.path.realpath(sys.prefix)
- with patch("tools.code_execution_env._python_environment_prefix",
- return_value=hermes_prefix):
- self.assertTrue(_uses_hermes_python_environment("/same/env/python"))
-
-
-# ---------------------------------------------------------------------------
-# PYTHONPATH composition — hermes root included only for same-env interpreters
-# ---------------------------------------------------------------------------
-
-class TestPythonPathComposition(unittest.TestCase):
- """Verify hermes root inclusion in PYTHONPATH depends on env match.
-
- Patches ``_uses_hermes_python_environment`` directly so these tests are
- independent of subprocess availability — the unit tests above already
- cover the detection logic end-to-end.
- """
-
- def _capture_pythonpath(self, same_env: bool) -> tuple:
- """Return (PYTHONPATH, staging_dir) that execute_code passes to the child."""
- captured = {}
-
- class _Captured(RuntimeError):
- pass
-
- def _fake_popen(cmd, **kwargs):
- env = kwargs.get("env") or {}
- captured["PYTHONPATH"] = env.get("PYTHONPATH", "")
- # cmd is [python, <staging_dir>/script.py] (per-call) or
- # [python, <staging_dir>/hermes_kernel_runner.py] (session
- # kernel) — staging dir derivation is identical.
- captured["staging_dir"] = os.path.dirname(cmd[1])
- # Abort the spawn after capture: returning a MagicMock proc
- # would leave the kernel's reader threads spinning on mock
- # reads and hang the cell wait loop (always-on session
- # kernels; the pre-kernel version of this helper could get
- # away with a fake proc because the per-call path only
- # .wait()ed on it).
- raise _Captured()
-
- with patch("tools.code_execution_tool._load_config", return_value={"mode": "strict"}), \
- patch("model_tools.handle_function_call", side_effect=_mock_handle_function_call), \
- patch("tools.code_execution_env._uses_hermes_python_environment",
- return_value=same_env), \
- patch("subprocess.Popen", side_effect=_fake_popen):
- try:
- execute_code(code="pass", task_id="test-pp",
- enabled_tools=[], reset=True)
- except _Captured:
- pass # expected: spawn aborted right after env capture
- except Exception:
- pass # kernel path wraps the abort; capture already happened
-
- # If execute_code never reached Popen, the capture is empty and any
- # "X not in PYTHONPATH" assertion downstream would pass vacuously.
- self.assertIn("PYTHONPATH", captured,
- "execute_code never spawned the child process")
- return captured["PYTHONPATH"], captured["staging_dir"]
-
- def _hermes_root(self) -> str:
- import tools.code_execution_tool as _cet
- tools_dir = os.path.dirname(os.path.abspath(_cet.__file__))
- return os.path.dirname(tools_dir)
-
- def test_hermes_root_included_when_same_env(self):
- """When interpreter is in the Hermes env, hermes root is in PYTHONPATH."""
- pythonpath, _ = self._capture_pythonpath(same_env=True)
- parts = pythonpath.split(os.pathsep)
- self.assertIn(self._hermes_root(), parts,
- "hermes root must be in PYTHONPATH for same-env interpreters")
-
- def test_hermes_root_excluded_when_external_env(self):
- """When interpreter is external, hermes root must NOT be in PYTHONPATH."""
- pythonpath, _ = self._capture_pythonpath(same_env=False)
- parts = pythonpath.split(os.pathsep)
- self.assertNotIn(self._hermes_root(), parts,
- "hermes root must not leak into an external interpreter's PYTHONPATH")
-
- def test_staging_dir_always_first(self):
- """The staging tmpdir must always be the first PYTHONPATH entry."""
- for same_env in (True, False):
- with self.subTest(same_env=same_env):
- pythonpath, staging_dir = self._capture_pythonpath(same_env=same_env)
- parts = pythonpath.split(os.pathsep)
- self.assertEqual(parts[0], staging_dir,
- "PYTHONPATH must start with the staging tmpdir")
-
-
-if __name__ == "__main__":
- unittest.main()
+from tests.tools._child_env_fixtures import child_env, project_python, run_code # noqa: F401
+from tools import code_execution_env as ce
+from tools.code_execution_tool import build_execute_code_schema
+
+
[email protected]("linux", "macos", "windows")
[email protected]("mode", ["strict", "project"])
[email protected]("activation", ["VIRTUAL_ENV", "CONDA_PREFIX"])
+def test_selected_interpreter_environment_and_real_rpc(child_env, project_python, monkeypatch, mode, activation):
+ python, prefix = project_python
+ monkeypatch.setenv(activation, str(prefix))
+ repo = Path(__file__).resolve().parents[2]
+ site = Path(sys.prefix) / ("Lib/site-packages" if os.name == "nt" else
+ f"lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages")
+ user_lib = child_env / "user-lib"
+ user_lib.mkdir()
+ (user_lib / "user_probe.py").write_text("VALUE = 'user → 雪'\n", encoding="utf-8")
+ witness = child_env / "rpc-witness.txt"
+ witness.write_text("RPC → 雪\n", encoding="utf-8")
+ monkeypatch.setenv("PYTHONPATH", os.pathsep.join(map(str, [repo, site, repo, user_lib, user_lib])))
+ monkeypatch.setenv("OPENAI_API_KEY", "fake-provider-secret")
+ before = dict(os.environ)
+ result = run_code(f'''
+import importlib.util, json, os, sys
+import hermes_tools, user_probe
+from hermes_tools import read_file
+print(json.dumps({{
+ "executable": sys.executable, "prefix": sys.prefix, "cwd": os.getcwd(),
+ "pythonpath": os.environ["PYTHONPATH"].split(os.pathsep),
+ "sys_path": sys.path,
+ "staging": os.path.dirname(hermes_tools.__file__),
+ "encoding": [os.environ.get("PYTHONIOENCODING"), os.environ.get("PYTHONUTF8")],
+ "essentials": {{k: os.environ.get(k) for k in ("SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT")}},
+ "secret": os.environ.get("OPENAI_API_KEY"),
+ "project": (__import__("project_only_probe").VALUE
+ if importlib.util.find_spec("project_only_probe") else None),
+ "user": user_probe.VALUE, "rpc": read_file({str(witness)!r}),
+}}, ensure_ascii=False))
+''', mode)
+ assert result["encoding"] == ["utf-8", "1"]
+ if os.name == "nt":
+ assert result["essentials"] == {k: before.get(k) for k in result["essentials"]}
+ assert result["secret"] is None
+ assert result["user"] == "user → 雪"
+ assert "RPC → 雪" in result["rpc"]["content"]
+ assert result["rpc"]["total_lines"] == 1
+ expected_python, expected_prefix = (python, prefix) if mode == "project" else (Path(sys.executable), Path(sys.prefix))
+ assert Path(result["executable"]) == expected_python
+ assert Path(result["prefix"]).resolve() == expected_prefix.resolve()
+ assert result["project"] == ("project-only → 雪" if mode == "project" else None)
+ if mode == "project":
+ assert os.path.normcase(str(site)) not in list(map(os.path.normcase, result["sys_path"]))
+ expected_cwd = child_env if mode == "project" else Path(result["staging"])
+ assert Path(result["cwd"]).resolve() == expected_cwd.resolve()
+ controlled = [result["staging"]] + ([str(repo)] if mode == "strict" else [])
+ assert list(map(os.path.normcase, result["pythonpath"])) == list(map(os.path.normcase, controlled + [str(user_lib)] * 2))
+ assert dict(os.environ) == before
+
+
[email protected]("linux", "macos", "windows")
[email protected]("mode", ["strict", "project"])
+def test_credential_policy_and_whitelist_in_real_child(child_env, monkeypatch, mode):
+ from tools.env_passthrough import register_env_passthrough
+ blocked = (
+ "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GITHUB_TOKEN", "MY_SECRET",
+ "DB_PASSWORD", "VAULT_CREDENTIAL", "LDAP_PASSWD", "AUTH_TOKEN",
+ "SENTRY_DSN", "SLACK_WEBHOOK", "HOME_APIKEY", "USER_CREDS", "TERM_BEARER",
+ "HERMES_BASE_URL", "HERMES_INTERACTIVE", "BUZZ_PRIVATE_KEY", "RANDOM_UNKNOWN",
+ )
+ allowed = ("HERMES_PROFILE", "HERMES_CONFIG", "HERMES_ENV", "LC_ENV_TEST", "TENOR_API_KEY")
+ for name in blocked + allowed:
+ monkeypatch.setenv(name, "fake-" + name)
+ # Registration is real: a skill cannot tunnel a provider or Buzz credential.
+ register_env_passthrough(["TENOR_API_KEY", "OPENAI_API_KEY", "BUZZ_PRIVATE_KEY"])
+ result = run_code(f'''
+import json, os, hermes_tools
+print(json.dumps({{"env": {{k: os.environ.get(k) for k in {blocked + allowed!r}}},
+ "recursive": hasattr(hermes_tools, "execute_code"),
+ "delegation": hasattr(hermes_tools, "delegate_task")}}))
+''', mode, enabled_tools=("read_file", "execute_code", "delegate_task"))
+ assert result["env"] == {**dict.fromkeys(blocked), **{k: "fake-" + k for k in allowed}}
+ assert result["recursive"] is False
+ assert result["delegation"] is False
+
+
[email protected]("helper,cache,failed,success", [
+ (ce._is_usable_python, ce._usable_python_cache, False, True),
+ (ce._python_environment_prefix, ce._python_prefix_cache, "", os.path.realpath("recovered-prefix")),
+])
+def test_probe_retries_transient_failure_and_caches_success(helper, cache, failed, success):
+ cache.clear()
+ try:
+ with patch("subprocess.run", side_effect=[
+ subprocess.TimeoutExpired(cmd=[], timeout=5),
+ subprocess.CompletedProcess([], 0, "recovered-prefix\n"),
+ ]) as run:
+ assert helper("probe-python") == failed
+ assert helper("probe-python") == success
+ assert helper("probe-python") == success
+ assert run.call_count == 2
+ finally:
+ cache.clear()
+
+
[email protected]("outcome", [
+ OSError("missing interpreter"), subprocess.CompletedProcess([], 1, ""),
+ subprocess.CompletedProcess([], 0, " \n"),
+])
+def test_unknown_prefix_is_not_cached(outcome):
+ ce._python_prefix_cache.clear()
+ with patch("subprocess.run", side_effect=outcome if isinstance(outcome, Exception) else None,
+ return_value=outcome) as run:
+ assert ce._python_environment_prefix("bad-python") == ""
+ assert ce._python_environment_prefix("bad-python") == ""
+ assert run.call_count == 2
+ assert "bad-python" not in ce._python_prefix_cache
+
+
+def test_current_interpreter_needs_no_probe():
+ with patch("subprocess.run", side_effect=AssertionError("unexpected probe")):
+ assert ce._uses_hermes_python_environment(sys.executable)
+
+
+def test_project_without_active_venv_falls_back(child_env):
+ assert ce._resolve_child_python("project") == sys.executable
+
+
+def test_project_stale_cwd_falls_through_then_uses_process_cwd(child_env, monkeypatch):
+ from tools import terminal_tool
+ monkeypatch.setattr(terminal_tool, "_task_env_overrides", {})
+ monkeypatch.setattr(terminal_tool, "_session_cwd", {})
+ terminal_tool.register_task_env_overrides("stale", {"cwd": str(child_env)})
+ terminal_tool.record_session_cwd("stale", str(child_env / "deleted"))
+ monkeypatch.setenv("TERMINAL_CWD", str(child_env / "missing"))
+ assert ce._resolve_child_cwd("project", "staging", task_id="stale") == str(child_env)
+ assert ce._resolve_child_cwd("project", "staging") == os.getcwd()
+
+
[email protected]("mode,description", [("strict", "temp dir"), ("project", "session")])
+def test_mode_schema_matches_config_without_claiming_isolation(mode, description):
+ with patch("tools.code_execution_tool._load_config", return_value={"mode": mode}):
+ text = build_execute_code_schema()["description"].lower()
+ assert description in text
+ assert not any(word in text for word in ("sandbox", "isolated", "cloud"))
diff --git a/tests/tools/test_code_execution_windows_env.py b/tests/tools/test_code_execution_windows_env.py
index aced2ffcb6c..f1300fa5913 100644
--- a/tests/tools/test_code_execution_windows_env.py
+++ b/tests/tools/test_code_execution_windows_env.py
@@ -1,23 +1,7 @@
-"""Tests for execute_code env scrubbing on Windows.
+"""Windows essentials and native Winsock/legacy-encoding controls.
-On Windows the child process needs a small set of OS-essential env vars
-(SYSTEMROOT, WINDIR, COMSPEC, ...) to run. Without SYSTEMROOT in particular,
-``socket.socket(AF_INET, SOCK_STREAM)`` fails inside the sandbox with
-WinError 10106 (Winsock can't locate mswsock.dll) and no tool call over
-loopback TCP can ever succeed.
-
-These tests cover ``_scrub_child_env`` directly so they run on every OS
-— the logic is conditional on a passed-in ``is_windows`` flag, not on
-the host platform. We also keep a live Winsock smoke test that only runs
-on a real Windows host.
-
-Also covers the companion Windows bug: the sandbox writes
-``hermes_tools.py`` and ``script.py`` into a temp dir, and those files
-must be written as UTF-8 on every platform — the generated stub contains
-em-dash/en-dash characters in docstrings, and the default ``open(path, "w")``
-on Windows uses the system locale (cp1252 typically), corrupting those
-bytes. The child then fails to import with a SyntaxError:
-``'utf-8' codec can't decode byte 0x97``.
+Actual production UTF-8 env and Unicode RPC are exercised in
+`test_code_execution_modes.py`; never reproduce the production scrubber here.
"""
import os
@@ -27,168 +11,34 @@ import textwrap
import pytest
-from tools.code_execution_env import (
- _SECRET_SUBSTRINGS,
- _WINDOWS_ESSENTIAL_ENV_VARS,
- _scrub_child_env,
-)
+from tools.code_execution_env import _scrub_child_env
-def _no_passthrough(_name):
+def _no_passthrough(_):
return False
-class TestWindowsEssentialAllowlist:
- """The allowlist itself — contents, shape, and invariants."""
-
- def test_contains_winsock_required_vars(self):
- # Without SYSTEMROOT the child cannot initialize Winsock.
- assert "SYSTEMROOT" in _WINDOWS_ESSENTIAL_ENV_VARS
-
-
- def test_contains_only_uppercase_names(self):
- # Windows env var names are case-insensitive but we canonicalize to
- # uppercase for the membership check (``k.upper() in _WINDOWS_...``).
- for name in _WINDOWS_ESSENTIAL_ENV_VARS:
- assert name == name.upper(), f"{name!r} should be uppercase"
-
- def test_no_overlap_with_secret_substrings(self):
- # Sanity: none of the essential OS vars should look like secrets.
- # If this ever fires, we'd have a precedence ordering bug (secrets
- # are blocked *before* the essentials check).
- for name in _WINDOWS_ESSENTIAL_ENV_VARS:
- assert not any(s in name for s in _SECRET_SUBSTRINGS), (
- f"{name!r} looks secret-like — would be blocked before the "
- "essentials allowlist can match"
- )
-
-
-class TestScrubChildEnvWindows:
- """Verify _scrub_child_env passes Windows essentials through when
- is_windows=True and blocks them when is_windows=False (so POSIX hosts
- don't inherit pointless Windows vars)."""
-
- def _sample_windows_env(self):
- """A realistic subset of what os.environ looks like on Windows."""
- return {
- "SYSTEMROOT": r"C:\Windows",
- "SystemDrive": "C:", # Windows preserves native case
- "WINDIR": r"C:\Windows",
- "ComSpec": r"C:\Windows\System32\cmd.exe",
[email protected]("windows", [False, True])
[email protected]("passthrough", [False, True])
+def test_native_essentials_and_passthrough_priority(windows, passthrough):
+ # Platform is explicit input to this pure policy helper, not a fake host.
+ essentials = {
+ "SYSTEMROOT": r"C:\Windows", "SystemRoot": r"C:\Windows",
+ "SystemDrive": "C:", "WINDIR": r"C:\Windows",
+ "ComSpec": r"C:\Windows\System32\cmd.exe", "comspec": r"C:\Windows\System32\cmd.exe",
+ "APPDATA": r"C:\Users\alice\AppData\Roaming",
+ "LOCALAPPDATA": r"C:\Users\alice\AppData\Local",
+ }
+ safe = {"PATH": r"C:\Windows\System32;C:\Python", "HOME": r"C:\Users\alice",
"PATHEXT": ".COM;.EXE;.BAT;.CMD;.PY",
- "USERPROFILE": r"C:\Users\alice",
- "APPDATA": r"C:\Users\alice\AppData\Roaming",
- "LOCALAPPDATA": r"C:\Users\alice\AppData\Local",
- "PATH": r"C:\Windows\System32;C:\Python311",
- "HOME": r"C:\Users\alice",
- "TEMP": r"C:\Users\alice\AppData\Local\Temp",
- # Should still be blocked:
- "OPENAI_API_KEY": "sk-secret",
- "GITHUB_TOKEN": "ghp_secret",
- "MY_PASSWORD": "hunter2",
- # Not matched by any rule — should be dropped on both OSes:
- "RANDOM_UNKNOWN_VAR": "value",
- }
-
- def test_windows_essentials_passed_through_when_is_windows_true(self):
- env = self._sample_windows_env()
- scrubbed = _scrub_child_env(env,
- is_passthrough=_no_passthrough,
- is_windows=True)
-
- # Every essential var from the sample env should survive.
- assert scrubbed["SYSTEMROOT"] == r"C:\Windows"
- assert scrubbed["SystemDrive"] == "C:" # case preserved
- assert scrubbed["WINDIR"] == r"C:\Windows"
- assert scrubbed["ComSpec"] == r"C:\Windows\System32\cmd.exe"
- assert scrubbed["PATHEXT"] == ".COM;.EXE;.BAT;.CMD;.PY"
- assert scrubbed["USERPROFILE"] == r"C:\Users\alice"
- assert scrubbed["APPDATA"].endswith("Roaming")
- assert scrubbed["LOCALAPPDATA"].endswith("Local")
-
- # Safe-prefix vars still pass (baseline behavior).
- assert "PATH" in scrubbed
- assert "HOME" in scrubbed
- assert "TEMP" in scrubbed
-
- def test_secrets_still_blocked_on_windows(self):
- """The Windows allowlist must NOT defeat the secret-substring block.
-
- This is the key security invariant: essentials are allowed by
- *exact name*, and the secret-substring block runs before the
- essentials check anyway, so a variable named e.g. ``API_KEY`` can
- never sneak through just because we added Windows support.
- """
- env = self._sample_windows_env()
- scrubbed = _scrub_child_env(env,
- is_passthrough=_no_passthrough,
- is_windows=True)
- assert "OPENAI_API_KEY" not in scrubbed
- assert "GITHUB_TOKEN" not in scrubbed
- assert "MY_PASSWORD" not in scrubbed
-
-
- def test_essentials_blocked_when_is_windows_false(self):
- """On POSIX hosts, Windows-specific vars should not pass — they
- have no meaning and could confuse child tooling."""
- env = self._sample_windows_env()
- scrubbed = _scrub_child_env(env,
- is_passthrough=_no_passthrough,
- is_windows=False)
- # Safe prefixes still match (PATH, HOME, TEMP).
- assert "PATH" in scrubbed
- assert "HOME" in scrubbed
- assert "TEMP" in scrubbed
- # But Windows OS vars should be dropped.
- assert "SYSTEMROOT" not in scrubbed
- assert "WINDIR" not in scrubbed
- assert "ComSpec" not in scrubbed
- assert "APPDATA" not in scrubbed
-
- def test_case_insensitive_essential_match(self):
- """Windows env var names are case-insensitive at the OS level but
- Python preserves whatever case os.environ reported. The scrubber
- must normalize to uppercase for the membership check."""
- env = {
- "SystemRoot": r"C:\Windows", # mixed case
- "comspec": r"C:\Windows\System32\cmd.exe", # lowercase
- "APPDATA": r"C:\Users\x\AppData\Roaming", # uppercase
- }
- scrubbed = _scrub_child_env(env,
- is_passthrough=_no_passthrough,
- is_windows=True)
- assert "SystemRoot" in scrubbed
- assert "comspec" in scrubbed
- assert "APPDATA" in scrubbed
-
-
-class TestScrubChildEnvPassthroughInteraction:
- """The passthrough hook runs *before* the secret block, so a skill
- can legitimately forward a third-party API key. The Windows
- essentials addition must not interfere with that."""
-
- def test_passthrough_wins_over_secret_block(self):
- env = {"TENOR_API_KEY": "x", "PATH": "/bin"}
- scrubbed = _scrub_child_env(env,
- is_passthrough=lambda k: k == "TENOR_API_KEY",
- is_windows=False)
- assert scrubbed.get("TENOR_API_KEY") == "x"
- assert scrubbed.get("PATH") == "/bin"
-
- def test_passthrough_still_works_on_windows(self):
- env = {
- "TENOR_API_KEY": "x",
- "SYSTEMROOT": r"C:\Windows",
- "OPENAI_API_KEY": "sk-secret", # not passthrough
- }
- scrubbed = _scrub_child_env(
- env,
- is_passthrough=lambda k: k == "TENOR_API_KEY",
- is_windows=True,
- )
- assert scrubbed.get("TENOR_API_KEY") == "x"
- assert scrubbed.get("SYSTEMROOT") == r"C:\Windows"
- assert "OPENAI_API_KEY" not in scrubbed
+ "USERPROFILE": r"C:\Users\alice", "TEMP": r"C:\Users\alice\Temp"}
+ secret = {"OPENAI_API_KEY": "fake-provider", "GITHUB_TOKEN": "fake-github",
+ "MY_PASSWORD": "fake-password", "TENOR_API_KEY": "fake-third-party",
+ "RANDOM_UNKNOWN_VAR": "unknown"}
+ result = _scrub_child_env({**essentials, **safe, **secret}, is_windows=windows,
+ is_passthrough=lambda k: passthrough and k == "TENOR_API_KEY")
+ assert result == {**safe, **(essentials if windows else {}),
+ **({"TENOR_API_KEY": "fake-third-party"} if passthrough else {})}
# ``platforms("windows")`` rather than ``skipif(sys.platform != "win32")``: the
@@ -234,252 +84,7 @@ class TestWindowsSocketSmokeTest:
assert "OK" in result.stdout
-# ---------------------------------------------------------------------------
-# POSIX equivalence guard
-# ---------------------------------------------------------------------------
-
-def _legacy_posix_scrubber(source_env, is_passthrough):
- """Independent oracle for TestPosixEquivalence — a from-scratch reimpl of
- _scrub_child_env's POSIX behavior, used to prove the production helper does
- what we think it does.
-
- Deliberately updated for #27303 (the broad ``HERMES_`` prefix was dropped
- in favor of an explicit operational allowlist, and DSN/WEBHOOK were added
- to the secret substrings). The original docstring said: if POSIX behavior
- legitimately needs to evolve, adjust this oracle on purpose so the churn is
- visible in review — that is what this change is.
- """
- _SAFE_ENV_PREFIXES = ("PATH", "HOME", "USER", "LANG", "LC_", "TERM",
- "TMPDIR", "TMP", "TEMP", "SHELL", "LOGNAME",
- "XDG_", "PYTHONPATH", "VIRTUAL_ENV", "CONDA")
- _SECRET_SUBSTRINGS = ("KEY", "TOKEN", "SECRET", "PASSWORD", "CREDENTIAL",
- "PASSWD", "AUTH", "DSN", "WEBHOOK")
- _HERMES_CHILD_ALLOWED = frozenset({
- "HERMES_HOME", "HERMES_PROFILE", "HERMES_CONFIG", "HERMES_ENV",
- })
- out = {}
- for k, v in source_env.items():
- if is_passthrough(k):
- out[k] = v
- continue
- if any(s in k.upper() for s in _SECRET_SUBSTRINGS):
- continue
- if any(k.startswith(p) for p in _SAFE_ENV_PREFIXES):
- out[k] = v
- continue
- if k in _HERMES_CHILD_ALLOWED:
- out[k] = v
- return out
-
-
-class TestPosixEquivalence:
- """Lock in the invariant that _scrub_child_env(env, is_windows=False)
- behaves *bit-for-bit identically* to the pre-refactor inline scrubber.
-
- If this ever fails, it means somebody changed POSIX env-scrubbing
- behavior — maybe on purpose, maybe not. Either way it should land
- as a deliberate, reviewed change (update _legacy_posix_scrubber
- above in the same PR).
-
- Rationale: the Windows-essentials patch refactored the scrubber into
- a helper. Linux/macOS must not regress. This class gates that.
- """
-
- _POSIX_SYNTHETIC_ENV = {
- # Safe-prefix matches
- "PATH": "/usr/bin:/bin",
- "HOME": "/home/alice",
- "USER": "alice",
- "LANG": "en_US.UTF-8",
- "LC_CTYPE": "en_US.UTF-8",
- "TERM": "xterm-256color",
- "SHELL": "/bin/zsh",
- "LOGNAME": "alice",
- "TMPDIR": "/tmp",
- "XDG_RUNTIME_DIR": "/run/user/1000",
- "XDG_CONFIG_HOME": "/home/alice/.config",
- "PYTHONPATH": "/opt/lib",
- "VIRTUAL_ENV": "/home/alice/.venv",
- "CONDA_PREFIX": "/opt/conda",
- # HERMES_* handling (#27303): only the operational allowlist passes;
- # every other HERMES_* is dropped (the broad prefix was removed).
- "HERMES_HOME": "/home/alice/.hermes", # allowlisted → kept
- "HERMES_PROFILE": "default", # allowlisted → kept
- "HERMES_INTERACTIVE": "1", # not allowlisted → dropped
- "HERMES_BASE_URL": "https://api.internal", # not allowlisted → dropped
- "HERMES_KANBAN_DB": "postgres://u:p@h/db", # not allowlisted → dropped
- # Secret-substring blocks
- "OPENAI_API_KEY": "sk-xxx",
- "GITHUB_TOKEN": "ghp_xxx",
- "AWS_SECRET_ACCESS_KEY": "yyy",
- "MY_PASSWORD": "hunter2",
- "SENTRY_DSN": "https://[email protected]/1", # DSN substring → blocked
- "SLACK_WEBHOOK": "https://hooks.slack/x", # WEBHOOK substring → blocked
- # Uncategorized — must be dropped
- "RANDOM_UNKNOWN": "drop-me",
- "DISPLAY": ":0",
- "SSH_AUTH_SOCK": "/run/user/1000/ssh-agent",
- # Passthrough candidate (also matches secret block by default)
- "TENOR_API_KEY": "tenor-xxx",
- }
-
- _WINDOWS_SYNTHETIC_ENV = {
- # Windows-essential names (must be dropped on POSIX, passed on Win)
- "SYSTEMROOT": r"C:\Windows",
- "SystemDrive": "C:",
- "WINDIR": r"C:\Windows",
- "ComSpec": r"C:\Windows\System32\cmd.exe",
- "PATHEXT": ".COM;.EXE;.BAT",
- "USERPROFILE": r"C:\Users\alice",
- "APPDATA": r"C:\Users\alice\AppData\Roaming",
- "LOCALAPPDATA": r"C:\Users\alice\AppData\Local",
- # Safe-prefix matches (cross-platform)
- "PATH": r"C:\Python311;C:\Windows\System32",
- "HOME": r"C:\Users\alice",
- "TEMP": r"C:\Users\alice\AppData\Local\Temp",
- # Secret-looking (always blocked)
- "OPENAI_API_KEY": "sk-xxx",
- "GITHUB_TOKEN": "ghp_xxx",
- }
-
- @pytest.mark.parametrize("env_name,env", [
- ("posix_synthetic", _POSIX_SYNTHETIC_ENV),
- ("windows_synthetic_on_posix", _WINDOWS_SYNTHETIC_ENV),
- ])
- @pytest.mark.parametrize("pt_name,pt", [
- ("no_passthrough", lambda _: False),
- ("tenor_passthrough", lambda k: k == "TENOR_API_KEY"),
- ("all_passthrough", lambda _: True),
- ])
- def test_posix_behavior_unchanged(self, env_name, env, pt_name, pt):
- """For every combination of (env shape × passthrough rule), the
- new helper with is_windows=False must produce the exact same dict
- as the legacy inline scrubber.
-
- We parametrize over three passthrough rules to cover the full
- surface: no passthrough, single-var passthrough (the common
- skill-registered case), and everything-passes (edge case that
- could expose precedence bugs)."""
- expected = _legacy_posix_scrubber(env, pt)
- actual = _scrub_child_env(env, is_passthrough=pt, is_windows=False)
- assert actual == expected, (
- f"POSIX behavior regressed for env={env_name}, passthrough={pt_name}\n"
- f" only in legacy: {sorted(set(expected) - set(actual))}\n"
- f" only in new: {sorted(set(actual) - set(expected))}\n"
- f" value diffs: {[k for k in expected if k in actual and expected[k] != actual[k]]}"
- )
-
-
- def test_windows_mode_is_strict_superset_of_posix_mode(self):
- """Correctness check on the NEW behavior: is_windows=True must
- keep everything POSIX mode keeps, and *may* add Windows
- essentials. It must never drop a var that POSIX mode would keep
- — if it did, we'd have broken same-host reuse of the scrubber."""
- env = {**self._POSIX_SYNTHETIC_ENV, **self._WINDOWS_SYNTHETIC_ENV}
- posix_result = _scrub_child_env(env,
- is_passthrough=lambda _: False,
- is_windows=False)
- windows_result = _scrub_child_env(env,
- is_passthrough=lambda _: False,
- is_windows=True)
- missing = set(posix_result) - set(windows_result)
- assert not missing, (
- f"is_windows=True dropped vars that is_windows=False kept: {missing}"
- )
- # And any extras must come from the Windows essentials allowlist.
- extras = set(windows_result) - set(posix_result)
- for k in extras:
- assert k.upper() in _WINDOWS_ESSENTIAL_ENV_VARS, (
- f"Unexpected extra var in windows-mode output: {k} "
- f"(not in _WINDOWS_ESSENTIAL_ENV_VARS)"
- )
-
-
-# ---------------------------------------------------------------------------
-# UTF-8 file-write regression test
-# ---------------------------------------------------------------------------
-#
-# The sandbox writes two Python files into a temp dir — the generated
-# ``hermes_tools.py`` stub, and the LLM's ``script.py``. Both contain
-# non-ASCII characters in practice: the stub has em-dashes in docstrings
-# ("``tcp://host:port`` — the parent falls back..."), and user scripts
-# routinely contain non-ASCII strings, comments, or Unicode identifiers.
-#
-# On Windows, ``open(path, "w")`` without encoding= uses the system locale
-# (cp1252 on US/UK installs), which cannot encode em-dashes. Python then
-# tries to decode the file as UTF-8 when importing it (PEP 3120), fails,
-# and the sandbox aborts with:
-#
-# SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0x97
-# in position N: invalid start byte
-#
-# This was the *second* Windows-specific bug (WinError 10106 was the first).
-# The fix is to always pass ``encoding="utf-8"`` when writing Python source.
-
-
-class TestSandboxWritesUtf8:
- """Verify the file-write call sites use UTF-8 explicitly, not the
- platform default. We check the source of ``execute_code`` rather
- than spawning a real sandbox because the latter needs a full agent
- context — but the code inspection is deterministic and fast."""
-
- def test_stub_and_script_writes_specify_utf8(self):
- """Both ``hermes_tools.py`` and ``script.py`` writes in
- ``_execute_local`` must pass ``encoding="utf-8"``."""
- import tools.code_execution_tool as cet
- src = open(cet.__file__, encoding="utf-8").read()
-
- # There should be no ``open(path, "w")`` without encoding= for
- # the two staging files. Grep-style check: find every write of
- # a .py file inside tmpdir and assert the line also contains
- # ``encoding="utf-8"`` within a short window.
- import re
- pattern = re.compile(
- r'open\(\s*os\.path\.join\(\s*tmpdir\s*,\s*"[^"]+\.py"\s*\)\s*,\s*"w"[^)]*\)'
- )
- for match in pattern.finditer(src):
- line = match.group(0)
- assert 'encoding="utf-8"' in line or "encoding='utf-8'" in line, (
- f"Sandbox file write missing encoding=\"utf-8\" on Windows: {line!r}"
- )
-
-
- def test_stub_source_roundtrips_through_utf8(self):
- """Concrete regression: write the generated stub to a temp file
- using ``encoding="utf-8"``, then parse it. This is what the
- sandbox does, and it must succeed even when the stub contains
- em-dashes (which it does — check the transport-header docstring).
- """
- from tools.code_execution_tool import generate_hermes_tools_module
- import tempfile, ast
- stub = generate_hermes_tools_module(
- ["terminal", "read_file", "write_file"], transport="uds"
- )
- # Sanity: stub actually contains a non-ASCII character, otherwise
- # this test wouldn't prove anything meaningful.
- non_ascii = [c for c in stub if ord(c) > 127]
- assert non_ascii, (
- "Generated stub is pure ASCII — test is meaningless. If the "
- "stub's docstrings have lost their em-dashes, update this "
- "assertion, but be aware the original regression is no longer "
- "covered."
- )
-
- with tempfile.NamedTemporaryFile(
- mode="w", suffix=".py", delete=False, encoding="utf-8"
- ) as f:
- f.write(stub)
- tmp_path = f.name
-
- try:
- # Re-read and parse exactly like the child Python would.
- with open(tmp_path, encoding="utf-8") as fh:
- round_tripped = fh.read()
- assert round_tripped == stub, "UTF-8 round-trip corrupted the stub"
- ast.parse(round_tripped) # must not raise SyntaxError
- finally:
- os.unlink(tmp_path)
-
+class TestNativeLegacyEncodingControls:
@pytest.mark.platforms("windows")
def test_windows_default_encoding_would_have_failed(self):
"""Negative control: prove that on Windows, writing the stub
@@ -535,85 +140,6 @@ class TestSandboxWritesUtf8:
finally:
os.unlink(tmp_path)
-
-# ---------------------------------------------------------------------------
-# UTF-8 stdio regression test
-# ---------------------------------------------------------------------------
-#
-# The third Windows-specific sandbox bug: after the UTF-8 file-write fix
-# let the child import hermes_tools, a user script that printed non-ASCII
-# to stdout still crashed with:
-#
-# UnicodeEncodeError: 'charmap' codec can't encode character '\u2192'
-# in position N: character maps to <undefined>
-#
-# Python's sys.stdout on Windows is bound to the console code page
-# (cp1252 on US-locale installs) when the process is attached to a pipe
-# without PYTHONIOENCODING set. LLM-generated scripts routinely print
-# em-dashes, arrows, accented chars, emoji — all of which break.
-#
-# Fix: spawn the child with PYTHONIOENCODING=utf-8 and PYTHONUTF8=1.
-# The latter also makes open()'s default encoding UTF-8 (PEP 540),
-# belt-and-suspenders for user scripts that do their own file I/O.
-
-
-class TestChildStdioIsUtf8:
- """Verify the sandbox child is spawned with UTF-8 stdio encoding,
- so LLM scripts can print non-ASCII without crashing on Windows."""
-
- def test_popen_env_sets_pythonioencoding_utf8(self):
- """Source-level check: the child env builder must set
- PYTHONIOENCODING=utf-8 in child_env."""
- import tools.code_execution_env as cee
- src = open(cee.__file__, encoding="utf-8").read()
- assert 'child_env["PYTHONIOENCODING"] = "utf-8"' in src, (
- "PYTHONIOENCODING=utf-8 missing from child env — Windows "
- "scripts that print non-ASCII will crash with "
- "UnicodeEncodeError."
- )
-
-
- def test_live_child_can_print_non_ascii(self):
- """Live regression: spawn a Python child with the same env
- treatment the sandbox uses (PYTHONIOENCODING=utf-8 + PYTHONUTF8=1)
- and verify it can print em-dashes, arrows, and emoji to stdout
- without crashing. This is the exact scenario that broke in live
- usage.
-
- Runs on every OS — on POSIX the fix is belt-and-suspenders but
- still load-bearing for C.ASCII locale environments.
- """
- script = textwrap.dedent("""
- import sys
- # Mix of chars that cp1252 can't encode: arrow, emoji.
- print("em-dash \\u2014 arrow \\u2192 emoji \\U0001f680")
- sys.exit(0)
- """).strip()
-
- # Build a scrubbed env the same way the sandbox does, then apply
- # the stdio overrides.
- scrubbed = _scrub_child_env(os.environ, is_passthrough=_no_passthrough)
- scrubbed["PYTHONIOENCODING"] = "utf-8"
- scrubbed["PYTHONUTF8"] = "1"
-
- result = subprocess.run(
- [sys.executable, "-c", script],
- env=scrubbed,
- capture_output=True,
- timeout=15,
- # Don't decode at the subprocess boundary — we want to check
- # the raw bytes match UTF-8, same as what the sandbox does.
- )
- assert result.returncode == 0, (
- f"Child crashed printing non-ASCII:\n"
- f" stdout (raw): {result.stdout!r}\n"
- f" stderr (raw): {result.stderr!r}"
- )
- decoded = result.stdout.decode("utf-8")
- assert "\u2014" in decoded, f"em-dash missing from output: {decoded!r}"
- assert "\u2192" in decoded, f"arrow missing from output: {decoded!r}"
- assert "\U0001f680" in decoded, f"emoji missing from output: {decoded!r}"
-
@pytest.mark.platforms("windows")
def test_windows_child_without_utf8_env_would_fail(self):
"""Negative control: spawn a Python child *without* our env
diff --git a/tests/tools/test_execute_code_approval_cluster.py b/tests/tools/test_execute_code_approval_cluster.py
index a14a807aac4..e743aa18da7 100644
--- a/tests/tools/test_execute_code_approval_cluster.py
+++ b/tests/tools/test_execute_code_approval_cluster.py
@@ -5,7 +5,7 @@ Covers the canonical fix for issues #4146, #27303, #30882, #33057:
1. tools.thread_context.propagate_context_to_thread — propagates the agent
turn's ContextVars AND thread-local approval/sudo callbacks into worker
threads, and clears the callbacks on teardown.
- 2. Both execute_code RPC threads are wrapped with that helper (source guard).
+ 2. Local and remote file-RPC carry the cell's authority in real processes.
3. tools.approval.check_execute_code_guard — the entry-point guard decision
matrix (isolated backends, yolo/off, cron-deny, headless-local,
gateway approve/deny/timeout/missing-notify, smart mode).
@@ -25,10 +25,10 @@ import pytest
from tools import approval as A
import tools.approval_detection as approval_detection
from tools import approval_context
-from tools import approval_context
from tools import approval_smart
from tools.thread_context import propagate_context_to_thread
from gateway.session_context import clear_session_vars, reset_session_vars, set_session_vars
+from tests.tools._child_env_fixtures import child_env # noqa: F401
# ---------------------------------------------------------------------------
@@ -87,26 +87,51 @@ def test_helper_clears_callbacks_on_teardown():
TT.set_approval_callback(None)
-def test_both_rpc_threads_use_propagation_helper():
- """Source guard: every execute_code RPC serving thread must carry the
- cell's approval context, or the gateway approval bypass (#33057) silently
- returns. The remote poll thread wraps its target with
- propagate_context_to_thread; the local session kernel instead rebinds
- authority per cell (``dispatch=`` passed to ``_rpc_server_loop``)."""
- import inspect
- import tools.code_execution_tool as cet
- import tools.code_kernel as ck
-
- src = inspect.getsource(cet)
- assert "propagate_context_to_thread(_rpc_poll_loop)" in src, (
- "remote file-RPC poll thread is not wrapped with "
- "propagate_context_to_thread — gateway approval routing will be lost."
- )
- kernel_src = inspect.getsource(ck)
- assert "_rpc_server_loop(" in kernel_src and "dispatch=" in kernel_src, (
- "local session-kernel RPC server thread must pass a per-cell "
- "dispatch= to _rpc_server_loop — gateway approval routing will be lost."
- )
[email protected]("transport", ["local", "remote-file"])
+def test_rpc_carries_authority_to_real_dispatch(child_env, monkeypatch, transport):
+ import time
+ import model_tools
+ from tests.tools._child_env_fixtures import RunToCompletionEnv, run_code
+ from tools import terminal_tool
+ from tools.code_execution_tool import _run_remote_per_call
+
+ witness = child_env / "authority.txt"
+
+ marker = contextvars.ContextVar("rpc-authority", default="missing")
+ seen = []
+ original = model_tools.handle_function_call
+
+ def dispatch(name, args, *pos, **kwargs):
+ seen.append((marker.get(), terminal_tool._get_approval_callback()))
+ return original(name, args, *pos, **kwargs)
+
+ monkeypatch.setattr(model_tools, "handle_function_call", dispatch)
+ code = f"from hermes_tools import read_file\nimport json\nprint(json.dumps(read_file({str(witness)!r})))"
+ try:
+ for turn in ("first", "second"):
+ witness.write_text(f"real RPC payload {turn}\n", encoding="utf-8")
+ callback = object()
+ token = marker.set(turn)
+ terminal_tool.set_approval_callback(callback)
+ try:
+ if transport == "local":
+ result = run_code(code, reset=(turn == "first"))
+ else:
+ raw = json.loads(_run_remote_per_call(
+ RunToCompletionEnv(child_env), "ssh", code, "authority-test",
+ frozenset({"read_file"}), timeout=30, max_tool_calls=2, exec_start=time.monotonic()))
+ assert raw["status"] == "success", raw
+ assert raw["tool_calls_made"] == 1
+ result = json.loads(raw["output"])
+ assert "content" in result, result
+ assert f"real RPC payload {turn}" in result["content"]
+ assert seen[-1] == (turn, callback)
+ finally:
+ marker.reset(token)
+ finally:
+ terminal_tool.set_approval_callback(None)
+ assert len(seen) == 2
# ---------------------------------------------------------------------------
diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.py
index 29d31af9a3a..f7e83b9a7d3 100644
--- a/tests/tools/test_local_env_blocklist.py
+++ b/tests/tools/test_local_env_blocklist.py
@@ -1,602 +1,346 @@
-"""Tests for subprocess env sanitization in LocalEnvironment.
-
-Verifies that Hermes-managed provider, tool, and gateway env vars are
-stripped from subprocess environments so external CLIs are not silently
-misrouted or handed Hermes secrets.
-
-See: https://github.com/NousResearch/hermes-agent/issues/1002
-See: https://github.com/NousResearch/hermes-agent/issues/1264
-"""
+"""Child-observed terminal policy, profile lifetime and PYTHONPATH provenance."""
+import json
import os
import subprocess
import sys
-import tempfile
from pathlib import Path
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
import pytest
-from tools.environments.local import LocalEnvironment
-from tools.environments.local_env_policy import (
- _HERMES_PROVIDER_ENV_BLOCKLIST,
- _HERMES_PROVIDER_ENV_FORCE_PREFIX,
-)
-
-
-def _running_venv_site_packages() -> Path:
- """Independently construct the host-native venv site-packages path."""
- if sys.platform == "win32":
- return Path(sys.prefix) / "Lib" / "site-packages"
- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"
- return Path(sys.prefix) / "lib" / pyver / "site-packages"
-
-
-def _make_fake_popen(captured: dict):
- """Return a fake Popen constructor that records the env kwarg."""
- def fake_popen(cmd, **kwargs):
- captured["env"] = kwargs.get("env", {})
- proc = MagicMock()
- proc.poll.return_value = 0
- proc.returncode = 0
- proc.stdout = MagicMock(__iter__=lambda s: iter([]), __next__=lambda s: (_ for _ in ()).throw(StopIteration))
- proc.stdin = MagicMock()
- return proc
- return fake_popen
-
-
-def _run_with_env(extra_os_env=None, self_env=None):
- """Execute a command via LocalEnvironment with mocked Popen
- and return the env dict passed to the subprocess."""
- captured = {}
- test_environ = {
- **os.environ,
- "PATH": os.environ.get("PATH", ""),
- "HOME": "/home/user",
- "USER": "testuser",
+from tests.tools._child_env_fixtures import child_env, observe_child, observe_terminal # noqa: F401
+from tools.environments import local
+from tools.environments import local_pythonpath as pp
+
+
+# Expectations come from independent provider/config declarations and literal
+# policy examples, never the finished blocklist or a test-owned scrubber.
+STATIC_BLOCKED = """
+OPENAI_BASE_URL OPENAI_API_KEY OPENAI_API_BASE OPENAI_ORG_ID OPENAI_ORGANIZATION
+OPENROUTER_API_KEY ANTHROPIC_BASE_URL ANTHROPIC_API_KEY ANTHROPIC_TOKEN LLM_MODEL
+VERTEX_CREDENTIALS_PATH GOOGLE_APPLICATION_CREDENTIALS AWS_BEARER_TOKEN_BEDROCK
+GOOGLE_API_KEY DEEPSEEK_API_KEY MISTRAL_API_KEY GROQ_API_KEY TOGETHER_API_KEY
+PERPLEXITY_API_KEY COHERE_API_KEY FIREWORKS_API_KEY XAI_API_KEY HELICONE_API_KEY
+TELEGRAM_HOME_CHANNEL TELEGRAM_HOME_CHANNEL_NAME DISCORD_HOME_CHANNEL
+DISCORD_HOME_CHANNEL_NAME DISCORD_REQUIRE_MENTION DISCORD_FREE_RESPONSE_CHANNELS
+DISCORD_AUTO_THREAD SLACK_HOME_CHANNEL SLACK_HOME_CHANNEL_NAME SLACK_ALLOWED_USERS
+WHATSAPP_ENABLED WHATSAPP_MODE WHATSAPP_ALLOWED_USERS SIGNAL_HTTP_URL SIGNAL_ACCOUNT
+SIGNAL_ALLOWED_USERS SIGNAL_GROUP_ALLOWED_USERS SIGNAL_HOME_CHANNEL SIGNAL_HOME_CHANNEL_NAME
+SIGNAL_IGNORE_STORIES HASS_TOKEN HASS_URL EMAIL_ADDRESS EMAIL_PASSWORD EMAIL_IMAP_HOST
+EMAIL_SMTP_HOST EMAIL_HOME_ADDRESS EMAIL_HOME_ADDRESS_NAME HERMES_DASHBOARD_SESSION_TOKEN
+GATEWAY_ALLOWED_USERS GATEWAY_ALLOW_ALL_USERS GH_TOKEN GITHUB_APP_ID
+GITHUB_APP_PRIVATE_KEY_PATH GITHUB_APP_INSTALLATION_ID MODAL_TOKEN_ID MODAL_TOKEN_SECRET
+DAYTONA_API_KEY VERCEL_OIDC_TOKEN VERCEL_TOKEN VERCEL_PROJECT_ID VERCEL_TEAM_ID GATEWAY_RELAY_ID
+AUXILIARY_VISION_API_KEY AUXILIARY_WEB_EXTRACT_API_KEY AUXILIARY_APPROVAL_API_KEY
+AUXILIARY_MY_PLUGIN_TASK_API_KEY AUXILIARY_VISION_BASE_URL AUXILIARY_COMPRESSION_BASE_URL
+GATEWAY_RELAY_SECRET GATEWAY_RELAY_DELIVERY_KEY GATEWAY_RELAY_SESSION_TOKEN
+""".split()
+OPERATOR_ALLOWED = """
+AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE AWS_DEFAULT_REGION
+AWS_REGION AWS_SHARED_CREDENTIALS_FILE AWS_CONFIG_FILE AWS_WEB_IDENTITY_TOKEN_FILE AWS_ROLE_ARN
+CLAUDE_CODE_OAUTH_TOKEN AUXILIARY_VISION_PROVIDER AUXILIARY_VISION_MODEL GATEWAY_RELAY_URL
+GATEWAY_RELAY_PLATFORMS MY_APP_KEY MY_CUSTOM_VAR
+""".split()
+
+
+def _running_site():
+ return Path(sys.prefix) / ("Lib/site-packages" if os.name == "nt" else
+ f"lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages")
+
+
+def test_terminal_child_observes_declared_policy(child_env, monkeypatch):
+ from hermes_cli.auth import PROVIDER_REGISTRY
+ from hermes_cli.config import OPTIONAL_ENV_VARS
+ blocked = set(STATIC_BLOCKED)
+ for config in PROVIDER_REGISTRY.values():
+ blocked.update(config.api_key_env_vars)
+ if config.base_url_env_var:
+ blocked.add(config.base_url_env_var)
+ blocked.update(name for name, meta in OPTIONAL_ENV_VARS.items()
+ if meta.get("category") in {"tool", "messaging"}
+ or (meta.get("category") == "setting" and meta.get("password")))
+ blocked.discard("CLAUDE_CODE_OAUTH_TOKEN") # operator's subscription, not Hermes inference
+ for name in blocked | set(OPERATOR_ALLOWED):
+ monkeypatch.setenv(name, "fake-" + name)
+ before = dict(os.environ)
+ env = local.LocalEnvironment(cwd=str(child_env), timeout=30,
+ env={"OPENAI_BASE_URL": "fake-override", "MY_CUSTOM_VAR": "caller-value"})
+ try:
+ observed = observe_terminal(env, sorted(blocked | set(OPERATOR_ALLOWED)))
+ finally:
+ env.cleanup()
+ assert observed == {**dict.fromkeys(blocked), **{k: "fake-" + k for k in OPERATOR_ALLOWED},
+ "MY_CUSTOM_VAR": "caller-value"}
+ assert dict(os.environ) == before
+
+
[email protected]("builder", ["foreground", "background", "factory", "nonterminal"])
+def test_builders_strip_runtime_markers_and_owned_paths(child_env, monkeypatch, builder):
+ repo, site = Path(__file__).resolve().parents[2], _running_site()
+ user_path = str(child_env / "user-lib")
+ for k, v in {"VIRTUAL_ENV": "/unrelated/venv", "CONDA_PREFIX": "/unrelated/conda",
+ "PYTHONHOME": "/nonexistent/python-home",
+ "PYTHONPATH": os.pathsep.join([str(repo), str(site), user_path])}.items():
+ monkeypatch.setenv(k, v)
+ factories = {
+ "foreground": lambda: local._make_run_env({}),
+ "background": lambda: local._sanitize_subprocess_env(dict(os.environ), {"VIRTUAL_ENV": "/extra/venv"}),
+ "factory": local.build_subprocess_env,
+ "nonterminal": local.hermes_subprocess_env,
}
- if extra_os_env:
- test_environ.update(extra_os_env)
-
- env = LocalEnvironment(cwd=tempfile.gettempdir(), timeout=10, env=self_env)
-
- with patch("tools.environments.local._find_bash", return_value="/bin/bash"), \
- patch("subprocess.Popen", side_effect=_make_fake_popen(captured)), \
- patch.dict(os.environ, test_environ, clear=True):
- env.execute("echo hello")
-
- return captured.get("env", {})
-
-
-class TestProviderEnvBlocklist:
- """Provider env vars loaded from ~/.hermes/.env must not leak."""
-
- def test_blocked_vars_are_stripped(self):
- """OPENAI_BASE_URL and other provider vars must not appear in subprocess env."""
- leaked_vars = {
- "OPENAI_BASE_URL": "http://localhost:8000/v1",
- "OPENAI_API_KEY": "sk-fake-key",
- "OPENROUTER_API_KEY": "or-fake-key",
- "ANTHROPIC_API_KEY": "ant-fake-key",
- "LLM_MODEL": "anthropic/claude-opus-4-6",
- }
- result_env = _run_with_env(extra_os_env=leaked_vars)
-
- for var in leaked_vars:
- assert var not in result_env, f"{var} leaked into subprocess env"
-
- def test_registry_derived_vars_are_stripped(self):
- """Vars from the provider registry (ANTHROPIC_TOKEN, ZAI_API_KEY, etc.)
- must also be blocked — not just the hand-written extras."""
- registry_vars = {
- "ANTHROPIC_TOKEN": "ant-tok",
- "ZAI_API_KEY": "zai-key",
- "Z_AI_API_KEY": "z-ai-key",
- "GLM_API_KEY": "glm-key",
- "KIMI_API_KEY": "kimi-key",
- "MINIMAX_API_KEY": "mm-key",
- "MINIMAX_CN_API_KEY": "mmcn-key",
- "DEEPSEEK_API_KEY": "deepseek-key",
- "NVIDIA_API_KEY": "nvidia-key",
- }
- result_env = _run_with_env(extra_os_env=registry_vars)
-
- for var in registry_vars:
- assert var not in result_env, f"{var} leaked into subprocess env"
-
- def test_bedrock_bearer_token_is_stripped(self):
- """The Bedrock-specific bearer token is a Hermes inference secret
- (analogous to OPENAI_API_KEY) and must not leak into subprocesses.
-
- Regression for #32314: AWS_BEARER_TOKEN_BEDROCK leaked into terminal /
- execute_code children because the ``bedrock`` ProviderConfig declares
- ``api_key_env_vars=()`` (auth_type="aws_sdk") and the blocklist builder
- only consulted that field. The reporter caught it when ``opencode
- models`` run inside a Hermes terminal enumerated the entire Bedrock
- catalog off the leaked bearer token.
- """
- result_env = _run_with_env(extra_os_env={
- "AWS_BEARER_TOKEN_BEDROCK": "bedrock-bearer-secret",
- })
-
- assert "AWS_BEARER_TOKEN_BEDROCK" not in result_env, (
- "AWS_BEARER_TOKEN_BEDROCK leaked into subprocess env (see #32314)"
- )
-
- def test_vertex_credentials_path_is_stripped(self):
- """The Vertex AI service-account JSON path must not leak into
- subprocesses, even though it is filesystem path metadata rather
- than a bare API key.
-
- Regression: ``vertex`` authenticates via OAuth2 (service-account
- JSON / ADC), not PROVIDER_REGISTRY, and OPTIONAL_ENV_VARS marks
- VERTEX_CREDENTIALS_PATH as ``password=False`` (it's a path, not a
- secret string) with ``category="provider"`` — a category the
- registry-derived loop above never checks — so it fell through both
- blocklist sources. GOOGLE_APPLICATION_CREDENTIALS (the ADC fallback
- the adapter also reads) had the same gap. A leaked path discloses
- the on-disk location of a GCP service-account key to every spawned
- subprocess (terminal, codex/copilot app-server, browser workers).
- """
- result_env = _run_with_env(extra_os_env={
- "VERTEX_CREDENTIALS_PATH": "/home/user/.config/gcloud/sa-key.json",
- "GOOGLE_APPLICATION_CREDENTIALS": "/home/user/.config/gcloud/adc.json",
- })
-
- assert "VERTEX_CREDENTIALS_PATH" not in result_env
- assert "GOOGLE_APPLICATION_CREDENTIALS" not in result_env
-
- def test_general_aws_credential_chain_is_preserved(self):
- """The GENERAL AWS credential chain must STILL pass through to
- subprocesses — this is the no-regression guard for #32314.
-
- Per SECURITY.md §3.2 the local terminal is the user's trusted operator
- shell. A user running ``aws``/``terraform``/``cdk``/``boto3`` in the
- agent terminal must keep the same AWS access their own shell has.
- Stripping these would (a) break every user who does AWS work in the
- agent terminal — not just Bedrock users, since the registry is iterated
- unconditionally — and (b) be unrecoverable, because env_passthrough.py
- refuses to re-allow anything in _HERMES_PROVIDER_ENV_BLOCKLIST
- (GHSA-rhgp-j443-p4rf). Only the Bedrock inference bearer token is
- Hermes-managed; the rest belongs to the user.
- """
- general_chain = {
- "AWS_ACCESS_KEY_ID": "AKIAIOSFODNN7EXAMPLE",
- "AWS_SECRET_ACCESS_KEY": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
- "AWS_SESSION_TOKEN": "session-token",
- "AWS_PROFILE": "production",
- "AWS_DEFAULT_REGION": "us-east-1",
- "AWS_REGION": "us-east-1",
- "AWS_SHARED_CREDENTIALS_FILE": "/home/user/.aws/credentials",
- "AWS_CONFIG_FILE": "/home/user/.aws/config",
- "AWS_WEB_IDENTITY_TOKEN_FILE": "/var/run/secrets/token",
- "AWS_ROLE_ARN": "arn:aws:iam::123456789012:role/example",
- }
- result_env = _run_with_env(extra_os_env=general_chain)
-
- for var, value in general_chain.items():
- assert result_env.get(var) == value, (
- f"{var} was stripped from subprocess env — this is a "
- f"capability regression (see #32314 discussion)"
- )
-
- def test_non_registry_provider_vars_are_stripped(self):
- """Extra provider vars not in PROVIDER_REGISTRY must also be blocked."""
- extra_provider_vars = {
- "GOOGLE_API_KEY": "google-key",
- "MISTRAL_API_KEY": "mistral-key",
- "GROQ_API_KEY": "groq-key",
- "TOGETHER_API_KEY": "together-key",
- "PERPLEXITY_API_KEY": "perplexity-key",
- "COHERE_API_KEY": "cohere-key",
- "FIREWORKS_API_KEY": "fireworks-key",
- "XAI_API_KEY": "xai-key",
- "HELICONE_API_KEY": "helicone-key",
- }
- result_env = _run_with_env(extra_os_env=extra_provider_vars)
-
- for var in extra_provider_vars:
- assert var not in result_env, f"{var} leaked into subprocess env"
-
- def test_tool_and_gateway_vars_are_stripped(self):
- """Tool and gateway secrets/config must not leak into subprocess env."""
- leaked_vars = {
- "TELEGRAM_BOT_TOKEN": "bot-token",
- "TELEGRAM_HOME_CHANNEL": "12345",
- "DISCORD_HOME_CHANNEL": "67890",
- "SLACK_APP_TOKEN": "xapp-secret",
- "WHATSAPP_ALLOWED_USERS": "+15555550123",
- "SIGNAL_ACCOUNT": "+15555550124",
- "HASS_TOKEN": "ha-secret",
- "EMAIL_PASSWORD": "email-secret",
- "FIRECRAWL_API_KEY": "fc-secret",
- "HERMES_DASHBOARD_SESSION_TOKEN": "dashboard-session-secret",
- "BROWSERBASE_PROJECT_ID": "bb-project",
- "ELEVENLABS_API_KEY": "el-secret",
- "GITHUB_TOKEN": "ghp_secret",
- "GH_TOKEN": "gh_alias_secret",
- "GATEWAY_ALLOW_ALL_USERS": "true",
- "GATEWAY_ALLOWED_USERS": "alice,bob",
- "MODAL_TOKEN_ID": "modal-id",
- "MODAL_TOKEN_SECRET": "modal-secret",
- "DAYTONA_API_KEY": "daytona-key",
- "VERCEL_OIDC_TOKEN": "vercel-oidc-token",
- "VERCEL_TOKEN": "vercel-token",
- "VERCEL_PROJECT_ID": "vercel-project",
- "VERCEL_TEAM_ID": "vercel-team",
- }
- result_env = _run_with_env(extra_os_env=leaked_vars)
-
- for var in leaked_vars:
- assert var not in result_env, f"{var} leaked into subprocess env"
-
- def test_safe_vars_are_preserved(self):
- """Standard env vars (PATH, HOME, USER) must still be passed through."""
- result_env = _run_with_env()
-
- assert "HOME" in result_env
- assert result_env["HOME"] == "/home/user"
- assert "USER" in result_env
- assert "PATH" in result_env
-
- def test_bare_hermes_resolves_from_sanitized_subprocess_path(self):
- """Cron children can resolve Hermes even when the gateway PATH cannot."""
- from tools.environments.local import _sanitize_subprocess_env
-
- with patch(
- "tools.environments.local._resolve_hermes_bin_dir",
- return_value="/home/user/.local/bin",
- ):
- result = _sanitize_subprocess_env(
- {
- "PATH": os.pathsep.join(["/usr/bin", "/bin"]),
- "HOME": "/home/user",
- }
- )
-
- assert result["PATH"] == os.pathsep.join(
- ["/home/user/.local/bin", "/usr/bin", "/bin"]
- )
-
- def test_bare_hermes_path_does_not_duplicate_existing_install_dir(self):
- """The PATH repair is idempotent for already-correct environments."""
- from tools.environments.local import _sanitize_subprocess_env
-
- with patch(
- "tools.environments.local._resolve_hermes_bin_dir",
- return_value="/home/user/.local/bin",
- ):
- result = _sanitize_subprocess_env(
- {"PATH": os.pathsep.join(["/home/user/.local/bin", "/usr/bin"])}
- )
-
- assert result["PATH"] == os.pathsep.join(
- ["/home/user/.local/bin", "/usr/bin"]
- )
-
- def test_self_env_blocked_vars_also_stripped(self):
- """Blocked vars in self.env are stripped; non-blocked vars pass through."""
- result_env = _run_with_env(self_env={
- "OPENAI_BASE_URL": "http://custom:9999/v1",
- "MY_CUSTOM_VAR": "keep-this",
- })
-
- assert "OPENAI_BASE_URL" not in result_env
- assert "MY_CUSTOM_VAR" in result_env
- assert result_env["MY_CUSTOM_VAR"] == "keep-this"
-
-
-class TestTerminalFirstPartyPlatformEnv:
- """BUZZ_* first-party platform credentials must reach terminal children —
- but ONLY in a Buzz agent context.
-
- Issue #78026: Buzz platform agents could not use the ``buzz`` CLI from the
- terminal tool because BUZZ_PRIVATE_KEY / BUZZ_AUTH_TAG / BUZZ_RELAY_URL
- (and the other BUZZ_* vars) are stripped by _HERMES_PROVIDER_ENV_BLOCKLIST
- and env_passthrough refuses to re-allow them (GHSA-rhgp-j443-p4rf).
-
- The carve-out is TERMINAL-ONLY and CONTEXT-GATED: it applies when the
- process is a Buzz-ACP managed agent (BUZZ_MANAGED_AGENT set by the
- buzz-acp harness, #76243) or the live session's platform is ``buzz``.
- Foreground (_make_run_env) and background/PTY (_sanitize_subprocess_env)
- children then get the BUZZ_* vars; execute_code, hermes_subprocess_env,
- docker, and env_passthrough registration stay sealed, and non-Buzz
- sessions/processes keep stripping the vars. The blocklist itself is NOT
- modified.
- """
-
- def test_make_run_env_preserves_buzz_vars(self):
- """Foreground terminal children get the BUZZ_* credentials when the
- process is a Buzz-managed agent (BUZZ_MANAGED_AGENT set)."""
- from tools.environments.local import _make_run_env
-
- buzz_vars = {
- "BUZZ_PRIVATE_KEY": "nsec1faketestkey",
- "BUZZ_AUTH_TAG": '["tag","data","kind","sig"]',
- "BUZZ_RELAY_URL": "https://mycommunity.communities.buzz.xyz",
- }
- with patch.dict(
- os.environ,
- {**buzz_vars, "BUZZ_MANAGED_AGENT": "1", "PATH": "/usr/bin:/bin"},
- clear=True,
- ):
- run_env = _make_run_env({})
-
- for var, value in buzz_vars.items():
- assert run_env.get(var) == value, (
- f"{var} missing from foreground terminal env (issue #78026)"
- )
-
- def test_sanitize_subprocess_env_preserves_buzz_vars(self, monkeypatch):
- """Background/PTY terminal children get the BUZZ_* credentials when
- the process is a Buzz-managed agent."""
- from tools.environments.local import _sanitize_subprocess_env
-
- monkeypatch.setenv("BUZZ_MANAGED_AGENT", "1")
- buzz_vars = {
- "BUZZ_PRIVATE_KEY": "nsec1faketestkey",
- "BUZZ_AUTH_TAG": '["tag","data","kind","sig"]',
- "BUZZ_RELAY_URL": "https://mycommunity.communities.buzz.xyz",
- }
- result = _sanitize_subprocess_env({**buzz_vars, "HOME": "/home/user"})
-
- for var, value in buzz_vars.items():
- assert result.get(var) == value, (
- f"{var} missing from background/PTY terminal env (issue #78026)"
- )
-
- def test_buzz_vars_stripped_without_buzz_context(self, monkeypatch):
- """NEGATIVE gate: with no Buzz context signal (no BUZZ_MANAGED_AGENT,
- session platform not buzz), the BUZZ_* credentials stay stripped from
- BOTH terminal scrub paths — a Telegram/CLI/cron session on a host that
- also runs a Buzz gateway must not see BUZZ_PRIVATE_KEY."""
- from gateway.session_context import _SESSION_PLATFORM
- from tools.environments.local import _make_run_env, _sanitize_subprocess_env
-
- monkeypatch.delenv("BUZZ_MANAGED_AGENT", raising=False)
- monkeypatch.delenv("HERMES_SESSION_PLATFORM", raising=False)
- buzz_vars = {
- "BUZZ_PRIVATE_KEY": "nsec1faketestkey",
- "BUZZ_AUTH_TAG": '["tag","data","kind","sig"]',
- "BUZZ_RELAY_URL": "https://mycommunity.communities.buzz.xyz",
- }
- for var, value in buzz_vars.items():
- monkeypatch.setenv(var, value)
- # Bind a non-buzz session platform (ContextVar-authoritative).
- token = _SESSION_PLATFORM.set("telegram")
- try:
- run_env = _make_run_env({})
- sanitized = _sanitize_subprocess_env({**buzz_vars, "HOME": "/home/user"})
- finally:
- _SESSION_PLATFORM.reset(token)
-
- for var in buzz_vars:
- assert var not in run_env, f"{var} leaked into non-Buzz foreground env"
- assert var not in sanitized, f"{var} leaked into non-Buzz background env"
-
- def test_session_platform_buzz_enables_carveout(self, monkeypatch):
- """A live gateway session whose platform is ``buzz`` gets the
- carve-out even without BUZZ_MANAGED_AGENT (native buzz gateway
- plugin path), via the concurrency-safe session ContextVar."""
- from gateway.session_context import _SESSION_PLATFORM
- from tools.environments.local import _make_run_env, _sanitize_subprocess_env
-
- monkeypatch.delenv("BUZZ_MANAGED_AGENT", raising=False)
- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec1faketestkey")
- token = _SESSION_PLATFORM.set("buzz")
- try:
- run_env = _make_run_env({})
- sanitized = _sanitize_subprocess_env(
- {"BUZZ_PRIVATE_KEY": "nsec1faketestkey", "HOME": "/home/user"}
- )
- finally:
- _SESSION_PLATFORM.reset(token)
-
- assert run_env.get("BUZZ_PRIVATE_KEY") == "nsec1faketestkey"
- assert sanitized.get("BUZZ_PRIVATE_KEY") == "nsec1faketestkey"
-
- def test_buzz_vars_stay_in_blocklist(self):
- """The carve-out is a scrub-path exemption, NOT a blocklist removal —
- BUZZ_* must remain blocked for every non-terminal surface (execute_code,
- hermes_subprocess_env, env_passthrough registration)."""
- assert {"BUZZ_PRIVATE_KEY", "BUZZ_AUTH_TAG", "BUZZ_RELAY_URL"} <= \
- _HERMES_PROVIDER_ENV_BLOCKLIST
-
- def test_buzz_vars_use_plain_value_under_multiplex_without_scope(self, monkeypatch):
- """First-party platform vars are the process's own env values: with
- multiplex active and NO profile secret scope installed, the terminal
- scrub paths must forward the plain env value — NOT raise
- UnscopedSecretError (the fail-closed regression where the webhook-
- filter script runner crashed instead of running without the var)."""
- from agent import secret_scope as ss
- from tools.environments.local import _make_run_env, _sanitize_subprocess_env
-
- monkeypatch.setenv("BUZZ_MANAGED_AGENT", "1")
- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec-plain-value")
- monkeypatch.setenv("PATH", "/usr/bin:/bin")
- ss.set_multiplex_active(True)
- try:
- run_env = _make_run_env({})
- sanitized = _sanitize_subprocess_env(
- {"BUZZ_PRIVATE_KEY": "nsec-plain-value", "HOME": "/home/user"}
- )
- finally:
- ss.set_multiplex_active(False)
-
- assert run_env["BUZZ_PRIVATE_KEY"] == "nsec-plain-value"
- assert sanitized["BUZZ_PRIVATE_KEY"] == "nsec-plain-value"
-
- def test_buzz_vars_are_not_scope_resolved(self, monkeypatch):
- """First-party matches bypass the profile secret scope: a scope value
- for BUZZ_PRIVATE_KEY must NOT override the process env value — only
- skill/config passthrough names are scope-resolved."""
- from agent import secret_scope as ss
- from tools.environments.local import _make_run_env, _sanitize_subprocess_env
-
+ before = dict(os.environ)
+ actual = observe_child(factories[builder](), ["VIRTUAL_ENV", "CONDA_PREFIX", "PYTHONHOME", "PYTHONPATH", "HOME"])
+ assert actual == {"VIRTUAL_ENV": None, "CONDA_PREFIX": None, "PYTHONHOME": None,
+ "PYTHONPATH": user_path, "HOME": str(child_env)}
+ assert dict(os.environ) == before
+
+
[email protected]("builder,base_force,extra_force", [
+ ("foreground", "base-forced", "extra-forced"),
+ ("background", None, "extra-forced"),
+ ("factory", None, "extra-forced"),
+ ("nonterminal", None, None),
+])
+def test_force_prefix_is_not_plugin_passthrough(child_env, monkeypatch, builder, base_force, extra_force):
+ from tools.env_passthrough import register_env_passthrough, is_env_passthrough
+ register_env_passthrough(["OPENAI_API_KEY", "AUXILIARY_VISION_API_KEY", "SERVICE_TOKEN"])
+ assert not is_env_passthrough("OPENAI_API_KEY")
+ assert not is_env_passthrough("AUXILIARY_VISION_API_KEY")
+ assert is_env_passthrough("SERVICE_TOKEN")
+ monkeypatch.setenv("OPENAI_API_KEY", "fake-parent")
+ monkeypatch.setenv("_HERMES_FORCE_OPENAI_API_KEY", "base-forced")
+ extra = {"_HERMES_FORCE_OPENAI_BASE_URL": "extra-forced",
+ "_HERMES_FORCE_AUXILIARY_VISION_API_KEY": "never-forward",
+ "AUXILIARY_VISION_API_KEY": "never-forward", "MY_CUSTOM_VAR": "caller-value"}
+ factories = {
+ "foreground": lambda: local._make_run_env(extra),
+ "background": lambda: local._sanitize_subprocess_env(dict(os.environ), extra),
+ "factory": lambda: local.build_subprocess_env(extra=extra),
+ "nonterminal": lambda: local.hermes_subprocess_env(base_env={**os.environ, **extra}),
+ }
+ result = factories[builder]()
+ assert result.get("OPENAI_API_KEY") == base_force
+ assert result.get("OPENAI_BASE_URL") == extra_force
+ assert result["MY_CUSTOM_VAR"] == "caller-value"
+ assert "AUXILIARY_VISION_API_KEY" not in result
+ assert not any(k.startswith("_HERMES_FORCE_") for k in result)
+ # Even a buggy plugin hook cannot bypass dynamic-secret exclusion.
+ with patch("tools.env_passthrough.is_env_passthrough", return_value=True):
+ assert "AUXILIARY_VISION_API_KEY" not in factories[builder]()
+
+
[email protected]("managed,platform,allowed", [(True, "telegram", True), (False, "buzz", True), (False, "telegram", False)])
[email protected]("scope", [None, {"BUZZ_PRIVATE_KEY": "fake-scoped"}])
+def test_buzz_context_and_plain_process_value(child_env, monkeypatch, managed, platform, allowed, scope):
+ from agent import secret_scope as ss
+ from gateway.session_context import _SESSION_PLATFORM
+ from tools.code_execution_env import _scrub_child_env
+ from tools.env_passthrough import register_env_passthrough, is_env_passthrough
+ buzz = {"BUZZ_PRIVATE_KEY": "fake-process", "BUZZ_AUTH_TAG": "fake-tag", "BUZZ_RELAY_URL": "fake-relay"}
+ for k, v in buzz.items():
+ monkeypatch.setenv(k, v)
+ if managed:
monkeypatch.setenv("BUZZ_MANAGED_AGENT", "1")
- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec-process-env")
- monkeypatch.setenv("PATH", "/usr/bin:/bin")
- ss.set_multiplex_active(True)
- token = ss.set_secret_scope({"BUZZ_PRIVATE_KEY": "nsec-scoped"})
- try:
- run_env = _make_run_env({})
- sanitized = _sanitize_subprocess_env(
- {"BUZZ_PRIVATE_KEY": "nsec-process-env", "HOME": "/home/user"}
- )
- finally:
- ss.reset_secret_scope(token)
- ss.set_multiplex_active(False)
-
- assert run_env["BUZZ_PRIVATE_KEY"] == "nsec-process-env"
- assert sanitized["BUZZ_PRIVATE_KEY"] == "nsec-process-env"
-
-
-class TestTerminalFirstPartySnapshotIsolation:
- """BUZZ_* first-party vars must not persist in the shared terminal
- snapshot — a cross-profile leak under a multiplexed gateway.
-
- The terminal login-shell snapshot (init_session ``export -p`` dump and the
- per-command re-dump) captures the child env, which now includes
- BUZZ_PRIVATE_KEY. The exclusion set is derived from get_all_passthrough()
- plus backend-specific additions — and BUZZ_* can never be in it, because
- env_passthrough refuses blocklisted names (GHSA-rhgp-j443-p4rf). Without
- an exclusion, profile A's BUZZ_PRIVATE_KEY lands in hermes-snap-<id>.sh
- and profile B's later command on the same collapsed LocalEnvironment
- sources it. Fix: LocalEnvironment treats first-party terminal env names
- like profile-scoped passthrough names — excluded from the dump and
- save/restored per command.
- """
-
- def test_snapshot_exclusion_set_includes_first_party_names(self, monkeypatch):
- """Under multiplex, BUZZ_* names present in the env are added to the
- snapshot exclusion set, so the dump excludes them and _wrap_command
- save/restores them per command."""
- from agent import secret_scope as ss
- from tools.environments.local import LocalEnvironment
-
- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec-profile-a")
- env = LocalEnvironment.__new__(LocalEnvironment)
- env.env = {}
- env._snapshot_passthrough_names = set()
- ss.set_multiplex_active(True)
- try:
- excluded = env._snapshot_excluded_passthrough_names()
- finally:
- ss.set_multiplex_active(False)
-
- assert "BUZZ_PRIVATE_KEY" in excluded
- # The set is monotonic for the environment lifetime: the name stays
- # excluded (and unset-guarded per command) even once it leaves the env.
+ platform_token = _SESSION_PLATFORM.set(platform)
+ ss.set_multiplex_active(True)
+ scope_token = ss.set_secret_scope(scope) if scope is not None else None
+ try:
+ register_env_passthrough(buzz)
+ assert not any(is_env_passthrough(k) for k in buzz)
+ for result in (local._make_run_env({}), local._sanitize_subprocess_env(dict(os.environ))):
+ assert {k: result.get(k) for k in buzz} == (buzz if allowed else dict.fromkeys(buzz))
+ for result in (local.hermes_subprocess_env(), _scrub_child_env(os.environ)):
+ assert not set(buzz) & result.keys()
+ finally:
+ if scope_token is not None:
+ ss.reset_secret_scope(scope_token)
+ ss.set_multiplex_active(False)
+ _SESSION_PLATFORM.reset(platform_token)
+
+
[email protected]("linux", "macos", "windows")
[email protected]("first_platform,first_value", [("buzz", "fake-profile-a"), ("telegram", None)], ids=["buzz", "other"])
+def test_buzz_secret_never_reaches_second_profile_via_snapshot(child_env, monkeypatch, first_platform, first_value):
+ from agent import secret_scope as ss
+ from gateway.session_context import _SESSION_PLATFORM
+ monkeypatch.setenv("BUZZ_PRIVATE_KEY", "fake-profile-a")
+ ss.set_multiplex_active(True)
+ platform = _SESSION_PLATFORM.set(first_platform)
+ env = None
+ try:
+ env = local.LocalEnvironment(cwd=str(child_env), timeout=30)
+ snap = Path(env._snapshot_path)
+ assert snap.exists()
+ assert "BUZZ_PRIVATE_KEY" not in snap.read_text(encoding="utf-8")
+ assert observe_terminal(env, ["BUZZ_PRIVATE_KEY"]) == {"BUZZ_PRIVATE_KEY": first_value}
+ assert "fake-profile-a" not in snap.read_text(encoding="utf-8")
+ monkeypatch.delenv("BUZZ_PRIVATE_KEY")
+ _SESSION_PLATFORM.reset(platform)
+ platform = _SESSION_PLATFORM.set("telegram")
+ assert observe_terminal(env, ["BUZZ_PRIVATE_KEY"]) == {"BUZZ_PRIVATE_KEY": None}
assert "BUZZ_PRIVATE_KEY" in env._snapshot_passthrough_names
-
- def test_buzz_secret_never_reaches_second_profile_via_snapshot(self, monkeypatch, tmp_path):
- """Multiplex regression, end-to-end with real bash: (a) the snapshot
- file never contains profile A's BUZZ_PRIVATE_KEY, and (b) profile B
- sharing the same LocalEnvironment does not see profile A's
- BUZZ_PRIVATE_KEY in its terminal env."""
- import shutil
- if not shutil.which("bash"):
- pytest.skip("bash required")
-
- from agent import secret_scope as ss
- from tools.environments.local import LocalEnvironment
-
- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec-profile-a")
- ss.set_multiplex_active(True)
- env = LocalEnvironment(cwd=str(tmp_path), timeout=30)
- try:
- # Profile A's command re-dumps the snapshot; the exclusion must
- # keep BUZZ_PRIVATE_KEY out of BOTH the initial dump and the
- # per-command re-dump.
- env.execute("true")
-
- snap = Path(env._snapshot_path)
- assert snap.exists()
- snap_text = snap.read_text(encoding="utf-8", errors="replace")
- assert "nsec-profile-a" not in snap_text
- assert "BUZZ_PRIVATE_KEY" not in snap_text
-
- # Profile B: no BUZZ_PRIVATE_KEY in its env, same LocalEnvironment
- # (same snapshot file). It must not see profile A's value.
- monkeypatch.delenv("BUZZ_PRIVATE_KEY")
- result = env.execute("printf '%s' \"${BUZZ_PRIVATE_KEY-unset}\"")
- assert "nsec-profile-a" not in result["output"]
- assert "unset" in result["output"]
- finally:
+ assert "BUZZ_PRIVATE_KEY" not in snap.read_text(encoding="utf-8")
+ finally:
+ if env is not None:
env.cleanup()
- ss.set_multiplex_active(False)
-
-
-class TestForceEnvOptIn:
- """Callers can opt in to passing a blocked var via _HERMES_FORCE_ prefix."""
-
- def test_force_prefix_passes_blocked_var(self):
- """_HERMES_FORCE_OPENAI_API_KEY in self.env should inject OPENAI_API_KEY."""
- result_env = _run_with_env(self_env={
- f"{_HERMES_PROVIDER_ENV_FORCE_PREFIX}OPENAI_API_KEY": "sk-explicit",
- })
-
- assert "OPENAI_API_KEY" in result_env
- assert result_env["OPENAI_API_KEY"] == "sk-explicit"
- # The force-prefixed key itself must not appear
- assert f"{_HERMES_PROVIDER_ENV_FORCE_PREFIX}OPENAI_API_KEY" not in result_env
-
- def test_force_prefix_overrides_os_environ_block(self):
- """Force-prefix in self.env wins even when os.environ has the blocked var."""
- result_env = _run_with_env(
- extra_os_env={"OPENAI_BASE_URL": "http://leaked/v1"},
- self_env={f"{_HERMES_PROVIDER_ENV_FORCE_PREFIX}OPENAI_BASE_URL": "http://intended/v1"},
- )
-
- assert result_env["OPENAI_BASE_URL"] == "http://intended/v1"
-
-
-class TestActiveVenvMarkerStripping:
- """Active-virtualenv markers must not leak into terminal subprocesses (#23473).
-
- The gateway runs inside its own venv, so its process environment carries
- VIRTUAL_ENV (and possibly CONDA_PREFIX). If those leak into commands the
- agent runs against ANOTHER Python project, ``uv``/``poetry`` treat the
- inherited value as the active environment and build that project's deps
- into the Hermes venv path instead of the project's own ``.venv`` —
- silently clobbering the Hermes environment (and, when the other project
- pins a different Python, breaking the gateway outright). The Hermes venv
- stays reachable via PATH, so stripping the markers is safe.
- """
-
- def test_virtualenv_marker_stripped_end_to_end(self):
- result_env = _run_with_env(extra_os_env={
- "VIRTUAL_ENV": "/home/user/.hermes/hermes-agent/venv",
- })
- assert "VIRTUAL_ENV" not in result_env
-
- def test_conda_prefix_marker_stripped_end_to_end(self):
- result_env = _run_with_env(extra_os_env={
- "CONDA_PREFIX": "/opt/conda/envs/hermes",
- })
- assert "CONDA_PREFIX" not in result_env
-
- def test_make_run_env_strips_markers(self):
- from tools.environments.local import _make_run_env
- poison = {"VIRTUAL_ENV": "/venv", "CONDA_PREFIX": "/conda", "PATH": "/usr/bin"}
- with patch.dict(os.environ, poison, clear=True):
- result = _make_run_env({})
- assert "VIRTUAL_ENV" not in result
- assert "CONDA_PREFIX" not in result
-
- def test_sanitize_subprocess_env_strips_markers(self):
- from tools.environments.local import _sanitize_subprocess_env
- base = {"VIRTUAL_ENV": "/venv", "CONDA_PREFIX": "/conda", "HOME": "/home/user"}
- # Even an explicitly-passed extra marker is stripped.
- result = _sanitize_subprocess_env(base, {"VIRTUAL_ENV": "/also/venv"})
- assert "VIRTUAL_ENV" not in result
- assert "CONDA_PREFIX" not in result
- assert result.get("HOME") == "/home/user"
-
- def test_markers_constant_contents(self):
- from tools.environments.local_env_policy import _ACTIVE_VENV_MARKER_VARS
- assert "VIRTUAL_ENV" in _ACTIVE_VENV_MARKER_VARS
- assert "CONDA_PREFIX" in _ACTIVE_VENV_MARKER_VARS
+ _SESSION_PLATFORM.reset(platform)
+ ss.set_multiplex_active(False)
+
+
[email protected]("scoped,expected", [({"SERVICE_TOKEN": "fake-routed"}, "fake-routed"), ({}, None)])
+def test_profile_passthrough_in_terminal_child(child_env, monkeypatch, scoped, expected):
+ from agent import secret_scope as ss
+ from tools.env_passthrough import register_env_passthrough
+ register_env_passthrough(["SERVICE_TOKEN"])
+ monkeypatch.setenv("SERVICE_TOKEN", "fake-default")
+ ss.set_multiplex_active(True)
+ token = ss.set_secret_scope(scoped)
+ env = None
+ try:
+ env = local.LocalEnvironment(cwd=str(child_env), timeout=30)
+ assert observe_terminal(env, ["SERVICE_TOKEN"]) == {"SERVICE_TOKEN": expected}
+ result = local._sanitize_subprocess_env(dict(os.environ))
+ assert result.get("SERVICE_TOKEN") == expected
+ finally:
+ if env is not None:
+ env.cleanup()
+ ss.reset_secret_scope(token)
+ ss.set_multiplex_active(False)
+
+
[email protected]("entries,expected", [
+ (["SITE", "/user/lib"], ["/user/lib"]),
+ (["REPO", "/user/lib"], ["/user/lib"]),
+ (["SITE", "/user/lib", "SITE", "/user/lib"], ["/user/lib", "/user/lib"]),
+ (["SITE", "REPO"], None),
+ (["/first", "REPO", "", "SITE", "/last"], ["/first", "", "/last"]),
+ ([" /opt/user-lib ", "relative/../lib", "", "/opt/user-lib", "/opt/user-lib"],
+ [" /opt/user-lib ", "relative/../lib", "", "/opt/user-lib", "/opt/user-lib"]),
+ (["/nix/store/user-plugin/lib/python3.12/site-packages", "/old/lib/python2.7/site-packages"],
+ ["/nix/store/user-plugin/lib/python3.12/site-packages", "/old/lib/python2.7/site-packages"]),
+ (["/opt/tools/python3.13/bin", "/opt/downloads/python3.13", "/custom/python3.13"],
+ ["/opt/tools/python3.13/bin", "/opt/downloads/python3.13", "/custom/python3.13"]),
+ ([""], [""]),
+ (None, None),
+])
+def test_pythonpath_literal_policy(entries, expected):
+ locations = {"REPO": str(Path(__file__).resolve().parents[2]), "SITE": str(_running_site())}
+ env = {} if entries is None else {"PYTHONPATH": os.pathsep.join(locations.get(p, p) for p in entries)}
+ pp._strip_hermes_owned_pythonpath(env)
+ assert env.get("PYTHONPATH") == (os.pathsep.join(expected) if expected is not None else None)
+
+
+def test_pythonpath_descendants_are_not_owned():
+ repo, site = Path(__file__).resolve().parents[2], _running_site()
+ entries = [str(site / "user-path"), str(repo / "tools"), str(repo / "tools/environments"),
+ "/opt/other-venv/lib/python3.99/site-packages"]
+ env = {"PYTHONPATH": os.pathsep.join(entries)}
+ pp._strip_hermes_owned_pythonpath(env)
+ assert env["PYTHONPATH"].split(os.pathsep) == entries
+
+
[email protected]("linux", "macos", "windows")
[email protected]("link_at", ["home", "repo", "unrelated"])
[email protected]("profile", [False, True])
+def test_launcher_alias_provenance(child_env, monkeypatch, link_at, profile):
+ from hermes_cli.gateway_windows import _preserve_hermes_home_path
+ from hermes_cli.profiles import resolve_profile_env
+ physical_home = child_env / "physical-home"
+ physical_root = physical_home / "hermes-agent"
+ physical_root.mkdir(parents=True)
+ configured = child_env / "configured-home"
+ if link_at == "home":
+ _make_directory_link(configured, physical_home)
+ else:
+ configured.mkdir()
+ if link_at == "repo":
+ _make_directory_link(configured / "hermes-agent", physical_root)
+ else:
+ (configured / "hermes-agent").mkdir()
+ (configured / "profiles/coder").mkdir(parents=True)
+ unrelated = child_env / "user-tools/hermes-agent"
+ unrelated.mkdir(parents=True)
+ lexical_root = configured / "hermes-agent"
+ monkeypatch.setenv("HERMES_HOME", str(configured))
+ assert Path(resolve_profile_env("default")) == configured
+ assert Path(resolve_profile_env("coder")) == configured / "profiles/coder"
+ if link_at == "home":
+ assert Path(_preserve_hermes_home_path(physical_root)) == lexical_root
+ active_home = configured / "profiles/coder" if profile else configured
+ aliases = pp._build_hermes_repo_root_aliases(physical_root.resolve(), physical_root, active_home)
+ monkeypatch.setattr(local, "_hermes_repo_root_aliases", aliases)
+ nested = lexical_root / "user-data"
+ entries = [str(lexical_root), str(nested), str(unrelated), str(active_home / "not-the-repo")]
+ env = {"PYTHONPATH": os.pathsep.join(entries)}
+ pp._strip_hermes_owned_pythonpath(env)
+ assert env["PYTHONPATH"].split(os.pathsep) == (entries if link_at == "unrelated" else entries[1:])
+ if profile:
+ assert active_home / "hermes-agent" not in aliases
+
+
[email protected]("has_facts", [True, False])
+def test_runtime_provenance_is_independent_of_aliases_and_virtual_env(child_env, monkeypatch, has_facts):
+ from hermes_cli.runtime_paths import runtime_facts_path
+ payload = child_env / "payload"
+ runtime = payload / "state/environments/candidate/venv"
+ site = runtime / ("Lib/site-packages" if os.name == "nt" else
+ f"lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages")
+ site.mkdir(parents=True)
+ (runtime / "pyvenv.cfg").write_text("version = 3.14\n", encoding="utf-8")
+ (payload / "tools").mkdir()
+ (payload / "manifest.json").write_text("{}", encoding="utf-8")
+ monkeypatch.setattr("hermes_cli.runtime_paths.install_state_dir", lambda repo: payload / "state")
+ if has_facts:
+ facts = runtime_facts_path(Path(__file__).resolve().parents[2])
+ facts.parent.mkdir(parents=True, exist_ok=True)
+ facts.write_text(json.dumps({"packages": {"venv": {"environment": str(runtime)}}}), encoding="utf-8")
+ monkeypatch.setattr(local, "_in_venv", False)
+ monkeypatch.setattr(local, "_hermes_site_packages", None)
+ alias = child_env / "unrelated-repo-alias"
+ monkeypatch.setattr(local, "_hermes_repo_root_aliases", (alias,))
+ user_venv = child_env / "user-venv"
+ user_site = user_venv / "Lib/site-packages"
+ user_site.mkdir(parents=True)
+ (user_venv / "pyvenv.cfg").write_text("version = 3.13\n", encoding="utf-8")
+ base = {"VIRTUAL_ENV": str(user_venv), "PYTHONPATH": os.pathsep.join(map(str, [site, alias, user_site]))}
+ result = local._sanitize_subprocess_env(base)
+ expected = [str(user_site)] if has_facts else [str(site), str(user_site)]
+ assert result["PYTHONPATH"].split(os.pathsep) == expected
+ assert "VIRTUAL_ENV" not in result
+ assert base["VIRTUAL_ENV"] == str(user_venv)
+
+
[email protected]("existing,expected", [
+ (["/usr/bin", "/bin"], ["/opt/hermes/bin", "/usr/bin", "/bin"]),
+ (["/usr/bin", "/opt/hermes/bin"], ["/usr/bin", "/opt/hermes/bin"]),
+])
+def test_background_hermes_path_repair_is_idempotent(child_env, monkeypatch, existing, expected):
+ monkeypatch.setattr(local, "_HERMES_BIN_DIR", "/opt/hermes/bin")
+ result = local._sanitize_subprocess_env({"PATH": os.pathsep.join(existing)})
+ assert result["PATH"].split(os.pathsep) == expected
+ assert local._sanitize_subprocess_env(result)["PATH"] == result["PATH"]
+
+
+def test_hermes_bin_resolution_and_unresolved_noop(child_env, monkeypatch):
+ bin_dir = child_env / "bin"
+ bin_dir.mkdir()
+ monkeypatch.setattr(local, "_HERMES_BIN_DIR", local._SENTINEL)
+ monkeypatch.setattr(local.shutil, "which", lambda name: str(bin_dir / "hermes") if name == "hermes" else None)
+ assert local._resolve_hermes_bin_dir() == str(bin_dir)
+ monkeypatch.setattr(local, "_HERMES_BIN_DIR", None)
+ assert local._prepend_hermes_bin_dir("/usr/bin") == "/usr/bin"
+
+
+def test_foreground_minimal_path_preserves_operator_precedence(child_env, monkeypatch):
+ monkeypatch.setattr(local, "_HERMES_BIN_DIR", "/opt/hermes/bin")
+ monkeypatch.setenv("PATH", "/custom/bin:/custom/bin::/usr/bin")
+ result = local._make_run_env({})["PATH"].split(":")
+ assert result[:3] == ["/opt/hermes/bin", "/custom/bin", "/usr/bin"]
+ assert "/opt/homebrew/bin" in result and "/opt/homebrew/sbin" in result
+ assert "" not in result
+ assert result.count("/custom/bin") == 1
def _make_directory_link(link: Path, target: Path) -> None:
@@ -626,142 +370,10 @@ def _make_directory_link(link: Path, target: Path) -> None:
raise OSError(detail or f"mklink /J failed: {result.returncode}")
-def _physical_repo_root(tmp_path: Path) -> Path:
- """Create the physical repo checkout directory for junction tests."""
- physical_root = tmp_path / "physical-home" / "hermes-agent"
- physical_root.mkdir(parents=True)
- return physical_root
-
-
-class TestPythonpathSelectiveStrip:
- """PYTHONPATH Hermes-owned entry stripping (#74817).
-
- The Desktop Electron app injects the Hermes repo root and the Hermes
- venv's site-packages (Python 3.11) into PYTHONPATH. When this leaks
- into subprocesses running a different Python (e.g. 3.13), 3.11 C
- extensions appear on sys.path and crash with ImportError.
- ``_strip_hermes_owned_pythonpath`` surgically removes only the
- entries Hermes itself owns (repo root, own venv site-packages),
- preserving user paths — including user paths whose names merely
- contain another Python version.
- """
-
- def test_owned_entries_stripped_matrix(self):
- """Exact Hermes-owned entries are removed; everything else survives
- verbatim (ordering, duplicates, empty components).
-
- Covers: the running venv's site-packages, the repo root (computed
- independently via parents[2] so an off-by-one in _hermes_repo_root
- cannot silently pass), duplicate Hermes entries, all-owned input
- (PYTHONPATH key removed), and mixed user/Hermes ordering with an
- empty component preserved.
- """
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
-
- venv_sp = str(_running_venv_site_packages())
- local_file = Path(__import__("tools.environments.local", fromlist=["__file__"]).__file__).resolve()
- repo_root = str(local_file.parents[2])
- cases = [
- ([venv_sp, "/home/user/my-lib"], ["/home/user/my-lib"]),
- ([repo_root, "/home/user/my-lib"], ["/home/user/my-lib"]),
- ([venv_sp, "/user/lib", venv_sp, "/user/lib"], ["/user/lib", "/user/lib"]),
- ([venv_sp], None), # all owned -> PYTHONPATH key removed
- (["/first/user/lib", repo_root, "", venv_sp, "/second/user/lib"],
- ["/first/user/lib", "", "/second/user/lib"]),
- ]
- for input_entries, expected in cases:
- env = {"PYTHONPATH": os.pathsep.join(input_entries)}
- _strip_hermes_owned_pythonpath(env)
- if expected is None:
- assert "PYTHONPATH" not in env
- else:
- assert env["PYTHONPATH"].split(os.pathsep) == expected
-
- @pytest.mark.parametrize("user_pp", [
- os.pathsep.join(["/opt/my-lib", "/another/path"]),
- "/nix/store/abc123-user-plugin/lib/python3.12/site-packages",
- os.pathsep.join(["/old/lib/python2.7/site-packages", "/home/user/lib"]),
- os.pathsep.join(["/opt/tools/python3.13/bin", "/opt/downloads/python3.13", "/custom/python3.13"]),
- os.pathsep.join([" /opt/user-lib ", "relative/../lib", "", "/opt/user-lib", "/opt/user-lib"]),
- os.pathsep.join(["/foo", "", "/bar"]),
- "",
- ])
- def test_non_owned_entries_preserved(self, user_pp):
- """Anything not proven Hermes-owned is preserved byte-for-byte.
-
- One invariant, one matrix: ordinary user paths, Nix store paths,
- other-major/minor-version site-packages, paths merely containing a
- pythonX.Y component, raw spellings (whitespace, relative segments,
- duplicates), empty components, and an empty PYTHONPATH all reduce to
- the same contract -- ownership is decided by provenance, never by
- path shape or version (P1/P2, #74817 follow-ups).
- """
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
- env = {"PYTHONPATH": user_pp}
- _strip_hermes_owned_pythonpath(env)
- assert env.get("PYTHONPATH") == user_pp
-
- def test_non_owned_runtime_shaped_entries_preserved(self):
- """Runtime-derived user spellings are preserved: site-packages for a
- different interpreter version, a descendant of the Hermes venv
- site-packages, and direct/deeper children of the repo root. The
- repo root is computed independently (parents[2] of this file) so an
- off-by-one in _hermes_repo_root cannot silently pass; no launcher
- injects a direct child as a standalone entry, so such paths are user
- paths by contract.
- """
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
- import sys
-
- running_minor = sys.version_info[1]
- other_minor = running_minor + 1 if running_minor < 20 else running_minor - 1
- local_file = Path(__import__("tools.environments.local", fromlist=["__file__"]).__file__).resolve()
- real_repo_root = local_file.parents[2]
- inputs = [
- os.pathsep.join([
- f"/opt/other-venv/lib/python{sys.version_info[0]}.{other_minor}/site-packages",
- "/home/user/my-lib",
- ]),
- os.pathsep.join([str(_running_venv_site_packages() / "some-user-path"), "/home/user/my-lib"]),
- os.pathsep.join([str(real_repo_root / "tools"), "/home/user/my-lib"]),
- os.pathsep.join([str(real_repo_root / "tools" / "environments"), "/home/user/my-lib"]),
- ]
- for user_pp in inputs:
- env = {"PYTHONPATH": user_pp}
- _strip_hermes_owned_pythonpath(env)
- assert env["PYTHONPATH"] == user_pp
-
- def test_windows_backslash_paths(self):
- """Windows-style backslash paths are handled for Hermes-owned entries.
-
- On Windows, os.pathsep is ';'. We mock it so the test runs
- correctly on POSIX CI. On a POSIX host a backslash path is a
- single path component, so ``Path`` cannot identify it as
- Hermes-owned — the critical invariant is that user Windows paths
- (including site-packages paths for another Python version) are
- never destroyed. On a real Windows host, Path splits on
- backslashes and Hermes venv site-packages entries are stripped
- by the same Hermes-owned check (covered by the Windows-only test
- below).
- """
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
- import sys
-
- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"
- hermes_win = f"C:\\\\Users\\\\u\\\\.hermes\\\\hermes-agent\\\\venv\\\\lib\\\\{pyver}\\\\site-packages"
- user_win = "D:\\\\user\\\\lib"
- env = {
- "PYTHONPATH": ";".join([hermes_win, user_win]),
- }
- # Mock os.pathsep to ';' (Windows) just for the strip call.
- with patch("os.pathsep", ";"):
- _strip_hermes_owned_pythonpath(env)
- assert "PYTHONPATH" in env
- entries = env["PYTHONPATH"].split(";")
- # Both survive on POSIX: user paths must always be preserved, and
- # the Hermes-owned check cannot match a backslash path here.
- assert hermes_win in entries
- assert user_win in entries
+class TestNativeEnvironmentContracts:
+ @pytest.fixture(autouse=True)
+ def _no_bin_injection(self, monkeypatch):
+ monkeypatch.setattr(local, "_HERMES_BIN_DIR", None)
@pytest.mark.platforms("windows")
def test_windows_hermes_owned_paths_stripped(self):
@@ -772,7 +384,7 @@ class TestPythonpathSelectiveStrip:
on a POSIX host."""
from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
- venv_sp = str(_running_venv_site_packages())
+ venv_sp = str(_running_site())
# Windows form: C:\...\venv\Lib\site-packages (backslashes)
hermes_win = venv_sp
user_win = "D:\\\\user\\\\lib"
@@ -784,833 +396,6 @@ class TestPythonpathSelectiveStrip:
assert hermes_win not in entries
assert user_win in entries
- def test_empty_pythonpath_unchanged(self):
- """An empty PYTHONPATH is a no-op (falsy -> early return)."""
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
- env = {"PYTHONPATH": ""}
- _strip_hermes_owned_pythonpath(env)
- # Empty string is falsy, so the function returns early without
- # modifying the dict. The key stays as-is (empty string).
- assert env.get("PYTHONPATH") == ""
-
- def test_empty_component_preserved(self):
- """An empty component means cwd and must survive unchanged."""
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
-
- user_pp = os.pathsep.join(["/foo", "", "/bar"])
- env = {"PYTHONPATH": user_pp}
-
- _strip_hermes_owned_pythonpath(env)
-
- assert env["PYTHONPATH"] == user_pp
-
- def test_raw_user_spelling_preserved(self):
- """The sanitizer does not trim, normalize, or deduplicate user entries."""
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
-
- user_pp = os.pathsep.join([
- " /opt/user-lib ",
- "relative/../lib",
- "",
- "/opt/user-lib",
- "/opt/user-lib",
- ])
- env = {"PYTHONPATH": user_pp}
-
- _strip_hermes_owned_pythonpath(env)
-
- assert env["PYTHONPATH"] == user_pp
-
-
- def test_base_python_sanitizer_uses_validated_separate_runtime_venv(self, tmp_path, monkeypatch):
- """A base interpreter strips the exact pm runtime site-packages.
-
- This deliberately uses a synthetic Hermes venv separate from the test
- runner: sys.prefix represents base Python, while the pm-provisioned
- runtime venv (facts + store layout, no VIRTUAL_ENV anywhere)
- identifies the Hermes runtime site-packages.
- """
- import json
-
- import tools.environments.local as local
- from tools.environments import local_pythonpath
-
- # pm bundled-install layout: store + manifest + relocatable venv.
- payload = tmp_path / "payload"
- store = payload / "tools"
- runtime_venv = payload / "state" / "environments" / "candidate" / "venv"
- runtime_sp = __import__("hermes_cli.runtime_paths", fromlist=["site_packages"]).site_packages(runtime_venv)
- runtime_sp.mkdir(parents=True)
- store.mkdir(parents=True, exist_ok=True)
- (payload / "manifest.json").write_text("{}", encoding="utf-8")
- from hermes_cli.runtime_paths import runtime_facts_path
- monkeypatch.setattr("hermes_cli.runtime_paths.install_state_dir", lambda repo: payload / "state")
- facts = runtime_facts_path(Path(local.__file__).resolve().parents[2])
- facts.parent.mkdir(parents=True, exist_ok=True)
- (runtime_venv / "pyvenv.cfg").write_text("version = 3.11\n")
- facts.write_text(json.dumps({"packages": {"venv": {"environment": str(runtime_venv)}}}))
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
- monkeypatch.delenv("VIRTUAL_ENV", raising=False)
-
- base_prefix = tmp_path / "base-python"
- unrelated = "/custom/lib/python3.13/site-packages"
-
- monkeypatch.setattr(local, "_hermes_repo_root_aliases", (tmp_path / "hermes-agent",))
- monkeypatch.setattr(local, "_in_venv", False)
- monkeypatch.setattr(local, "_hermes_site_packages", None)
- monkeypatch.setattr(local.sys, "prefix", str(base_prefix))
- monkeypatch.setattr(local.sys, "base_prefix", str(base_prefix))
-
- env = {
- "PYTHONPATH": os.pathsep.join([str(runtime_sp), unrelated]),
- }
- result = local._sanitize_subprocess_env(env)
-
- assert Path(local.sys.prefix) == base_prefix
- assert runtime_venv != Path(local.sys.prefix)
- assert result["PYTHONPATH"] == unrelated
- assert "VIRTUAL_ENV" not in result
-
- def test_unrelated_virtual_env_is_not_runtime_provenance(self, tmp_path, monkeypatch):
- """An arbitrary inherited VIRTUAL_ENV cannot claim PYTHONPATH
- ownership — provenance is pm's facts, and pm records no venv here."""
- import tools.environments.local as local
- from tools.environments import local_pythonpath
-
- unrelated_venv = tmp_path / "user-venv"
- unrelated_sp = unrelated_venv / "Lib" / "site-packages"
- unrelated_sp.mkdir(parents=True)
- (unrelated_venv / "pyvenv.cfg").write_text("version = 3.13\n", encoding="utf-8")
-
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "no-such-store"))
- monkeypatch.delenv("VIRTUAL_ENV", raising=False)
- monkeypatch.setattr(local, "_hermes_repo_root_aliases", (tmp_path / "hermes-agent",))
- monkeypatch.setattr(local, "_in_venv", False)
- monkeypatch.setattr(local, "_hermes_site_packages", None)
-
- env = {
- "VIRTUAL_ENV": str(unrelated_venv),
- "PYTHONPATH": str(unrelated_sp),
- }
- local_pythonpath._strip_hermes_owned_pythonpath(env)
-
- assert env["PYTHONPATH"] == str(unrelated_sp)
-
-
- def test_no_pythonpath_key(self):
- """Missing PYTHONPATH key is a no-op."""
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
- env = {"PATH": "/usr/bin"}
- _strip_hermes_owned_pythonpath(env)
- assert "PYTHONPATH" not in env
-
-
- @pytest.mark.parametrize("builder", [
- "_make_run_env",
- "_sanitize_subprocess_env",
- "hermes_subprocess_env",
- ])
- def test_builders_strip_hermes_venv_pythonpath(self, builder):
- """Every subprocess env builder applies the same sanitation contract:
- Hermes venv site-packages is stripped, user entries survive.
- """
- from tools.environments import local as local_mod
-
- venv_sp = str(_running_venv_site_packages())
- seed = {
- "PATH": "/usr/bin:/bin",
- "HOME": "/home/user",
- "PYTHONPATH": os.pathsep.join([venv_sp, "/home/user/my-lib"]),
- }
- with patch.dict(os.environ, seed, clear=False):
- if builder == "_make_run_env":
- result = local_mod._make_run_env({})
- elif builder == "_sanitize_subprocess_env":
- result = local_mod._sanitize_subprocess_env(dict(os.environ))
- else:
- result = local_mod.hermes_subprocess_env()
- pp = result.get("PYTHONPATH", "")
- entries = pp.split(os.pathsep) if pp else []
- assert venv_sp not in entries
- assert "/home/user/my-lib" in entries
-
- def test_scrub_child_env_strips_hermes_venv_pythonpath(self):
- """execute_code's _scrub_child_env path: after scrubbing, Hermes venv
- site-packages entries should be stripped when
- _strip_hermes_owned_pythonpath is applied (as the spawn path does),
- while user entries (even for another Python version) are preserved.
- """
- from tools.code_execution_env import _scrub_child_env
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
-
- venv_sp = str(_running_venv_site_packages())
- other_sp = "/opt/other-venv/lib/python3.99/site-packages"
- source = {
- "PATH": "/usr/bin",
- "HOME": "/home/user",
- "PYTHONPATH": os.pathsep.join([venv_sp, other_sp, "/home/user/my-lib"]),
- }
- scrubbed = _scrub_child_env(source)
- # The scrubber passes PYTHONPATH through (it's in _SAFE_ENV_PREFIXES).
- assert "PYTHONPATH" in scrubbed
- # Now apply the selective strip (as the spawn path does).
- _strip_hermes_owned_pythonpath(scrubbed)
- pp = scrubbed.get("PYTHONPATH", "")
- entries = pp.split(os.pathsep) if pp else []
- assert venv_sp not in entries
- assert other_sp in entries
- assert "/home/user/my-lib" in entries
-
- @pytest.mark.parametrize("same_env", [True, False])
- def test_execute_code_composition_strips_inherited_hermes_entries(self, same_env):
- """Integration: execute_code's real spawn path composes a clean PYTHONPATH.
-
- Seeds a contaminated inherited PYTHONPATH (Hermes repo root + Hermes
- venv site-packages + user entries) through os.environ and drives
- execute_code all the way to Popen. Proves the #84500 conditional
- composition and the #82581 selective strip compose correctly:
-
- * inherited Hermes venv site-packages never survive into the sandbox;
- * the staging tmpdir stays the first entry;
- * the repo root is deliberately re-added exactly once for a same-env
- child (the single occurrence proves the inherited copy was stripped
- first) and stays absent for an external-environment child;
- * user entries survive after the controlled entries.
- """
- import tools.code_execution_tool as cet
- from tools.code_execution_tool import execute_code
-
- def _mock_handle_function_call(function_name, function_args, task_id=None, user_task=None):
- return '{"output": "mock", "exit_code": 0}'
-
- hermes_root = str(Path(cet.__file__).resolve().parents[1])
- venv_sp = str(_running_venv_site_packages())
- user_a = "/home/user/my-lib"
- user_b = "/opt/project/lib"
- captured = {}
-
- def _fake_popen(cmd, **kwargs):
- captured["env"] = kwargs.get("env", {})
- captured["staging"] = os.path.dirname(cmd[1])
- proc = MagicMock()
- proc.stdout.read.return_value = b""
- proc.stdout.read1.return_value = b""
- proc.stderr.read.return_value = b""
- proc.wait.return_value = 0
- proc.returncode = 0
- proc.poll.return_value = 0
- return proc
-
- with patch("tools.code_execution_tool._load_config",
- return_value={"mode": "strict"}), \
- patch("model_tools.handle_function_call",
- side_effect=_mock_handle_function_call), \
- patch("tools.code_execution_env._uses_hermes_python_environment",
- return_value=same_env), \
- patch("subprocess.Popen", side_effect=_fake_popen), \
- patch.dict(os.environ, {
- "PYTHONPATH": os.pathsep.join(
- [hermes_root, venv_sp, user_a, user_b]),
- }):
- execute_code(code="pass", task_id="test-int", enabled_tools=[])
-
- assert "PYTHONPATH" in captured["env"], \
- "execute_code never reached Popen"
- parts = captured["env"]["PYTHONPATH"].split(os.pathsep)
- # Windows path comparison is case-insensitive: the inherited entries
- # and the re-added repo root can carry a different case than the
- # resolve()/abspath()-derived spellings used in this test (e.g. a
- # launcher-written lowercase PYTHONPATH). Normalize with
- # os.path.normcase so a case-only difference never fails the
- # composition contract (identity on POSIX).
- norm_parts = [os.path.normcase(p) for p in parts]
- norm_staging = os.path.normcase(captured["staging"])
- norm_root = os.path.normcase(hermes_root)
- norm_venv = os.path.normcase(venv_sp)
- norm_user_a = os.path.normcase(user_a)
- norm_user_b = os.path.normcase(user_b)
- assert norm_parts[0] == norm_staging, \
- "staging tmpdir must be the first PYTHONPATH entry"
- assert norm_venv not in norm_parts, \
- "inherited Hermes venv site-packages must be stripped"
- assert norm_user_a in norm_parts and norm_user_b in norm_parts, \
- "user PYTHONPATH entries must survive"
- assert norm_parts.index(norm_user_a) > norm_parts.index(norm_staging), \
- "user entries must come after the staging tmpdir"
- if same_env:
- assert norm_parts.count(norm_root) == 1, \
- "repo root must be re-added exactly once for a same-env child"
- assert norm_parts.index(norm_user_a) > norm_parts.index(norm_root), \
- "user entries must come after the re-added repo root"
- else:
- assert norm_root not in norm_parts, \
- "repo root must stay absent for an external-env child"
-
-
- def test_repo_root_direct_child_preserved(self):
- """A direct child of the repo root (depth=1) is PRESERVED.
-
- Independent audit of every real launcher producer (Electron
- ``apps/desktop/electron/main.ts``,
- ``gateway/run.py::_ensure_windows_gateway_venv_imports``,
- ``cron/scheduler.py::_windows_cron_python_invocation``,
- ``tui_gateway/host_supervisor.py``) shows they all inject the exact
- repo root and/or the venv site-packages — none injects
- ``<repo>/tools`` or another direct child as an independent
- PYTHONPATH entry. A user path that merely happens to live under
- the repo directory must therefore be preserved.
- """
- from tools.environments.local_pythonpath import _strip_hermes_owned_pythonpath
-
- local_file = Path(__import__("tools.environments.local", fromlist=["__file__"]).__file__).resolve()
- real_repo_root = local_file.parents[2]
- direct_child = str(real_repo_root / "tools")
-
- env = {
- "PYTHONPATH": os.pathsep.join([direct_child, "/home/user/my-lib"]),
- }
- _strip_hermes_owned_pythonpath(env)
- pp = env.get("PYTHONPATH", "")
- entries = pp.split(os.pathsep) if pp else []
- assert direct_child in entries
- assert "/home/user/my-lib" in entries
-
- def test_configured_home_alias_matches_launcher_output(self, tmp_path, monkeypatch):
- """The real producer spelling is derived and consumed end to end."""
- import tools.environments.local as local
- from tools.environments import local_pythonpath
- from hermes_cli.gateway_windows import _preserve_hermes_home_path
-
- physical_home = tmp_path / "physical-home"
- physical_root = _physical_repo_root(tmp_path)
- configured_home = tmp_path / "configured-home"
- try:
- _make_directory_link(configured_home, physical_home)
- except OSError as exc:
- pytest.skip(f"directory link unavailable on this host: {exc}")
- monkeypatch.setenv("HERMES_HOME", str(configured_home))
-
- launcher_entry = Path(_preserve_hermes_home_path(physical_root))
- aliases = local_pythonpath._build_hermes_repo_root_aliases(
- physical_root.resolve(),
- physical_root,
- configured_home,
- )
-
- assert launcher_entry == configured_home / "hermes-agent"
- assert launcher_entry in aliases
-
- monkeypatch.setattr(local, "_hermes_repo_root_aliases", aliases)
- nested_user_path = launcher_entry / "user-data"
- env = {
- "PYTHONPATH": os.pathsep.join([
- str(launcher_entry),
- str(nested_user_path),
- "/home/user/my-lib",
- ])
- }
- local_pythonpath._strip_hermes_owned_pythonpath(env)
-
- assert env["PYTHONPATH"].split(os.pathsep) == [
- str(nested_user_path),
- "/home/user/my-lib",
- ]
-
- def test_profile_rehome_keeps_junction_lexical_alias(self, tmp_path, monkeypatch):
- """Profile re-home must not lose the launcher's lexical repo-root spelling.
-
- The desktop/CLI spawn children with HERMES_HOME and PYTHONPATH in the
- configured (junction) spelling, but --profile / sticky active_profile
- re-home HERMES_HOME through resolve_profile_env() before the
- sanitizer loads. Regression (junction + profile re-home): the alias
- builder must still recover the lexical root so the inherited lexical
- repo-root entry is stripped.
- """
- import tools.environments.local as local
- from tools.environments import local_pythonpath
- from hermes_cli.profiles import resolve_profile_env
-
- physical_home = tmp_path / "physical-home"
- physical_root = physical_home / "hermes-agent"
- physical_root.mkdir(parents=True)
- (physical_home / "profiles" / "coder").mkdir(parents=True)
- configured_home = tmp_path / "configured-home"
- try:
- _make_directory_link(configured_home, physical_home)
- except OSError as exc:
- pytest.skip(f"directory link unavailable on this host: {exc}")
-
- # Launcher contract: the configured spelling is the env and the root.
- monkeypatch.setenv("HERMES_HOME", str(configured_home))
- lexical_root = configured_home / "hermes-agent"
-
- # Profile re-home keeps the configured spelling (physically identical
- # through the link; lexically the launcher spelling is preserved).
- assert Path(resolve_profile_env("default")) == configured_home
- assert Path(resolve_profile_env("coder")) == configured_home / "profiles" / "coder"
-
- # The sanitizer now runs under the re-homed (profile) HERMES_HOME.
- aliases = local_pythonpath._build_hermes_repo_root_aliases(
- physical_root.resolve(),
- physical_root,
- configured_home / "profiles" / "coder",
- )
- assert any(local_pythonpath._same_path(a, lexical_root) for a in aliases)
-
- monkeypatch.setattr(local, "_hermes_repo_root_aliases", aliases)
- env = {"PYTHONPATH": os.pathsep.join([str(lexical_root), "/home/user/my-lib"])}
- local_pythonpath._strip_hermes_owned_pythonpath(env)
- assert env["PYTHONPATH"].split(os.pathsep) == ["/home/user/my-lib"]
-
-
- def test_repo_level_junction_recovers_lexical_alias(self, tmp_path, monkeypatch):
- """The repo itself may be a junction under the configured root
- (e.g. D:\\hermes\\hermes-agent -> C:\\...\\hermes-agent) while the
- editable import spelling resolves to the physical location. The
- alias builder must recover the lexical spelling via exact-identity
- proof (strict resolve), not a name-based guess.
- """
- import tools.environments.local as local
- from tools.environments import local_pythonpath
-
- physical_root = _physical_repo_root(tmp_path)
- configured_home = tmp_path / "configured-home"
- configured_home.mkdir()
- # repo-level link: <configured-home>/hermes-agent -> physical repo
- try:
- _make_directory_link(configured_home / "hermes-agent", physical_root)
- except OSError as exc:
- pytest.skip(f"directory link unavailable on this host: {exc}")
-
- lexical_root = configured_home / "hermes-agent"
- aliases = local_pythonpath._build_hermes_repo_root_aliases(
- physical_root.resolve(),
- physical_root,
- configured_home,
- )
- assert any(local_pythonpath._same_path(a, lexical_root) for a in aliases)
-
- monkeypatch.setattr(local, "_hermes_repo_root_aliases", aliases)
- env = {"PYTHONPATH": os.pathsep.join([str(lexical_root), "/home/user/my-lib"])}
- local_pythonpath._strip_hermes_owned_pythonpath(env)
- assert env["PYTHONPATH"].split(os.pathsep) == ["/home/user/my-lib"]
-
- def test_same_named_non_owned_directories_preserved(self, tmp_path, monkeypatch):
- """Negative controls: a directory that merely shares the repo's name
- -- whether under the configured root or in an unrelated location --
- is never aliased or stripped. Exact filesystem identity decides,
- not the name; no ownership provenance means no strip.
- """
- import tools.environments.local as local
- from tools.environments import local_pythonpath
-
- physical_root = _physical_repo_root(tmp_path)
- configured_home = tmp_path / "configured-home"
- (configured_home / "hermes-agent").mkdir(parents=True)
- unrelated = tmp_path / "user-tools" / "hermes-agent"
- unrelated.mkdir(parents=True)
-
- aliases = local_pythonpath._build_hermes_repo_root_aliases(
- physical_root.resolve(),
- physical_root,
- configured_home,
- )
- for lookalike in (configured_home / "hermes-agent", unrelated):
- assert not any(local_pythonpath._same_path(a, lookalike) for a in aliases)
-
- monkeypatch.setattr(local, "_hermes_repo_root_aliases", aliases)
- for lookalike in (configured_home / "hermes-agent", unrelated):
- env = {"PYTHONPATH": os.pathsep.join([str(lookalike), "/home/user/my-lib"])}
- local_pythonpath._strip_hermes_owned_pythonpath(env)
- assert env["PYTHONPATH"].split(os.pathsep) == [str(lookalike), "/home/user/my-lib"]
-
- def test_profile_home_with_repo_level_junction(self, tmp_path, monkeypatch):
- """Profile re-home + repo-level junction together: the configured home
- is <root>/profiles/<name> while the repo is a link at <root>/hermes-agent.
- The root spelling must be derived (profiles -> grandparent) and then
- the lexical repo alias recovered from it.
- """
- import tools.environments.local as local
- from tools.environments import local_pythonpath
-
- physical_root = _physical_repo_root(tmp_path)
- configured_root = tmp_path / "configured-root"
- (configured_root / "profiles" / "coder").mkdir(parents=True)
- try:
- _make_directory_link(configured_root / "hermes-agent", physical_root)
- except OSError as exc:
- pytest.skip(f"directory link unavailable on this host: {exc}")
-
- configured_home = configured_root / "profiles" / "coder"
- lexical_root = configured_root / "hermes-agent"
- aliases = local_pythonpath._build_hermes_repo_root_aliases(
- physical_root.resolve(),
- physical_root,
- configured_home,
- )
- assert any(local_pythonpath._same_path(a, lexical_root) for a in aliases)
- assert not any(local_pythonpath._same_path(a, configured_home / "hermes-agent") for a in aliases)
-
- monkeypatch.setattr(local, "_hermes_repo_root_aliases", aliases)
- env = {"PYTHONPATH": os.pathsep.join([str(lexical_root), "/home/user/my-lib"])}
- local_pythonpath._strip_hermes_owned_pythonpath(env)
- assert env["PYTHONPATH"].split(os.pathsep) == ["/home/user/my-lib"]
-
- def test_pm_runtime_venv_provenance_is_alias_independent(self, tmp_path, monkeypatch):
- """pm's facts/store layout is the provenance for the runtime venv —
- not a VIRTUAL_ENV matched against repo aliases. The pm-provisioned
- venv's site-packages is stripped together with the repo root, while
- user entries survive, even when an unrelated VIRTUAL_ENV is present.
- """
- import json
-
- import tools.environments.local as local
- from tools.environments import local_pythonpath
-
- # pm bundled-install layout, entirely outside the repo aliases.
- payload = tmp_path / "payload"
- store = payload / "tools"
- venv_dir = payload / "state" / "environments" / "candidate" / "venv"
- venv_sp = __import__("hermes_cli.runtime_paths", fromlist=["site_packages"]).site_packages(venv_dir)
- venv_sp.mkdir(parents=True)
- store.mkdir(parents=True, exist_ok=True)
- (payload / "manifest.json").write_text("{}", encoding="utf-8")
- from hermes_cli.runtime_paths import runtime_facts_path
- monkeypatch.setattr("hermes_cli.runtime_paths.install_state_dir", lambda repo: payload / "state")
- facts = runtime_facts_path(Path(local.__file__).resolve().parents[2])
- facts.parent.mkdir(parents=True, exist_ok=True)
- (venv_dir / "pyvenv.cfg").write_text("version = 3.11\n")
- facts.write_text(json.dumps({"packages": {"venv": {"environment": str(venv_dir)}}}))
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
-
- validated = local_pythonpath._validated_runtime_venv({"VIRTUAL_ENV": "/somewhere/else"})
- assert validated is not None
- assert local_pythonpath._same_path(validated, venv_dir)
-
- monkeypatch.setattr(local, "_hermes_site_packages", None)
- monkeypatch.setattr(local, "_in_venv", False)
- env = {"PYTHONPATH": os.pathsep.join([
- str(venv_sp),
- "/home/user/my-lib",
- ])}
- local_pythonpath._strip_hermes_owned_pythonpath(env)
- assert env["PYTHONPATH"].split(os.pathsep) == ["/home/user/my-lib"]
-
-
-
-
-
-class TestPythonhomeSanitized:
- """PYTHONHOME must not leak from the Hermes runtime into subprocesses.
-
- The gateway inherits/sets PYTHONHOME in its process environment; a child
- interpreter (system Python, another venv, cron no_agent scripts) that
- inherits it redirects its stdlib search to the Hermes venv and crashes
- with version-mismatch errors before importing anything (#75018).
- """
-
- @pytest.mark.parametrize("builder", [
- "_make_run_env",
- "_sanitize_subprocess_env",
- "hermes_subprocess_env",
- "build_subprocess_env",
- ])
- def test_builders_strip_pythonhome(self, builder):
- """The gateway's inherited PYTHONHOME must not reach any subprocess
- builder -- terminal, background/PTY, cron no_agent scripts, and
- execute_code children (#75018).
- """
- from tools.environments import local as local_mod
-
- seed = {
- "PATH": "/usr/bin:/bin",
- "HOME": "/home/user",
- "PYTHONHOME": "/opt/hermes-venv",
- }
- with patch.dict(os.environ, seed, clear=True):
- if builder == "_make_run_env":
- result = local_mod._make_run_env({})
- elif builder == "_sanitize_subprocess_env":
- result = local_mod._sanitize_subprocess_env(dict(os.environ))
- elif builder == "hermes_subprocess_env":
- result = local_mod.hermes_subprocess_env()
- else:
- result = local_mod.build_subprocess_env()
- assert "PYTHONHOME" not in result
-
- def test_pythonhome_removed_from_active_venv_markers(self):
- """PYTHONHOME is part of _ACTIVE_VENV_MARKER_VARS so all builders
- that iterate it drop the variable."""
- from tools.environments.local_env_policy import _ACTIVE_VENV_MARKER_VARS
- assert "PYTHONHOME" in _ACTIVE_VENV_MARKER_VARS
-
- def test_build_subprocess_env_no_scrub_preserves_pythonhome(self):
- """``build_subprocess_env(scrub_secrets=False)`` is the documented
- byte-for-byte escape hatch: no key is removed, so PYTHONHOME (and
- everything else) survives there by contract, not by omission.
-
- Callers that explicitly opt out of scrubbing (git credential flows,
- secret CLIs) must not have their environment silently altered — this
- test pins that exception as intentional.
- """
- from tools.environments.local import build_subprocess_env
- base = {
- "PATH": "/usr/bin:/bin",
- "HOME": "/home/user",
- "PYTHONHOME": "/opt/hermes-venv",
- "VIRTUAL_ENV": "/opt/hermes-venv",
- "SERVICE_TOKEN": "s3cr3t",
- }
- result = build_subprocess_env(base, scrub_secrets=False)
- assert result.get("PYTHONHOME") == "/opt/hermes-venv"
- assert result.get("VIRTUAL_ENV") == "/opt/hermes-venv"
- assert result.get("SERVICE_TOKEN") == "s3cr3t"
-
-
-class TestProfileScopedPassthrough:
- def test_make_run_env_uses_active_profile_for_passthrough(self, monkeypatch):
- """Allowlisted values must come from the routed profile, not os.environ."""
- from agent import secret_scope as ss
- from tools.env_passthrough import clear_env_passthrough, register_env_passthrough
- from tools.environments.local import _make_run_env
-
- clear_env_passthrough()
- register_env_passthrough(["SERVICE_TOKEN"])
- monkeypatch.setenv("SERVICE_TOKEN", "token-for-default")
- ss.set_multiplex_active(True)
- token = ss.set_secret_scope({"SERVICE_TOKEN": "token-for-routed-profile"})
- try:
- result = _make_run_env({})
- finally:
- ss.reset_secret_scope(token)
- ss.set_multiplex_active(False)
- clear_env_passthrough()
-
- assert result["SERVICE_TOKEN"] == "token-for-routed-profile"
-
- def test_make_run_env_omits_missing_scoped_passthrough(self, monkeypatch):
- """A missing routed secret must not fall back to the default profile."""
- from agent import secret_scope as ss
- from tools.env_passthrough import clear_env_passthrough, register_env_passthrough
- from tools.environments.local import _make_run_env
-
- clear_env_passthrough()
- register_env_passthrough(["SERVICE_TOKEN"])
- monkeypatch.setenv("SERVICE_TOKEN", "token-for-default")
- ss.set_multiplex_active(True)
- token = ss.set_secret_scope({})
- try:
- result = _make_run_env({})
- finally:
- ss.reset_secret_scope(token)
- ss.set_multiplex_active(False)
- clear_env_passthrough()
-
- assert "SERVICE_TOKEN" not in result
-
-
-class TestBlocklistCoverage:
- """Sanity checks that the blocklist covers all known providers."""
-
- def test_issue_1002_offenders(self):
- """Blocklist includes the main offenders from issue #1002."""
- must_block = {
- "OPENAI_BASE_URL",
- "OPENAI_API_KEY",
- "OPENROUTER_API_KEY",
- "ANTHROPIC_API_KEY",
- "LLM_MODEL",
- }
- assert must_block.issubset(_HERMES_PROVIDER_ENV_BLOCKLIST)
-
- def test_registry_vars_are_in_blocklist(self):
- """Every api_key_env_var and base_url_env_var from PROVIDER_REGISTRY
- must appear in the blocklist — ensures no drift.
-
- CLAUDE_CODE_OAUTH_TOKEN is the one deliberate exemption: it is owned
- by the user's Claude Code install, not Hermes (#55878).
- """
- from hermes_cli.auth import PROVIDER_REGISTRY
-
- exempt = {"CLAUDE_CODE_OAUTH_TOKEN"}
- for pconfig in PROVIDER_REGISTRY.values():
- for var in pconfig.api_key_env_vars:
- if var in exempt:
- continue
- assert var in _HERMES_PROVIDER_ENV_BLOCKLIST, (
- f"Registry var {var} (provider={pconfig.id}) missing from blocklist"
- )
- if pconfig.base_url_env_var:
- assert pconfig.base_url_env_var in _HERMES_PROVIDER_ENV_BLOCKLIST, (
- f"Registry base_url_env_var {pconfig.base_url_env_var} "
- f"(provider={pconfig.id}) missing from blocklist"
- )
-
- def test_bedrock_bearer_token_is_in_blocklist(self):
- """auth_type='aws_sdk' providers contribute their Hermes-managed
- inference token (the Bedrock bearer) to the blocklist, keyed off
- auth_type so any future SDK-cred provider is covered automatically."""
- assert "AWS_BEARER_TOKEN_BEDROCK" in _HERMES_PROVIDER_ENV_BLOCKLIST
-
- def test_general_aws_chain_not_in_blocklist(self):
- """The general AWS credential chain must NOT be in the blocklist —
- no-regression guard for #32314. These belong to the user's trusted
- operator shell (SECURITY.md §3.2), not to Hermes, and blocklisting
- them would be unrecoverable via env_passthrough (GHSA-rhgp-j443-p4rf).
- """
- general_chain = {
- "AWS_ACCESS_KEY_ID",
- "AWS_SECRET_ACCESS_KEY",
- "AWS_SESSION_TOKEN",
- "AWS_PROFILE",
- "AWS_DEFAULT_REGION",
- "AWS_REGION",
- "AWS_SHARED_CREDENTIALS_FILE",
- "AWS_CONFIG_FILE",
- "AWS_WEB_IDENTITY_TOKEN_FILE",
- "AWS_ROLE_ARN",
- }
- leaked_block = general_chain & _HERMES_PROVIDER_ENV_BLOCKLIST
- assert not leaked_block, (
- f"General AWS chain vars must stay inheritable, but these are "
- f"blocklisted: {sorted(leaked_block)} (capability regression, #32314)"
- )
-
- def test_extra_auth_vars_covered(self):
- """Non-registry auth vars (ANTHROPIC_TOKEN) must also be in the
- blocklist."""
- extras = {"ANTHROPIC_TOKEN"}
- assert extras.issubset(_HERMES_PROVIDER_ENV_BLOCKLIST)
-
- def test_claude_code_oauth_token_is_inheritable(self):
- """CLAUDE_CODE_OAUTH_TOKEN is owned by the user's Claude Code install
- (subscription OAuth), not a Hermes inference credential. Stripping it
- made agent-spawned ``claude`` fall through to the shared Keychain /
- ~/.claude credential store and clobber the user's interactive login
- on auth failure (#55878). It must stay inheritable."""
- assert "CLAUDE_CODE_OAUTH_TOKEN" not in _HERMES_PROVIDER_ENV_BLOCKLIST
-
- def test_non_registry_provider_vars_are_in_blocklist(self):
- extras = {
- "GOOGLE_API_KEY",
- "DEEPSEEK_API_KEY",
- "MISTRAL_API_KEY",
- "GROQ_API_KEY",
- "TOGETHER_API_KEY",
- "PERPLEXITY_API_KEY",
- "COHERE_API_KEY",
- "FIREWORKS_API_KEY",
- "XAI_API_KEY",
- "HELICONE_API_KEY",
- }
- assert extras.issubset(_HERMES_PROVIDER_ENV_BLOCKLIST)
-
- def test_optional_tool_and_messaging_vars_are_in_blocklist(self):
- """Tool/messaging vars from OPTIONAL_ENV_VARS should stay covered."""
- from hermes_cli.config import OPTIONAL_ENV_VARS
-
- for name, metadata in OPTIONAL_ENV_VARS.items():
- category = metadata.get("category")
- if category in {"tool", "messaging"}:
- assert name in _HERMES_PROVIDER_ENV_BLOCKLIST, (
- f"Optional env var {name} (category={category}) missing from blocklist"
- )
- elif category == "setting" and metadata.get("password"):
- assert name in _HERMES_PROVIDER_ENV_BLOCKLIST, (
- f"Secret setting env var {name} missing from blocklist"
- )
-
- def test_gateway_runtime_vars_are_in_blocklist(self):
- extras = {
- "TELEGRAM_HOME_CHANNEL",
- "TELEGRAM_HOME_CHANNEL_NAME",
- "DISCORD_HOME_CHANNEL",
- "DISCORD_HOME_CHANNEL_NAME",
- "DISCORD_REQUIRE_MENTION",
- "DISCORD_FREE_RESPONSE_CHANNELS",
- "DISCORD_AUTO_THREAD",
- "SLACK_HOME_CHANNEL",
- "SLACK_HOME_CHANNEL_NAME",
- "SLACK_ALLOWED_USERS",
- "WHATSAPP_ENABLED",
- "WHATSAPP_MODE",
- "WHATSAPP_ALLOWED_USERS",
- "SIGNAL_HTTP_URL",
- "SIGNAL_ACCOUNT",
- "SIGNAL_ALLOWED_USERS",
- "SIGNAL_GROUP_ALLOWED_USERS",
- "SIGNAL_HOME_CHANNEL",
- "SIGNAL_HOME_CHANNEL_NAME",
- "SIGNAL_IGNORE_STORIES",
- "HASS_TOKEN",
- "HASS_URL",
- "EMAIL_ADDRESS",
- "EMAIL_PASSWORD",
- "EMAIL_IMAP_HOST",
- "EMAIL_SMTP_HOST",
- "EMAIL_HOME_ADDRESS",
- "EMAIL_HOME_ADDRESS_NAME",
- "HERMES_DASHBOARD_SESSION_TOKEN",
- "GATEWAY_ALLOWED_USERS",
- "GH_TOKEN",
- "GITHUB_APP_ID",
- "GITHUB_APP_PRIVATE_KEY_PATH",
- "GITHUB_APP_INSTALLATION_ID",
- "MODAL_TOKEN_ID",
- "MODAL_TOKEN_SECRET",
- "DAYTONA_API_KEY",
- "VERCEL_OIDC_TOKEN",
- "VERCEL_TOKEN",
- "VERCEL_PROJECT_ID",
- "VERCEL_TEAM_ID",
- }
- assert extras.issubset(_HERMES_PROVIDER_ENV_BLOCKLIST)
-
-
-class TestSanePathIncludesHomebrew:
- """Verify _SANE_PATH includes macOS Homebrew directories."""
-
- @pytest.fixture(autouse=True)
- def _disable_hermes_bin_injection(self):
- """These tests assert the sane-path merge in isolation. Disable the
- hermes-install-dir prepend (a separate concern, covered by
- TestHermesBinDirOnPath) so a real ``hermes`` on the test runner's PATH
- doesn't shift the asserted PATH layout."""
- from tools.environments import local as local_mod
- saved = local_mod._HERMES_BIN_DIR
- local_mod._HERMES_BIN_DIR = None # resolved -> no dir to inject
- yield
- local_mod._HERMES_BIN_DIR = saved
-
- def test_sane_path_includes_homebrew_bin(self):
- from tools.environments.local import _SANE_PATH
- assert "/opt/homebrew/bin" in _SANE_PATH
-
-
- def test_make_run_env_appends_homebrew_on_minimal_path(self, monkeypatch):
- """When PATH is minimal, _make_run_env appends missing sane entries.
-
- POSIX: the sane-path merge appends the Homebrew dirs. Windows:
- _append_missing_sane_path_entries is a documented passthrough (the
- native PATH must not be touched), so the assertion is the unchanged
- input. Git Bash dir prepending is neutralised so the merged PATH
- layout is deterministic on every host.
- """
- from tools.environments import local as local_mod
- from tools.environments.local import _SANE_PATH, _make_run_env
- monkeypatch.setattr(local_mod, "_git_bash_bin_dirs", lambda: [])
- minimal_env = {"PATH": "/some/custom/bin"}
- with patch.dict(os.environ, minimal_env, clear=True):
- result = _make_run_env({})
- path_entries = result["PATH"].split(os.pathsep)
- assert path_entries[0] == "/some/custom/bin"
- if sys.platform == "win32":
- assert result["PATH"] == "/some/custom/bin"
- else:
- for entry in _SANE_PATH.split(os.pathsep):
- assert entry in path_entries
-
-
@pytest.mark.platforms("macos")
def test_make_run_env_real_launchd_path_gains_homebrew(self):
"""The literal macOS launchd PATH is the production trigger for #35613.
@@ -1646,164 +431,3 @@ class TestSanePathIncludesHomebrew:
result = _make_run_env({})
assert result["Path"] == windows_env["Path"]
assert "PATH" not in result
-
-
-class TestHermesBinDirOnPath:
- """The hermes install dir is reachable in the terminal subshell PATH.
-
- Plugins shelling out to bare ``hermes`` via the terminal tool must work
- even when the gateway was launched without the hermes install dir on
- PATH (systemd, service managers, cron). See the discussion that motivated
- _resolve_hermes_bin_dir / _prepend_hermes_bin_dir.
- """
-
- def _reset_cache(self):
- from tools.environments import local as local_mod
- local_mod._HERMES_BIN_DIR = local_mod._SENTINEL
-
- def test_resolves_via_which(self, monkeypatch):
- from tools.environments import local as local_mod
- self._reset_cache()
- monkeypatch.setattr(local_mod.shutil, "which",
- lambda name: "/opt/hermes/bin/hermes" if name == "hermes" else None)
- monkeypatch.setattr(local_mod.os.path, "isdir", lambda p: p == "/opt/hermes/bin")
- assert local_mod._resolve_hermes_bin_dir() == "/opt/hermes/bin"
-
-
- def test_prepend_noop_when_unresolved(self, monkeypatch):
- from tools.environments import local as local_mod
- self._reset_cache()
- local_mod._HERMES_BIN_DIR = None
- assert local_mod._prepend_hermes_bin_dir("/usr/bin:/bin") == "/usr/bin:/bin"
-
- def test_make_run_env_injects_hermes_bin_dir(self):
- """A gateway env missing the hermes dir gets it back in the subshell PATH.
-
- Platform-agnostic: ``_prepend_hermes_bin_dir`` uses ``os.pathsep`` on
- every host, so no platform flag is faked here."""
- from tools.environments import local as local_mod
- from tools.environments.local import _make_run_env
- self._reset_cache()
- local_mod._HERMES_BIN_DIR = "/opt/hermes/bin"
- with patch.dict(
- os.environ,
- {"PATH": os.pathsep.join(["/usr/bin", "/bin"])},
- clear=True,
- ):
- result = _make_run_env({})
- entries = result["PATH"].split(os.pathsep)
- assert entries[0] == "/opt/hermes/bin"
- assert "/usr/bin" in entries
-
-
-class TestHermesInternalDynamicSecrets:
- """Dynamically-named Hermes secrets injected at gateway/CLI startup must
- not leak into terminal subprocesses.
-
- The static ``_HERMES_PROVIDER_ENV_BLOCKLIST`` is name-based and derived
- from provider/tool registries, so it cannot enumerate:
-
- - ``AUXILIARY_<TASK>_API_KEY`` / ``AUXILIARY_<TASK>_BASE_URL`` — per-task
- side-LLM credentials bridged from ``config.yaml[auxiliary]`` by
- ``gateway/run.py`` and ``cli.py``.
- - ``GATEWAY_RELAY_*_SECRET`` / ``_KEY`` / ``_TOKEN`` — relay-auth material
- provisioned by ``gateway/relay``.
-
- ``_is_hermes_internal_secret`` is the single source of truth; every spawn
- path (``_sanitize_subprocess_env``, ``_make_run_env``,
- ``hermes_subprocess_env``, Docker forward filter, ``env_passthrough``)
- consults it. These tests exercise the terminal execute path + predicate.
- """
-
- def test_predicate_matches_auxiliary_api_key(self):
- from tools.environments.local_env_policy import _is_hermes_internal_secret
- assert _is_hermes_internal_secret("AUXILIARY_VISION_API_KEY")
- assert _is_hermes_internal_secret("AUXILIARY_WEB_EXTRACT_API_KEY")
- assert _is_hermes_internal_secret("AUXILIARY_APPROVAL_API_KEY")
- # plugin-registered task names are covered by the pattern
- assert _is_hermes_internal_secret("AUXILIARY_MY_PLUGIN_TASK_API_KEY")
-
- def test_predicate_matches_auxiliary_base_url(self):
- from tools.environments.local_env_policy import _is_hermes_internal_secret
- assert _is_hermes_internal_secret("AUXILIARY_VISION_BASE_URL")
- assert _is_hermes_internal_secret("AUXILIARY_COMPRESSION_BASE_URL")
-
- def test_predicate_matches_gateway_relay_auth(self):
- from tools.environments.local_env_policy import _is_hermes_internal_secret
- assert _is_hermes_internal_secret("GATEWAY_RELAY_SECRET")
- assert _is_hermes_internal_secret("GATEWAY_RELAY_DELIVERY_KEY")
- assert _is_hermes_internal_secret("GATEWAY_RELAY_SESSION_TOKEN")
-
- def test_predicate_allows_auxiliary_non_secrets(self):
- """AUXILIARY_*_PROVIDER / _MODEL and GATEWAY_RELAY_* routing hints are
- NOT secrets and must remain visible so tooling that reads them works."""
- from tools.environments.local_env_policy import _is_hermes_internal_secret
- assert not _is_hermes_internal_secret("AUXILIARY_VISION_PROVIDER")
- assert not _is_hermes_internal_secret("AUXILIARY_VISION_MODEL")
- assert not _is_hermes_internal_secret("GATEWAY_RELAY_URL")
- assert not _is_hermes_internal_secret("GATEWAY_RELAY_PLATFORMS")
- assert not _is_hermes_internal_secret("GATEWAY_RELAY_ID") # not a secret suffix
- # unrelated vars pass through
- assert not _is_hermes_internal_secret("PATH")
- assert not _is_hermes_internal_secret("MY_APP_KEY")
-
- def test_auxiliary_secrets_stripped_from_subprocess(self):
- """AUXILIARY_*_API_KEY / _BASE_URL injected into os.environ must not
- reach the terminal subprocess, while _PROVIDER / _MODEL survive."""
- result_env = _run_with_env(extra_os_env={
- "AUXILIARY_VISION_API_KEY": "sk-vision-secret",
- "AUXILIARY_VISION_BASE_URL": "http://internal:1234/v1",
- "AUXILIARY_WEB_EXTRACT_API_KEY": "sk-webx-secret",
- "AUXILIARY_VISION_PROVIDER": "openai",
- "AUXILIARY_VISION_MODEL": "gpt-4o",
- })
- assert "AUXILIARY_VISION_API_KEY" not in result_env
- assert "AUXILIARY_VISION_BASE_URL" not in result_env
- assert "AUXILIARY_WEB_EXTRACT_API_KEY" not in result_env
- # Non-secret routing config is preserved.
- assert result_env.get("AUXILIARY_VISION_PROVIDER") == "openai"
- assert result_env.get("AUXILIARY_VISION_MODEL") == "gpt-4o"
-
- def test_gateway_relay_secret_stripped_from_subprocess(self):
- result_env = _run_with_env(extra_os_env={
- "GATEWAY_RELAY_SECRET": "relay-signing-secret",
- "GATEWAY_RELAY_DELIVERY_KEY": "relay-delivery-key",
- "GATEWAY_RELAY_URL": "https://relay.example.com",
- })
- assert "GATEWAY_RELAY_SECRET" not in result_env
- assert "GATEWAY_RELAY_DELIVERY_KEY" not in result_env
- # Non-secret routing hint stays visible.
- assert result_env.get("GATEWAY_RELAY_URL") == "https://relay.example.com"
-
- def test_auxiliary_secret_stripped_even_when_passthrough_registered(self):
- """A skill registering AUXILIARY_*_API_KEY as env_passthrough must NOT
- be able to tunnel it into a subprocess — the strip is unconditional."""
- with patch(
- "tools.env_passthrough.is_env_passthrough",
- side_effect=lambda name: name == "AUXILIARY_VISION_API_KEY",
- ):
- result_env = _run_with_env(extra_os_env={
- "AUXILIARY_VISION_API_KEY": "sk-vision-secret",
- })
- assert "AUXILIARY_VISION_API_KEY" not in result_env
-
- def test_make_run_env_strips_internal_secrets(self):
- """The foreground _make_run_env path strips the same dynamic secrets."""
- from tools.environments.local import _make_run_env
- with patch.dict(os.environ, {
- "PATH": "/usr/bin:/bin",
- "AUXILIARY_VISION_API_KEY": "sk-secret",
- "GATEWAY_RELAY_SECRET": "relay-secret",
- "AUXILIARY_VISION_PROVIDER": "openai",
- }, clear=True):
- run_env = _make_run_env({})
- assert "AUXILIARY_VISION_API_KEY" not in run_env
- assert "GATEWAY_RELAY_SECRET" not in run_env
- assert run_env.get("AUXILIARY_VISION_PROVIDER") == "openai"
-
- def test_gateway_relay_static_names_in_blocklist(self):
- """The static relay names are also added to the name-based blocklist so
- the exact-match path catches them independently of the predicate."""
- assert "GATEWAY_RELAY_SECRET" in _HERMES_PROVIDER_ENV_BLOCKLIST
- assert "GATEWAY_RELAY_DELIVERY_KEY" in _HERMES_PROVIDER_ENV_BLOCKLIST
- assert "GATEWAY_RELAY_ID" in _HERMES_PROVIDER_ENV_BLOCKLIST