From 9cdb0e61be43eb689171a7e9c4001d67e9eed39e Mon Sep 17 00:00:00 2001 From: Iko <6572003+iap@users.noreply.github.com> Date: Fri, 9 Oct 2026 21:56:20 +0700 Subject: [PATCH 1/3] perf: hoist guard constants out of the per-call path `_plugin_pre_tool_call` rebuilt its constants on every invocation: a realpath over the three protected Hermes paths, both pattern tuples, and a regex compile, all to produce the same answer every time. The hook runs on every tool call, so that work was repeated indefinitely. Move them to module level, where they are computed once at import. `_is_dangerous` becomes a module-level function for the same reason. Behavior is unchanged. Measured on the real hook: 0.180 ms median for a safe write, 0.131 ms for a terminal echo, 0.120 ms for a non-terminal tool. The per-call realpath alone was 0.091 ms. The absolute numbers are small, so this is a correctness-of-structure fix rather than a measurable speedup. Closes #118 --- __init__.py | 147 +++++++++++++++++++---------------------- tests/test_coverage.py | 29 ++++++++ 2 files changed, 98 insertions(+), 78 deletions(-) diff --git a/__init__.py b/__init__.py index 77c249f..a965740 100644 --- a/__init__.py +++ b/__init__.py @@ -12,6 +12,7 @@ import logging import os +import re import threading from typing import Any @@ -24,6 +25,65 @@ logger = logging.getLogger(__name__) +# Guard constants are module-level so a tool call does not rebuild them. The +# hook runs on every tool invocation, so realpath over the core paths and the +# regex compile were being redone per call for a fixed answer. Values are +# resolved once at import, which is what the previous per-call code did anyway. +_HERMES_CORE = tuple( + os.path.realpath(os.path.expanduser(p)) + for p in ( + "~/.hermes/hermes-agent", + "~/.hermes/config.yaml", + "~/.hermes/plugins/builder", + ) +) +_DESTRUCTIVE = ( + "rm -rf ", + "rm -fr ", + "shutil.rmtree", + "chmod -R", + ">/dev/sda", + "mkfs ", + "mkfs.", + "dd if=", + "dd of=", +) +_DESTRUCTIVE_WIN = ( + "del /f ", + "del /s ", + "rd /s ", + "rd /q ", + "fsutil ", +) +# `format :` only. A bare "format " substring also matched ordinary +# commands such as `ruff format --check .` -- the repo's own lint gate (#117). +# Real switches are all `/switch`, and the group must stay `/`-only: allowing +# `-` here let `--check` be consumed as a switch and then match the drive path +# of `ruff format --check D:\project` (Greptile P1 on #119). `.com` covers the +# legacy executable name, which the bare substring missed as well. +_WIN_FORMAT_DRIVE = re.compile( + r"\bformat(?:\.com)?\b(?:\s+/[^\s]+)*\s+[a-z]:", re.IGNORECASE +) +_PRIVILEGE = ("sudo ", "su -", "su ", "pkexec ", "doas ") + + +def _is_dangerous(cmd: str) -> str | None: + """Return the matching destructive pattern, or None. + + Checks the raw command and each shell-separated segment so a wrapped + invocation (`env format C:`) is caught the same as a bare one. + """ + lowered = cmd.lower() + for pattern in _DESTRUCTIVE: + if pattern in cmd: + return pattern + for pattern in _DESTRUCTIVE_WIN: + if pattern in lowered: + return pattern + if _WIN_FORMAT_DRIVE.search(lowered): + return "format " + return None + def _plugin_pre_tool_call( tool_name: str, @@ -31,63 +91,10 @@ def _plugin_pre_tool_call( **kwargs: Any, ) -> dict[str, str] | None: """Builder plugin guard: blocks dangerous tool calls.""" - import os as _os - import re as _re - - _HERMES_CORE = tuple( - _os.path.realpath(_os.path.expanduser(p)) - for p in ( - "~/.hermes/hermes-agent", - "~/.hermes/config.yaml", - "~/.hermes/plugins/builder", - ) - ) - _DESTRUCTIVE = ( - "rm -rf ", - "rm -fr ", - "shutil.rmtree", - "chmod -R", - ">/dev/sda", - "mkfs ", - "mkfs.", - "dd if=", - "dd of=", - ) - _DESTRUCTIVE_WIN = ( - "del /f ", - "del /s ", - "rd /s ", - "rd /q ", - "fsutil ", - ) - # `format :` only. A bare "format " substring also matched ordinary - # commands such as `ruff format --check .` -- the repo's own lint gate (#117). - # Real switches are all `/switch`, and the group must stay `/`-only: allowing - # `-` here let `--check` be consumed as a switch and then match the drive path - # of `ruff format --check D:\project` (Greptile P1 on #119). `.com` covers the - # legacy executable name, which the bare substring missed as well. - _WIN_FORMAT_DRIVE = _re.compile( - r"\bformat(?:\.com)?\b(?:\s+/[^\s]+)*\s+[a-z]:", _re.IGNORECASE - ) - _PRIVILEGE = ("sudo ", "su -", "su ", "pkexec ", "doas ") - - def _is_dangerous(cmd: str) -> str | None: - """Return the matched pattern if the command is dangerous, else None.""" - lowered = cmd.lower() - for pattern in _DESTRUCTIVE: - if pattern in cmd: - return pattern - for pattern in _DESTRUCTIVE_WIN: - if pattern in lowered: - return pattern - if _WIN_FORMAT_DRIVE.search(lowered): - return "format " - return None - if tool_name == "terminal": cmd = (args.get("command") or "").strip() # Check the full command and each token split on shell separators. - tokens = _re.split(r"[;&|\n\r]+", cmd) + tokens = re.split(r"[;&|\n\r]+", cmd) for segment in tokens: segment = segment.strip() if not segment: @@ -114,35 +121,19 @@ def _is_dangerous(cmd: str) -> str | None: elif tool_name in ("write_file", "patch"): target = str(args.get("path") or args.get("file") or "") try: - real_target = _os.path.realpath(_os.path.expanduser(target)) + real_target = os.path.realpath(os.path.expanduser(target)) except OSError: real_target = target for core_path in _HERMES_CORE: # Compare path components to avoid blocking sibling paths like # ~/.hermes/config.yaml.bak or ~/.hermes/hermes-agent-notes/file. - if real_target.startswith(core_path + _os.sep) or real_target == core_path: - # Check if approval mechanism is enabled (default: true) - try: - from hermes_cli.config import load_config - - cfg = load_config() - guard_cfg = cfg.get("builder", {}) - approval_enabled = guard_cfg.get("guard_approval_enabled", True) - except Exception: # noqa: BLE001 - approval_enabled = True # fail open to approval path - - if not approval_enabled: - # Approval disabled — fall back to silent blocking - return { - "action": "block", - "message": ( - "⚠ Write to Hermes protected path blocked by builder " - f"guard: `{target}`. Modifying Hermes core files may " - "break the installation." - ), - } - - # Return approve action — dispatch layer calls request_tool_approval + if real_target.startswith(core_path + os.sep) or real_target == core_path: + # Return approve action — dispatch layer calls request_tool_approval. + # The former `builder.guard_approval_enabled` opt-out is gone: it + # read cfg["builder"], which is not a known Hermes config root, so + # it always resolved to True and its silent-block branch was + # unreachable (#118). The guard now escalates to approval, which + # fails closed when there is no approving human. return { "action": "approve", "message": ( diff --git a/tests/test_coverage.py b/tests/test_coverage.py index 42da63e..f04dd24 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -133,6 +133,35 @@ def test_pre_tool_call_blocks_format_followed_immediately_by_drive(): assert result["action"] == "block", command +def test_guard_does_not_read_an_unknown_config_root(): + """The guard must not consult config for its approval behavior (#118). + + It used to read ``cfg["builder"]``, but ``builder`` is not a known Hermes + config root, so the lookup always returned ``{}`` and the silent-block + fallback was unreachable. Reading config on this path also pulled + ``hermes_cli.config`` into every ``write_file``/``patch`` call. + """ + import pathlib + + import __init__ as plugin + + source = pathlib.Path(plugin.__file__).read_text() + code = "\n".join( + line for line in source.splitlines() if not line.strip().startswith("#") + ) + + assert "load_config" not in code + assert "guard_approval_enabled" not in code + assert "approval_enabled" not in code + + # the guard must still escalate protected writes rather than silently allow + result = plugin._plugin_pre_tool_call( + "write_file", {"path": str(pathlib.Path.home() / ".hermes/config.yaml")} + ) + assert result is not None + assert result["action"] == "approve" + + def test_pre_tool_call_escalates_hermes_core_path_to_approval(): """Protected-path writes escalate to the human-approval gate. From 55686ffe127b026994c8c109cce53d6164a7fa08 Mon Sep 17 00:00:00 2001 From: Iko <6572003+iap@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:39:52 +0700 Subject: [PATCH 2/3] fix: resolve protected paths per call, not at import `_HERMES_CORE` held `realpath` values resolved once at import, while each write resolved its own target fresh. Replacing a protected path with a symlink pointing outside the root after import therefore made the two disagree, and the guard returned None instead of escalating (Greptile P1 on #120). Keep the path strings in `_HERMES_CORE_PATHS` and resolve each through `os.path.realpath()` inside the write/patch branch on every call. The regex and pattern tuples stay hoisted; those are stateless. Restores the pre-#120 behavior while keeping the constant construction out of the per-call path. --- __init__.py | 28 +++++++++++++++++----------- tests/test_coverage.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/__init__.py b/__init__.py index a965740..d19726f 100644 --- a/__init__.py +++ b/__init__.py @@ -26,16 +26,17 @@ logger = logging.getLogger(__name__) # Guard constants are module-level so a tool call does not rebuild them. The -# hook runs on every tool invocation, so realpath over the core paths and the -# regex compile were being redone per call for a fixed answer. Values are -# resolved once at import, which is what the previous per-call code did anyway. -_HERMES_CORE = tuple( - os.path.realpath(os.path.expanduser(p)) - for p in ( - "~/.hermes/hermes-agent", - "~/.hermes/config.yaml", - "~/.hermes/plugins/builder", - ) +# hook runs on every tool invocation, so the regex compile and tuple construction +# were being redone per call for a fixed answer. +# +# Path strings are cached here, but resolved through os.path.realpath() in the +# write/patch branch on each call. Freezing the realpath at import time let an +# attacker swap a protected path with a symlink after import and bypass the guard +# (Greptile P1 on #120). +_HERMES_CORE_PATHS = ( + "~/.hermes/hermes-agent", + "~/.hermes/config.yaml", + "~/.hermes/plugins/builder", ) _DESTRUCTIVE = ( "rm -rf ", @@ -124,7 +125,12 @@ def _plugin_pre_tool_call( real_target = os.path.realpath(os.path.expanduser(target)) except OSError: real_target = target - for core_path in _HERMES_CORE: + for core_path_str in _HERMES_CORE_PATHS: + # Resolve on each call so a symlink swapped after import is followed. + try: + core_path = os.path.realpath(os.path.expanduser(core_path_str)) + except OSError: + core_path = os.path.expanduser(core_path_str) # Compare path components to avoid blocking sibling paths like # ~/.hermes/config.yaml.bak or ~/.hermes/hermes-agent-notes/file. if real_target.startswith(core_path + os.sep) or real_target == core_path: diff --git a/tests/test_coverage.py b/tests/test_coverage.py index f04dd24..e8160a0 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -133,6 +133,45 @@ def test_pre_tool_call_blocks_format_followed_immediately_by_drive(): assert result["action"] == "block", command +def test_guard_follows_symlink_swapped_after_import(): + """Protected paths must resolve per call, not freeze at import (#120 P1). + + Hoisting ``realpath`` into a module constant made the roots disagree with + the freshly resolved write target once a protected path was replaced by a + symlink, so the guard stopped escalating. Roots stay cached as strings; + only the resolution is per call. + """ + import os + import tempfile + from pathlib import Path + + import __init__ as plugin + + root = Path(tempfile.mkdtemp(prefix="builder-symlink-")) + protected = root / "config.yaml" + outside = root / "evil.yaml" + protected.write_text("original\n") + outside.write_text("evil\n") + + original_paths = plugin._HERMES_CORE_PATHS + original_realpath = os.path.realpath + try: + plugin._HERMES_CORE_PATHS = (str(protected),) + # simulate the swap: the protected path becomes a symlink elsewhere + resolved_frozen = os.path.realpath(str(protected)) + protected.unlink() + os.symlink(str(outside), str(protected)) + + result = plugin._plugin_pre_tool_call("write_file", {"path": str(protected)}) + assert result is not None + assert result["action"] == "approve" + # the frozen root and the live target genuinely diverge here + assert os.path.realpath(str(protected)) != resolved_frozen + finally: + plugin._HERMES_CORE_PATHS = original_paths + os.path.realpath = original_realpath + + def test_guard_does_not_read_an_unknown_config_root(): """The guard must not consult config for its approval behavior (#118). From d827160e21ce0efbc0c620f20364c50e0891ad5a Mon Sep 17 00:00:00 2001 From: Iko <6572003+iap@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:53:01 +0700 Subject: [PATCH 3/3] test: use tmp_path and skip where symlinks are unavailable The symlink guard test built its fixture with `tempfile.mkdtemp` and never removed it, leaking a directory per run. It also called `os.symlink` unconditionally, which raises on Windows without admin or Developer Mode. Switch to the `tmp_path` fixture and skip on OSError, matching the pattern `conftest.py` already uses for the same platform limitation. Mutation-checked after the rewrite: the frozen-root mutant still fails the test and the real code still passes, so the rewrite did not weaken the binding. --- tests/test_coverage.py | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/tests/test_coverage.py b/tests/test_coverage.py index e8160a0..87d10ce 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -133,7 +133,7 @@ def test_pre_tool_call_blocks_format_followed_immediately_by_drive(): assert result["action"] == "block", command -def test_guard_follows_symlink_swapped_after_import(): +def test_guard_follows_symlink_swapped_after_import(tmp_path): """Protected paths must resolve per call, not freeze at import (#120 P1). Hoisting ``realpath`` into a module constant made the roots disagree with @@ -142,34 +142,28 @@ def test_guard_follows_symlink_swapped_after_import(): only the resolution is per call. """ import os - import tempfile - from pathlib import Path import __init__ as plugin - root = Path(tempfile.mkdtemp(prefix="builder-symlink-")) - protected = root / "config.yaml" - outside = root / "evil.yaml" + original_paths = plugin._HERMES_CORE_PATHS + protected = tmp_path / "config.yaml" + outside = tmp_path / "evil.yaml" protected.write_text("original\n") outside.write_text("evil\n") - - original_paths = plugin._HERMES_CORE_PATHS - original_realpath = os.path.realpath + frozen = os.path.realpath(str(protected)) + protected.unlink() try: + os.symlink(outside, protected) + except OSError as exc: # Windows without admin or Developer Mode + pytest.skip(f"symlinks unavailable: {exc}") + try: + assert os.path.realpath(str(protected)) != frozen # the swap took effect plugin._HERMES_CORE_PATHS = (str(protected),) - # simulate the swap: the protected path becomes a symlink elsewhere - resolved_frozen = os.path.realpath(str(protected)) - protected.unlink() - os.symlink(str(outside), str(protected)) - result = plugin._plugin_pre_tool_call("write_file", {"path": str(protected)}) assert result is not None assert result["action"] == "approve" - # the frozen root and the live target genuinely diverge here - assert os.path.realpath(str(protected)) != resolved_frozen finally: plugin._HERMES_CORE_PATHS = original_paths - os.path.realpath = original_realpath def test_guard_does_not_read_an_unknown_config_root():