The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(file-safety): approval-gate ~/.ssh/config writes instead of hard-denying (#84663)
Teknium62a9c0f0e99a
diff --git a/agent/copilot_acp_client.py b/agent/copilot_acp_client.pyindex 9cbdcd34944..021326c47dc 100644--- a/agent/copilot_acp_client.py+++ b/agent/copilot_acp_client.py@@ -26,7 +26,7 @@ from openai.types.chat.chat_completion_message_tool_call import (Function,)-from agent.file_safety import get_read_block_error, get_write_denied_error+from agent.file_safety import get_read_block_error, get_write_denied_error, is_write_approval_requiredfrom agent.redact import redact_sensitive_textfrom tools.environments.local import hermes_subprocess_env@@ -735,6 +735,14 @@ class CopilotACPClient:denied = get_write_denied_error(str(path))if denied:raise PermissionError(denied)+ # Approval-gated paths (e.g. ~/.ssh/config) are not hard-denied+ # for interactive tools, but the ACP shim has no human channel+ # to confirm the write — fail closed here.+ if is_write_approval_required(str(path)):+ raise PermissionError(+ f"Write denied: '{path}' requires interactive approval "+ "and cannot be written through the ACP file bridge."+ )path.parent.mkdir(parents=True, exist_ok=True)path.write_text(str(params.get("content") or ""), encoding="utf-8")response = {diff --git a/agent/file_safety.py b/agent/file_safety.pyindex 2e08db3d022..7547000fa46 100644--- a/agent/file_safety.py+++ b/agent/file_safety.py@@ -35,7 +35,17 @@ def build_write_denied_paths(home: str) -> set[str]:os.path.join(home, ".ssh", "authorized_keys"),os.path.join(home, ".ssh", "id_rsa"),os.path.join(home, ".ssh", "id_ed25519"),- os.path.join(home, ".ssh", "config"),+ # NOTE: ``~/.ssh/config`` is deliberately NOT hard-denied here.+ # It carries no private-key bytes and editing it (host aliases,+ # ProxyJump, VS Code Remote-SSH targets) is a routine, expected+ # task. Free-writing it is still wrong -- it can carry+ # ProxyCommand / Match exec directives -- so it is routed through+ # an approval gate in tools/file_tools.py instead (the same+ # approve-once/session/always flow the terminal tool already uses+ # for ~/.ssh writes). See build_write_approval_paths() below and+ # _check_ssh_config_write() in tools/file_tools.py. Hard-denying+ # it while the terminal only *asked* was an inconsistency that+ # made writes look like they flip-flopped between denied and OK.# Active profile .env (or top-level .env when not in profile mode).str(hermes_home / ".env"),# Top-level .env, even when running under a profile — overwriting it@@ -98,11 +108,40 @@ def get_safe_write_roots() -> set[str]:return roots+def build_write_approval_paths(home: str) -> set[str]:+ """Return paths that require human APPROVAL to write, but are not+ hard-denied credentials.++ ``~/.ssh/config`` lives here: it is routine to edit (host aliases,+ ProxyJump, VS Code Remote-SSH targets) and holds no private-key bytes,+ but it CAN carry ``ProxyCommand`` / ``Match exec`` directives, so a+ free write is inappropriate. The interactive file tools gate these+ through an approve-once/session/always prompt (mirroring the terminal+ tool's existing ``~/.ssh`` write approval); non-interactive callers+ that cannot prompt (ACP shims, background jobs) treat an+ approval-required path as denied and fail closed.+ """+ return {+ os.path.realpath(p)+ for p in [+ os.path.join(home, ".ssh", "config"),+ ]+ }++def _classify_write_denial(path: str) -> Optional[str]:"""Return ``'credential'``, ``'safe_root'``, or ``None`` if writes are allowed."""home = os.path.realpath(os.path.expanduser("~"))resolved = os.path.realpath(os.path.expanduser(str(path)))+ # Approval-gated paths (e.g. ~/.ssh/config) are NOT hard-denied here:+ # they are allowed at this layer so the interactive file tools can run+ # their approval prompt, and only blocked for non-interactive callers+ # via get_write_approval_error(). Checked before the credential deny so+ # the ``.ssh/`` directory prefix below doesn't swallow the config file.+ if resolved in build_write_approval_paths(home):+ return None+if resolved in build_write_denied_paths(home):return "credential"for prefix in build_write_denied_prefixes(home):@@ -177,6 +216,20 @@ def get_write_denied_error(path: str, *, verb: str = "Write") -> Optional[str]:return f"{verb} denied: '{path}' is a protected system/credential file."+def is_write_approval_required(path: str) -> bool:+ """Return True if ``path`` is an approval-gated write target.++ These paths (currently ``~/.ssh/config``) are not credentials and are+ not hard-denied, but a write to them must be confirmed by a human+ because they can influence process execution (e.g. an SSH+ ``ProxyCommand``). Callers with an interactive/gateway channel should+ prompt; callers without one should treat this as a block (fail closed).+ """+ home = os.path.realpath(os.path.expanduser("~"))+ resolved = os.path.realpath(os.path.expanduser(str(path)))+ return resolved in build_write_approval_paths(home)++# Common secret-bearing project-local environment file basenames.# These are blocked because .env files routinely contain API keys,# database passwords, and other credentials.diff --git a/tests/tools/test_file_write_safety.py b/tests/tools/test_file_write_safety.pyindex 0f146641912..514aba33fbf 100644--- a/tests/tools/test_file_write_safety.py+++ b/tests/tools/test_file_write_safety.py@@ -23,6 +23,50 @@ class TestStaticDenyList:assert _is_write_denied("/etc/shadow") is True+class TestSshConfigApprovalGate:+ """~/.ssh/config is approval-gated, not hard-denied (private keys stay denied)."""++ def test_ssh_config_not_hard_denied(self):+ from agent.file_safety import is_write_denied++ # The client config carries no key material — it must NOT be in the+ # flat credential deny (it is routed through approval instead).+ assert is_write_denied(os.path.expanduser("~/.ssh/config")) is False++ def test_ssh_config_get_write_denied_error_is_none(self):+ from agent.file_safety import get_write_denied_error++ assert get_write_denied_error(os.path.expanduser("~/.ssh/config")) is None++ def test_ssh_config_is_approval_required(self):+ from agent.file_safety import is_write_approval_required++ assert is_write_approval_required(os.path.expanduser("~/.ssh/config")) is True++ def test_private_keys_still_hard_denied(self):+ from agent.file_safety import is_write_approval_required, is_write_denied++ for name in ("id_rsa", "id_ed25519", "authorized_keys"):+ p = os.path.expanduser(f"~/.ssh/{name}")+ assert is_write_denied(p) is True, name+ # A hard-denied credential is not merely approval-gated.+ assert is_write_approval_required(p) is False, name++ def test_other_ssh_dir_files_still_hard_denied(self):+ from agent.file_safety import is_write_denied++ # The ~/.ssh/ directory prefix deny still covers everything else,+ # e.g. a known_hosts or an arbitrary key file.+ assert is_write_denied(os.path.expanduser("~/.ssh/id_rsa.pub")) is True+ assert is_write_denied(os.path.expanduser("~/.ssh/secret_key")) is True++ def test_regular_file_not_approval_required(self, tmp_path: Path):+ from agent.file_safety import is_write_approval_required++ assert is_write_approval_required(str(tmp_path / "notes.txt")) is False+++class TestSafeWriteRoot:"""HERMES_WRITE_SAFE_ROOT should sandbox writes to a specific subtree."""diff --git a/tools/file_tools.py b/tools/file_tools.pyindex 096b2070e2d..0c13e87f69b 100644--- a/tools/file_tools.py+++ b/tools/file_tools.py@@ -955,6 +955,66 @@ def _check_protected_instruction_write(paths: list[str],return _request_protected_instruction_approval(reasons, task_id)+def _check_approval_required_write(paths: list[str],+ task_id: str = "default") -> str | None:+ """Gate a write/patch touching an approval-required path (``~/.ssh/config``).++ These paths are NOT credentials and NOT hard-denied, but a write must+ be confirmed by a human because they can steer process execution+ (an SSH ``ProxyCommand`` / ``Match exec``). Unlike the protected-+ instruction gate this is a routine, user-initiated edit, so the prompt+ offers once/session/always scopes and honors --yolo (the historical+ dangerous-command semantics) rather than always re-asking.++ Returns ``None`` when no target is approval-gated or the human+ approved; otherwise a BLOCKED error string. Fail-closed when no+ interactive/gateway channel exists (a background/ACP caller cannot+ consent on the user's behalf).+ """+ try:+ from agent.file_safety import is_write_approval_required+ except Exception:+ return None++ targets = [p for p in paths if is_write_approval_required(p)]+ if not targets:+ return None++ display_targets = ", ".join(dict.fromkeys(targets))+ description = (+ f"Write to SSH client config file(s): {display_targets}. "+ "The SSH config can carry ProxyCommand / Match exec directives that "+ "run commands, so writes require your approval."+ )+ blocked = (+ f"BLOCKED: write to SSH config file(s) ({display_targets}) "+ "{why} Do NOT retry it via another path (terminal, execute_code) "+ "without the user's explicit consent."+ )++ try:+ import tools.approval as _approval+ except Exception:+ return blocked.format(why="requires approval but the approval "+ "subsystem is unavailable.")++ result = _approval._run_approval_gate(+ pattern_key="ssh_config_write",+ description=description,+ display_target=f"<write to {display_targets}>",+ cron_deny_message=blocked.format(+ why="requires approval but this cron session denies it."),+ autoapprove_log_prefix="ssh_config_write",+ fail_closed_when_no_human=True,+ no_human_block_message=blocked.format(+ why="requires approval but no interactive user or gateway is "+ "present to approve it."),+ )+ if result.get("approved"):+ return None+ return result.get("message") or blocked.format(why="was denied.")++def _get_container_mirror_prefix_for_task(task_id: str = "default") -> str | None:"""Return the container-side Hermes mirror prefix for Docker file tools."""try:@@ -2117,6 +2177,9 @@ def write_file_tool(path: str, content: str, task_id: str = "default",protected_err = _check_protected_instruction_write([path], task_id)if protected_err:return tool_error(protected_err)+ approval_err = _check_approval_required_write([path], task_id)+ if approval_err:+ return tool_error(approval_err)if not cross_profile:cross_warning = _check_cross_profile_path(path, task_id)if cross_warning:@@ -2254,6 +2317,9 @@ def patch_tool(mode: str = "replace", path: str = None, old_string: str = None,protected_err = _check_protected_instruction_write(_paths_to_check, task_id)if protected_err:return tool_error(protected_err)+ approval_err = _check_approval_required_write(_paths_to_check, task_id)+ if approval_err:+ return tool_error(approval_err)try:# Resolve paths for locking. Ordered + deduplicated so concurrent# callers lock in the same order — prevents deadlock on overlappingdiff --git a/tools/tts_tool.py b/tools/tts_tool.pyindex 812afa909fa..9338afceda4 100644--- a/tools/tts_tool.py+++ b/tools/tts_tool.py@@ -3219,9 +3219,9 @@ def _text_to_speech_single(file_path = _configured_command_tts_output_path(file_path, command_provider_config)- from agent.file_safety import is_write_denied+ from agent.file_safety import is_write_approval_required, is_write_denied- if is_write_denied(str(file_path)):+ if is_write_denied(str(file_path)) or is_write_approval_required(str(file_path)):return json.dumps({"success": False,"error": (@@ -3578,8 +3578,8 @@ def text_to_speech_tool(base_path = _configured_command_tts_output_path(base_path, command_provider_config,)- from agent.file_safety import is_write_denied- if is_write_denied(str(base_path)):+ from agent.file_safety import is_write_approval_required, is_write_denied+ if is_write_denied(str(base_path)) or is_write_approval_required(str(base_path)):return json.dumps({"success": False,"error": (diff --git a/website/docs/user-guide/security.md b/website/docs/user-guide/security.mdindex 59fde9033a3..9818ffa9f4f 100644--- a/website/docs/user-guide/security.md+++ b/website/docs/user-guide/security.md@@ -284,7 +284,7 @@ These categories are always denied, even when `HERMES_WRITE_SAFE_ROOT` is unset:| Category | Examples ||----------|----------|-| OS credential stores | `~/.ssh/`, `~/.aws/`, `~/.kube/`, `/etc/sudoers`, `~/.netrc` |+| OS credential stores | `~/.ssh/` (keys, `authorized_keys`), `~/.aws/`, `~/.kube/`, `/etc/sudoers`, `~/.netrc` || Hermes credential stores | `auth.json`, `.env`, `.anthropic_oauth.json`, `mcp-tokens/`, `pairing/` under HERMES_HOME (active profile and global root) || Project secret files | `.env`, `.env.local`, `.env.production`, `.envrc` anywhere on disk |@@ -292,6 +292,16 @@ Sensitive paths inside the safe root are still blocked — pointing `HERMES_WRITSafe-root violations return `Write denied: '…' is outside HERMES_WRITE_SAFE_ROOT (…)`. Credential-path blocks use `Write denied: '…' is a protected system/credential file.`+**Exception — `~/.ssh/config` is approval-gated, not hard-blocked.** The SSH+*client config* holds no private-key material and editing it (host aliases,+`ProxyJump`, VS Code Remote-SSH targets) is a routine task, so `write_file` /+`patch` route it through the same approve-once/session/always prompt the+terminal tool already uses for `~/.ssh` writes — instead of the flat refusal+that used to apply. It can still carry `ProxyCommand` / `Match exec` directives+that run commands, so the write is never silent. Non-interactive callers (ACP+file bridge, background jobs with no human channel) fail closed. Private keys,+`authorized_keys`, and everything else under `~/.ssh/` remain hard-blocked.+### HERMES_WRITE_SAFE_ROOT (optional sandbox)When set, `write_file` and `patch` may only target paths inside the listed directory prefix(es). Anything outside is **hard-blocked** — not routed through dangerous-command approval.