Skip to content

The agent that grows with you

fix(file-safety): anchor credential write guards to every home a write can land in

beardthelion7c478ac257a3
diff --git a/agent/file_safety.py b/agent/file_safety.py
index a06579802cb..d3a9ba924ac 100644
--- a/agent/file_safety.py
+++ b/agent/file_safety.py
@@ -74,6 +74,32 @@ def _home_and_resolved(path: str) -> tuple[str, str]:
return tuple(os.path.realpath(os.path.expanduser(p)) for p in ("~", str(path)))
+def _guard_homes(path: str = "") -> set[str]:
+ """Every home the write guards must cover. Process ``~`` alone is wrong whenever the
+ process HOME is not the OS user's real home — ``TERMINAL_HOME_MODE=profile``,
+ containers, and spawned workers pin ``HOME`` to ``{HERMES_HOME}/home``, which leaves
+ the real home's credential paths unguarded against absolute-path writes while file
+ tools happily write there (and ``_expand_tilde`` may route ``~`` to yet another
+ home). Deny/approval lists are built over the union: process home, real home,
+ subprocess home, and the profile home. A ``~name/...`` input resolves to a named
+ account's home, which joins the set so ``~root/.ssh/authorized_keys`` stays denied."""
+ homes = {os.path.expanduser("~")}
+ with suppress(Exception):
+ from hermes_constants import get_real_home, get_subprocess_home, _profile_home_path
+
+ for candidate in (get_real_home(), get_subprocess_home(), _profile_home_path()):
+ if candidate:
+ homes.add(str(candidate))
+ raw = str(path)
+ if len(raw) > 1 and raw.startswith("~") and raw[1] not in "/\\":
+ name = raw[1:].split("/", 1)[0].split("\\", 1)[0]
+ with suppress(Exception):
+ expanded = os.path.expanduser(f"~{name}")
+ if not expanded.startswith("~"):
+ homes.add(expanded)
+ return {os.path.realpath(h) for h in homes}
+
+
# ---------------------------------------------------------------------------
# Windows NT-namespace path guard
#
@@ -228,15 +254,18 @@ def _classify_write_denial(path: str) -> Optional[str]:
# prefixes defeat string-prefix denylist comparison after normalization.
if is_nt_namespace_path(path):
return "nt_namespace"
- home, resolved = _home_and_resolved(path)
+ _home, resolved = _home_and_resolved(path)
# Approval-gated paths are allowed at this layer so interactive tools can
# prompt; checked first so the ``.ssh/`` prefix deny doesn't swallow them.
- if resolved in build_write_approval_paths(home):
+ homes = _guard_homes(path)
+ if any(resolved in build_write_approval_paths(home) for home in homes):
return None
- if resolved in build_write_denied_paths(home) or any(
- resolved.startswith(prefix) for prefix in build_write_denied_prefixes(home)
+ if any(
+ resolved in build_write_denied_paths(home)
+ or any(resolved.startswith(prefix) for prefix in build_write_denied_prefixes(home))
+ for home in homes
):
return "credential"
@@ -275,8 +304,8 @@ def get_write_denied_error(path: str, *, verb: str = "Write") -> Optional[str]:
def is_write_approval_required(path: str) -> bool:
"""True if ``path`` is approval-gated (``~/.ssh/config``): interactive callers
prompt, callers without a channel treat it as a block (fail closed)."""
- home, resolved = _home_and_resolved(path)
- return resolved in build_write_approval_paths(home)
+ _home, resolved = _home_and_resolved(path)
+ return any(resolved in build_write_approval_paths(home) for home in _guard_homes(path))
# Secret-bearing project-local env file basenames, blocked anywhere on disk.
diff --git a/tests/agent/test_file_safety_write_credentials.py b/tests/agent/test_file_safety_write_credentials.py
index f3797d86c20..289f99477a0 100644
--- a/tests/agent/test_file_safety_write_credentials.py
+++ b/tests/agent/test_file_safety_write_credentials.py
@@ -55,3 +55,49 @@ def test_control_files_and_lookalikes_outside_home_stay_writable(hermes_layout,
assert fs.is_write_denied(str(_touch(base, rel))) is False, f"#45947 regression: {rel}"
assert fs.is_write_denied(str(_touch(tmp_path / "myproject", "cache/bws_cache.json"))) is False
assert fs.is_write_denied(str(_touch(tmp_path / "myproject", "vault/vault.key"))) is False
+
+
+class TestProfileHomeProcessHome:
+ """The write guard must cover the OS user's real home even when the process HOME is
+ pinned to ``{HERMES_HOME}/home`` (TERMINAL_HOME_MODE=profile / container / spawned
+ worker). Anchoring the deny and approval lists on ``expanduser("~")`` alone left the
+ real home's credential paths writable via absolute paths — while file tools resolve
+ ``~`` through ``get_subprocess_home()`` and can land a ``~``-spelled write on the real
+ home too."""
+
+ @pytest.fixture()
+ def profile_home_env(self, tmp_path, monkeypatch):
+ profile = tmp_path / "profile"
+ (profile / "home").mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(profile))
+ monkeypatch.setenv("HOME", str(profile / "home"))
+ monkeypatch.setattr(fs, "_hermes_home_path", lambda: profile)
+ monkeypatch.setattr(fs, "_hermes_root_path", lambda: profile.parent)
+ return profile
+
+ def test_real_home_credentials_denied(self, profile_home_env):
+ import pwd
+
+ real_home = Path(pwd.getpwuid(__import__("os").getuid()).pw_dir)
+ for rel in (".aws/credentials", ".ssh/id_ed25519", ".netrc", ".config/gh/hosts.yml"):
+ assert fs.is_write_denied(str(real_home / rel)), rel
+
+ def test_real_home_ssh_config_still_approval_gated(self, profile_home_env):
+ import pwd
+
+ real_home = Path(pwd.getpwuid(__import__("os").getuid()).pw_dir)
+ assert fs.is_write_approval_required(str(real_home / ".ssh" / "config"))
+
+ def test_profile_home_credentials_also_denied(self, profile_home_env):
+ """A pinned-HOME process still guards the profile home children see as ``~``."""
+ for rel in (".aws/credentials", ".ssh/id_rsa"):
+ assert fs.is_write_denied(str(profile_home_env / "home" / rel)), rel
+
+ def test_tilde_spelling_still_gated(self, profile_home_env):
+ assert fs.is_write_denied("~/.aws/credentials")
+ assert fs.is_write_approval_required("~/.ssh/config")
+
+ def test_benign_path_unaffected(self, profile_home_env, tmp_path):
+ benign = tmp_path / "scratch" / "notes.txt"
+ assert fs.is_write_denied(str(benign)) is False
+ assert fs.is_write_approval_required(str(benign)) is False
diff --git a/tests/tools/test_write_deny.py b/tests/tools/test_write_deny.py
index c71a509692e..a3aa346c1d3 100644
--- a/tests/tools/test_write_deny.py
+++ b/tests/tools/test_write_deny.py
@@ -1,10 +1,13 @@
"""Tests for _is_write_denied() — verifies deny list blocks sensitive paths on all platforms."""
+import json
import os
from pathlib import Path
from unittest.mock import patch
+import pytest
+
from agent.file_safety import is_write_denied as _is_write_denied
@@ -93,3 +96,64 @@ class TestWriteAllowed:
home = get_hermes_home()
for name in ["auth.json", "config.yaml", "webhook_subscriptions.json"]:
assert _is_write_denied(str(home / name)) is False, f"{name} should be writable"
+
+
+class TestProfileHomeE2E:
+ """End-to-end through ``write_file_tool``: with the process HOME pinned to
+ ``{HERMES_HOME}/home`` (TERMINAL_HOME_MODE=profile / container / spawned worker),
+ a write aimed at the OS user's real home must still hit the credential guards —
+ before the fix, absolute real-home paths sailed through untouched."""
+
+ @pytest.fixture()
+ def pinned_profile_home(self, tmp_path, monkeypatch):
+ profile = tmp_path / "profile"
+ (profile / "home").mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(profile))
+ monkeypatch.setenv("HOME", str(profile / "home"))
+ return profile
+
+ @staticmethod
+ def _real_home() -> Path:
+ import pwd
+
+ return Path(pwd.getpwuid(os.getuid()).pw_dir)
+
+ def test_absolute_real_home_write_denied_end_to_end(self, pinned_profile_home):
+ from tools.file_tools import write_file_tool
+
+ target = self._real_home() / ".ssh" / "e2e_guard_probe_key"
+ assert not target.exists()
+ try:
+ result = json.loads(write_file_tool(str(target), "not-a-key"))
+ assert result.get("error"), f"write slipped through: {result}"
+ assert not target.exists()
+ finally:
+ target.unlink(missing_ok=True)
+
+ def test_tilde_write_denied_end_to_end(self, pinned_profile_home):
+ """``~`` resolves to the real home via _expand_tilde's repair — and is denied."""
+ from tools.file_tools import write_file_tool
+
+ target = self._real_home() / ".aws" / "e2e_guard_probe_credentials"
+ assert not target.exists()
+ try:
+ result = json.loads(write_file_tool("~/.aws/e2e_guard_probe_credentials", "x"))
+ assert result.get("error"), f"write slipped through: {result}"
+ assert not target.exists()
+ finally:
+ target.unlink(missing_ok=True)
+
+ def test_named_user_tilde_denied(self, pinned_profile_home):
+ """``~root/...`` resolves to another account's home — still a credential write."""
+ import agent.file_safety as fs
+ assert fs.is_write_denied("~root/.ssh/authorized_keys") is True
+ assert fs.is_write_denied("~nosuchuser-hopefully/.ssh/authorized_keys") is False
+
+ def test_benign_write_still_lands(self, pinned_profile_home, tmp_path):
+ from tools.file_tools import write_file_tool
+
+ target = tmp_path / "scratch" / "ok.txt"
+ target.parent.mkdir(parents=True)
+ result = json.loads(write_file_tool(str(target), "hello"))
+ assert not result.get("error"), result
+ assert target.read_text() == "hello"