Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions forks/hermes-agent/hermes_cli/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,10 @@ def _load_auth_store(auth_file: Optional[Path] = None) -> dict[str, Any]:
return _empty_auth_store()
try:
raw = json.loads(auth_file.read_text(encoding="utf-8-sig"))
except PermissionError as exc:
if exc.errno == errno.EPERM and os.environ.get("HERMES_SECRET_SANDBOX") == "1":
return _empty_auth_store()
raise
except OSError:
# Exists but unreadable (EMFILE, EACCES, EIO, stalled mount): contents are not bad, and this
# module read-modify-writes everywhere, so an empty store here is one _save_auth_store()
Expand Down
2 changes: 2 additions & 0 deletions forks/hermes-agent/hermes_cli/config_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,8 @@
# go first because n/nvm/asdf write PATH exports there without an interactivity guard. Turn
# off if an rc file misbehaves when sourced non-interactively (exits on TTY check).
"auto_source_bashrc": True,
# Hide local macOS terminal commands from Hermes credential files when sandbox-exec exists.
"sandbox_macos_secrets": True,
# The default sandbox for every container backend: the nikolaik/python-nodejs base
# (Python 3.13 / Node 26) plus a display stack, so Bot Screen, computer_use and the
# bot's browser run INSIDE the sandbox and the pane can watch them (see bot_desktop).
Expand Down
11 changes: 9 additions & 2 deletions forks/hermes-agent/hermes_cli/env_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import codecs
import errno
import io
import itertools
import logging
Expand Down Expand Up @@ -637,7 +638,9 @@ def _load_user_dotenv(path: Path, *, load_pass: int) -> bool:
be the only place the backend is set, and skipping it would run terminal commands on the host."""
try:
_load_dotenv_with_fallback(path, override=True, load_pass=load_pass)
except PermissionError:
except PermissionError as exc:
if exc.errno == errno.EPERM and os.environ.get("HERMES_SECRET_SANDBOX") == "1":
return False
from hermes_cli import managed_scope

if managed_scope.pinned_terminal_backend() is None:
Expand Down Expand Up @@ -722,7 +725,11 @@ def load_hermes_dotenv(
# the committed .env. override=False lets a systemd `EnvironmentFile=-…/.op.env` token win.
op_env = home_path / ".op.env"
if op_env.exists() and not os.environ.get("OP_SERVICE_ACCOUNT_TOKEN"):
_load_dotenv_with_fallback(op_env, override=False, load_pass=load_pass)
try:
_load_dotenv_with_fallback(op_env, override=False, load_pass=load_pass)
except PermissionError as exc:
if exc.errno != errno.EPERM or os.environ.get("HERMES_SECRET_SANDBOX") != "1":
raise

if project_env_path and project_env_path.exists():
_load_dotenv_with_fallback(project_env_path, override=not user_env.exists(), load_pass=load_pass)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,16 @@ def test_unparseable_json_still_degrades_and_preserves_a_copy(store_file):
def test_healthy_store_is_returned_unchanged(store_file):
result = auth._load_auth_store(store_file)
assert result["providers"]["nous"]["api_key"] == "secret"


@pytest.mark.parametrize("error", [errno.EPERM, errno.EACCES])
def test_sandboxed_auth_permission_error_returns_empty_only_for_eperm(store_file, monkeypatch, error):
from pathlib import Path

monkeypatch.setenv("HERMES_SECRET_SANDBOX", "1")
monkeypatch.setattr(Path, "read_text", _fail_read(PermissionError(error, "denied")))
if error == errno.EPERM:
assert auth._load_auth_store(store_file) == {"version": auth.AUTH_STORE_VERSION, "providers": {}}
else:
with pytest.raises(PermissionError):
auth._load_auth_store(store_file)
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""

import builtins
import errno
import io
import logging
import os
Expand Down Expand Up @@ -132,3 +133,46 @@ def test_reload_still_removes_keys_a_readable_env_dropped(monkeypatch):
assert reload_env() == 2
assert "OPENAI_API_KEY" not in os.environ
assert os.environ["ANTHROPIC_API_KEY"] == "from-file"


@pytest.mark.parametrize("sandboxed,error,ignored", [(True, errno.EPERM, True), (True, errno.EACCES, False),
(False, errno.EPERM, False)])
def test_sandboxed_user_dotenv_permission_error(monkeypatch, tmp_path, sandboxed, error, ignored):
from hermes_cli import env_loader

def deny(*args, **kwargs):
raise PermissionError(error, "denied")
monkeypatch.setattr(env_loader, "_load_dotenv_with_fallback", deny)
monkeypatch.setattr(managed_scope, "pinned_terminal_backend", lambda: None)
if sandboxed:
monkeypatch.setenv("HERMES_SECRET_SANDBOX", "1")
else:
monkeypatch.delenv("HERMES_SECRET_SANDBOX", raising=False)
if ignored:
assert env_loader._load_user_dotenv(tmp_path / ".env", load_pass=1) is False
else:
with pytest.raises(PermissionError):
env_loader._load_user_dotenv(tmp_path / ".env", load_pass=1)


@pytest.mark.parametrize("sandboxed,error,ignored", [(True, errno.EPERM, True), (True, errno.EACCES, False),
(False, errno.EPERM, False)])
def test_sandboxed_op_dotenv_permission_error(monkeypatch, tmp_path, sandboxed, error, ignored):
from hermes_cli import env_loader

op_env = tmp_path / ".op.env"
op_env.touch()
monkeypatch.delenv("OP_SERVICE_ACCOUNT_TOKEN", raising=False)
if sandboxed:
monkeypatch.setenv("HERMES_SECRET_SANDBOX", "1")
else:
monkeypatch.delenv("HERMES_SECRET_SANDBOX", raising=False)
def deny(path, **kwargs):
if path == op_env:
raise PermissionError(error, "denied")
monkeypatch.setattr(env_loader, "_load_dotenv_with_fallback", deny)
if ignored:
load_hermes_dotenv(hermes_home=tmp_path, load_external_secrets=False)
else:
with pytest.raises(PermissionError):
load_hermes_dotenv(hermes_home=tmp_path, load_external_secrets=False)
221 changes: 221 additions & 0 deletions forks/hermes-agent/tests/tools/test_local_macos_secret_sandbox.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
"""Local macOS terminal sandboxing hides only the Hermes credential files."""

from unittest.mock import patch

import pytest

from tools.environments import local


def test_profile_denies_each_secret_file_but_not_logs(tmp_path, monkeypatch):
home = tmp_path / ".hermes"
monkeypatch.setenv("HERMES_HOME", str(home))

profile = local._local_macos_secret_profile()

for name in (".env", "auth.json", ".rr-token"):
assert f'(deny file-read* file-write* file-link (literal "{(home / name).resolve()}"))' in profile
assert "(allow default)" in profile
assert str((home / "logs").resolve()) not in profile


def test_profile_denies_symlink_and_resolved_paths(tmp_path, monkeypatch):
real_home = tmp_path / "real"
real_home.mkdir()
home = tmp_path / "link"
home.symlink_to(real_home, target_is_directory=True)
monkeypatch.setenv("HERMES_HOME", str(home))

profile = local._local_macos_secret_profile()

for name in (".env", "auth.json", ".rr-token"):
for path in (home / name, real_home / name):
assert f'(deny file-read* file-write* file-link (literal "{path}"))' in profile
assert str(home / "logs") not in profile
assert str(real_home / "logs") not in profile


def test_wraps_argv_on_darwin_when_sandbox_exec_exists(monkeypatch):
monkeypatch.setattr(local.sys, "platform", "darwin")
original = ["/bin/bash", "-c", "echo hi"]
monkeypatch.setattr(local.os.path, "exists", lambda path: path == "/usr/bin/sandbox-exec")
monkeypatch.setattr(local, "_local_macos_secret_profile", lambda: "profile")
with patch("hermes_cli.config_effective.load_user_config_effective", return_value={"terminal": {}}):
wrapped = local._sandbox_local_macos_argv(original)

assert wrapped == ["/usr/bin/sandbox-exec", "-p", "profile", "/usr/bin/env", "HERMES_SECRET_SANDBOX=1", *original]


def test_leaves_argv_unchanged_on_other_platform(monkeypatch):
monkeypatch.setattr(local.sys, "platform", "linux")
original = ["/bin/bash", "-c", "echo hi"]

assert local._sandbox_local_macos_argv(original) is original


def test_leaves_argv_unchanged_when_sandbox_exec_is_missing(monkeypatch, caplog):
monkeypatch.setattr(local.sys, "platform", "darwin")
monkeypatch.setattr(local, "_sandbox_missing_warned", False)
original = ["/bin/bash", "-c", "echo hi"]
monkeypatch.setattr(local.os.path, "exists", lambda path: False)
with patch("hermes_cli.config_effective.load_user_config_effective", return_value={"terminal": {}}):
wrapped = local._sandbox_local_macos_argv(original)
local._sandbox_local_macos_argv(original)

assert wrapped is original
assert "sandbox-exec is unavailable" in caplog.text
assert caplog.text.count("sandbox-exec is unavailable") == 1


def test_leaves_argv_unchanged_when_config_disables_sandbox(monkeypatch):
monkeypatch.setattr(local.sys, "platform", "darwin")
original = ["/bin/bash", "-c", "echo hi"]
monkeypatch.setattr(local.os.path, "exists", lambda path: True)
with patch("hermes_cli.config_effective.load_user_config_effective", return_value={
"terminal": {"sandbox_macos_secrets": False},
}):
wrapped = local._sandbox_local_macos_argv(original)

assert wrapped is original


def test_sandbox_setting_defaults_on():
from hermes_cli.config_defaults import DEFAULT_CONFIG

assert DEFAULT_CONFIG["terminal"]["sandbox_macos_secrets"] is True


def test_local_environment_spawn_uses_sandbox_wrapper(monkeypatch, tmp_path):
monkeypatch.setattr(local.sys, "platform", "darwin")
env = local.LocalEnvironment.__new__(local.LocalEnvironment)
env.cwd = str(tmp_path)
env.env = {}
captured = {}

monkeypatch.setattr(local, "_find_bash", lambda: "/bin/bash")
monkeypatch.setattr(local, "_make_run_env", lambda _env: {})
monkeypatch.setattr(env, "_recover_cwd", lambda: None)

def fake_popen(args, **kwargs):
captured["args"] = args
class FakeProcess:
pid = 1
return FakeProcess()

monkeypatch.setattr(local.subprocess, "Popen", fake_popen)
monkeypatch.setattr(local, "own_process_groups", lambda _groups: None)
monkeypatch.setattr(local.os.path, "exists", lambda path: path == "/usr/bin/sandbox-exec")
with patch("hermes_cli.config_effective.load_user_config_effective", return_value={"terminal": {}}):
with patch("gateway.status.get_process_start_time", return_value=None):
env._run_bash("echo hi")

assert captured["args"][:2] == ["/usr/bin/sandbox-exec", "-p"]
assert captured["args"][-3:] == ["/bin/bash", "-c", "echo hi"]


@pytest.mark.parametrize("platform", ["darwin", "linux"])
@pytest.mark.parametrize("use_pty", [False, True])
def test_background_spawn_sandbox(platform, use_pty, monkeypatch, tmp_path):
from types import SimpleNamespace
from tools import process_registry as pr

registry = pr.ProcessRegistry()
session = pr.ProcessSession(id="proc_test", command="echo hi", task_id="test", cwd=str(tmp_path))
captured = {}
monkeypatch.setattr(local.sys, "platform", platform)
monkeypatch.setattr(local.os.path, "exists", lambda path: path == "/usr/bin/sandbox-exec")
monkeypatch.setattr(local, "_local_macos_secret_profile", lambda: "profile")
monkeypatch.setattr(pr, "_find_shell", lambda: "/bin/bash")
monkeypatch.setattr(pr, "_IS_LINUX", False)
monkeypatch.setattr(pr, "worker_output_log", lambda _id: None)
monkeypatch.setattr(registry, "_spawn_env", lambda _env: {})
monkeypatch.setattr(registry, "_track_started", lambda *args: None)
monkeypatch.setattr(registry, "_safe_host_start_time", lambda _pid: None)
monkeypatch.setattr(registry, "_own_pty_job", lambda *_args: None)

def capture(argv, **kwargs):
captured["argv"] = argv
return SimpleNamespace(pid=1234)

monkeypatch.setattr(registry, "_spawn_job", lambda _session, argv, _persist, **kwargs: capture(argv, **kwargs))
with patch("hermes_cli.config_effective.load_user_config_effective", return_value={"terminal": {}}):
with patch("ptyprocess.PtyProcess.spawn", side_effect=capture):
registry._spawn_local_admitted(session, "echo hi", {}, use_pty, False)

shell = ["/bin/bash", "-lic", "set +m; echo hi"]
expected = (["/usr/bin/sandbox-exec", "-p", "profile", "/usr/bin/env", "HERMES_SECRET_SANDBOX=1", *shell]
if platform == "darwin" else shell)
assert captured["argv"] == expected


def test_profile_covers_shared_credentials_root_and_writes(tmp_path, monkeypatch):
import json
from agent.file_safety import _CREDENTIAL_FILE_NAMES

root = tmp_path / 'José " space'
home = root / "profiles" / "nemo"
monkeypatch.setenv("HERMES_HOME", str(home))
profile = local._local_macos_secret_profile()
for path in [*(home / name for name in _CREDENTIAL_FILE_NAMES), home / ".op.env",
home / ".rr-token", root / "auth.json"]:
literal = json.dumps(str(path), ensure_ascii=False)
assert f"(deny file-read* file-write* file-link (literal {literal}))" in profile
for path in (home, *home.parents, home / "config.yaml"):
assert f"(deny file-write* (literal {json.dumps(str(path), ensure_ascii=False)}))" in profile
assert str(home / "logs") not in profile


def test_profile_denies_secret_directories_and_symlink_ancestors(tmp_path, monkeypatch):
real = tmp_path / "real"
real.mkdir()
alias = tmp_path / "alias"
alias.symlink_to(real, target_is_directory=True)
home = alias / "profiles" / "nemo"
monkeypatch.setenv("HERMES_HOME", str(home))
profile = local._local_macos_secret_profile()
for path in (home, *home.parents):
for spelling in (path, path.resolve()):
assert f'(deny file-write* (literal "{spelling}"))' in profile
for name in ("mcp-tokens", "vault", "browser-profile", "webapp"):
for path in (home / name, (home / name).resolve()):
assert f'(deny file-read* file-write* file-link (subpath "{path}"))' in profile


def test_profile_rejects_control_characters(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "bad\x01home"))
with pytest.raises(ValueError, match="control characters"):
local._local_macos_secret_profile()


def test_config_error_still_wraps(monkeypatch):
monkeypatch.setattr(local.sys, "platform", "darwin")
monkeypatch.setattr(local.os.path, "exists", lambda path: True)
monkeypatch.setattr(local, "_local_macos_secret_profile", lambda: "profile")
with patch("hermes_cli.config_effective.load_user_config_effective", side_effect=OSError):
assert local._sandbox_local_macos_argv(["shell"])[0:2] == ["/usr/bin/sandbox-exec", "-p"]


def test_kernel_spawn_uses_sandbox(monkeypatch, tmp_path):
from types import SimpleNamespace
from tools import code_kernel

monkeypatch.setattr(local.sys, "platform", "darwin")
monkeypatch.setattr(local.os.path, "exists", lambda path: path == "/usr/bin/sandbox-exec")
monkeypatch.setattr(local, "_local_macos_secret_profile", lambda: "profile")
monkeypatch.setattr(code_kernel.tempfile, "mkdtemp", lambda **kwargs: str(tmp_path))
monkeypatch.setattr(code_kernel, "_bind_rpc_socket", lambda kernel: "socket")
monkeypatch.setattr(code_kernel, "_ensure_background_reaper", lambda: None)
monkeypatch.setattr(code_kernel.threading, "Thread", lambda **kwargs: SimpleNamespace(start=lambda: None))
captured = {}
def spawn(argv, **kwargs):
captured["argv"] = argv
return SimpleNamespace(pid=1234)
monkeypatch.setattr("hermes_cli.process_identity.spawn_owned", spawn)
monkeypatch.setattr("tools.code_execution_env._build_child_env", lambda **kwargs: {})
monkeypatch.setattr("tools.code_execution_tool.generate_hermes_tools_module", lambda tools: "")
with patch("hermes_cli.config_effective.load_user_config_effective", return_value={"terminal": {}}):
code_kernel._spawn(code_kernel.SessionKernel(("test",)), child_python="/bin/python", child_cwd="",
sandbox_tools=frozenset(), max_tool_calls=1)
assert captured["argv"] == ["/usr/bin/sandbox-exec", "-p", "profile", "/usr/bin/env",
"HERMES_SECRET_SANDBOX=1", "/bin/python", str(tmp_path / "hermes_kernel_runner.py")]

4 changes: 3 additions & 1 deletion forks/hermes-agent/tools/code_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,7 @@ def _parent_process_handle(child_env: dict[str, str]):
def _spawn(kernel: SessionKernel, *, child_python: str, child_cwd: str,
sandbox_tools: frozenset, max_tool_calls: int, task_id: str = "") -> None:
from tools.code_execution_env import _build_child_env
from tools.environments.local import _sandbox_local_macos_argv
from tools.code_execution_tool import generate_hermes_tools_module
kernel.tmpdir = tempfile.mkdtemp(prefix="hermes_kernel_")
kernel.rpc_token = secrets.token_urlsafe(32)
Expand All @@ -596,7 +597,8 @@ def _spawn(kernel: SessionKernel, *, child_python: str, child_cwd: str,
from hermes_cli.process_identity import spawn_owned
try:
kernel.proc = spawn_owned(
[child_python, os.path.join(kernel.tmpdir, "hermes_kernel_runner.py")], purpose="code-kernel",
_sandbox_local_macos_argv([child_python, os.path.join(kernel.tmpdir, "hermes_kernel_runner.py")]),
purpose="code-kernel",
# Strict mode passes an empty cwd: the kernel's staging dir plays the per-call tmpdir's role.
cwd=child_cwd or kernel.tmpdir, env=child_env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE,
Expand Down
Loading
Loading