Skip to content

The agent that grows with you

fix(file_ops): vet the Delete/Move entry itself, not its parent directory

kshitijk4poora721612bfa9c
diff --git a/agent/file_safety.py b/agent/file_safety.py
index 29625939014..789cb3d7479 100644
--- a/agent/file_safety.py
+++ b/agent/file_safety.py
@@ -246,8 +246,12 @@ def build_write_approval_paths(home: str) -> set[str]:
_HERMES_PROTECTED_SUBPATHS = ("state.db", "sessions", "mcp-tokens", "pairing", "vault", "browser-profile")
-def _classify_write_denial(path: str) -> Optional[str]:
- """Return ``'credential'``, ``'safe_root'``, ``'nt_namespace'``, or ``None`` if writes are allowed."""
+def _classify_write_denial(path: str, *, entry: bool = False) -> Optional[str]:
+ """Return ``'credential'``, ``'safe_root'``, ``'nt_namespace'``, or ``None`` if writes are allowed.
+
+ ``entry=True`` is for ops that unlink/rename the directory entry itself (a
+ symlink, not its target): the entry — parent realpath'd, final component
+ kept — is vetted as well as the target it resolves to."""
# NT/device-namespace check runs on the RAW string, before realpath():
# resolving such a path is itself the NTLM-leak trigger, and namespace
# prefixes defeat string-prefix denylist comparison after normalization.
@@ -260,10 +264,18 @@ def _classify_write_denial(path: str) -> Optional[str]:
# BEFORE the approval-gated allow so ~/.ssh-style gating cannot re-open it.
from agent.runtime_self_protection import is_protected_path
- runtime_hit = is_protected_path(path)
- if runtime_hit:
+ if is_protected_path(path) or (entry and is_protected_path(path, follow=False)):
return "credential"
+ denial = _classify_resolved_write_denial(homes, resolved)
+ if denial or not entry:
+ return denial
+ expanded = os.path.expanduser(str(path))
+ entry_path = os.path.join(os.path.realpath(os.path.dirname(expanded) or "."), os.path.basename(expanded))
+ return _classify_resolved_write_denial(homes, entry_path)
+
+def _classify_resolved_write_denial(homes: set[str], resolved: str) -> Optional[str]:
+ """Credential / protected-subpath / safe-root verdict for an already-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 any(resolved in build_write_approval_paths(home) for home in homes):
@@ -294,9 +306,10 @@ def is_write_denied(path: str) -> bool:
return _classify_write_denial(path) is not None
-def get_write_denied_error(path: str, *, verb: str = "Write") -> Optional[str]:
- """Return a user/model-facing error when writes to ``path`` are blocked."""
- denial = _classify_write_denial(path)
+def get_write_denied_error(path: str, *, verb: str = "Write", entry: bool = False) -> Optional[str]:
+ """Return a user/model-facing error when writes to ``path`` are blocked
+ (``entry``: see :func:`_classify_write_denial`)."""
+ denial = _classify_write_denial(path, entry=entry)
if denial == "safe_root":
roots_display = os.pathsep.join(sorted(get_safe_write_roots()))
return (
diff --git a/agent/runtime_self_protection.py b/agent/runtime_self_protection.py
index fb521131acc..d6917d3a120 100644
--- a/agent/runtime_self_protection.py
+++ b/agent/runtime_self_protection.py
@@ -151,9 +151,14 @@ def _overlaps(a: str, b: str) -> bool:
return a == b or a.startswith(b + sep) or b.startswith(a + sep)
-def is_protected_path(path: str) -> Optional[str]:
- """Description of the protected runtime path ``path`` touches, else ``None``."""
- resolved = _normalize_path(path)
+def is_protected_path(path: str, *, follow: bool = True) -> Optional[str]:
+ """Description of the protected runtime path ``path`` touches, else ``None``.
+
+ ``follow=False`` keeps the final component unresolved (the entry itself, for
+ ops that unlink/rename a symlink rather than its target)."""
+ resolved = _normalize_path(path) if follow else _normalize_path(os.path.dirname(path) or ".")
+ if resolved and not follow:
+ resolved = os.path.join(resolved, os.path.basename(path))
if not resolved:
return None
for protected, description in _protected():
diff --git a/tests/tools/test_file_operations_delete.py b/tests/tools/test_file_operations_delete.py
index 87dc97d461c..b76d091ff25 100644
--- a/tests/tools/test_file_operations_delete.py
+++ b/tests/tools/test_file_operations_delete.py
@@ -5,6 +5,9 @@ is refused (``is a directory``), never silently removed — no recursive delete
exists on this interface.
"""
+import os
+import sys
+
import pytest
from tools.environments.local import LocalEnvironment
@@ -37,3 +40,35 @@ def test_delete_file_refuses_directory(ops, tmp_path):
assert result.error is not None
assert "is a directory" in result.error
assert target.exists()
+
+
[email protected]("op", ["delete", "move"])
[email protected]("layout", ["beside_runtime_venv", "link_in_credential_dir"])
+def test_delete_and_move_guard_the_entry_itself(ops, tmp_path, monkeypatch, op, layout):
+ """Delete/Move vet the directory entry (parent resolved, leaf kept): a plain file whose
+ directory merely CONTAINS the runtime venv (``~/notes.txt``) stays deletable/movable,
+ while a link directly inside a credential dir is refused even though it points outside."""
+ home, outside = tmp_path / "home", tmp_path / "outside.txt"
+ outside.write_text("keep", encoding="utf-8")
+ monkeypatch.setenv("HOME", str(home))
+ if layout == "beside_runtime_venv":
+ (home / ".venv").mkdir(parents=True)
+ monkeypatch.setattr(sys, "prefix", str(home / ".venv"))
+ entry = home / "plain.txt"
+ entry.write_text("x", encoding="utf-8")
+ else:
+ (home / ".ssh").mkdir(parents=True)
+ entry = home / ".ssh" / "link"
+ entry.symlink_to(outside)
+ moved = home / "moved.txt"
+
+ result = ops.delete_file(str(entry)) if op == "delete" else ops.move_file(str(entry), str(moved))
+
+ if layout == "beside_runtime_venv":
+ assert result.error is None, result.error
+ assert not os.path.lexists(entry) and moved.exists() == (op == "move")
+ else:
+ assert result.error and "protected" in result.error, result.error
+ assert entry.is_symlink() and not os.path.lexists(moved)
+ assert outside.read_text(encoding="utf-8-sig") == "keep"
diff --git a/tools/file_operations.py b/tools/file_operations.py
index 7f87aa7d5d3..98ea6b9c266 100644
--- a/tools/file_operations.py
+++ b/tools/file_operations.py
@@ -1252,12 +1252,10 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
so one code path works on local/docker/ssh AND Windows shells (no ``rm``)."""
path = self._expand_path(path)
# Delete removes the directory entry (a symlink itself, not its target), so
- # the guards also run on the entry's directory; realpath(path) alone would
- # clear a link outside the safe root that points inside it.
- for p in (path, os.path.dirname(path) or "."):
- denied = get_write_denied_error(p, verb="Delete")
- if denied:
- return WriteResult(error=denied)
+ # the guards vet the entry as well as the target it resolves to.
+ denied = get_write_denied_error(path, verb="Delete", entry=True)
+ if denied:
+ return WriteResult(error=denied)
# Path baked in via repr() for shell-independent quoting; no
# ``unlink(missing_ok=True)`` (a 3.7 remote interpreter lacks it).
snippet = (
@@ -1292,9 +1290,9 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
def move_file(self, src: str, dst: str) -> WriteResult:
src = self._expand_path(src)
dst = self._expand_path(dst)
- # Entry-level op like delete_file: guard both entries' directories too.
- for p in (src, dst, os.path.dirname(src) or ".", os.path.dirname(dst) or "."):
- denied = get_write_denied_error(p, verb="Move")
+ # Entry-level op like delete_file: vet both entries, not just their targets.
+ for p in (src, dst):
+ denied = get_write_denied_error(p, verb="Move", entry=True)
if denied:
return WriteResult(error=denied)
result = self._exec(f"mv {self._escape_shell_arg(src)} {self._escape_shell_arg(dst)}")