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
1 change: 1 addition & 0 deletions tests/tools/test_managed_browserbase_and_modal.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ class _StubBrowserProvider:
detect_dangerous_command=lambda *args, **kwargs: None,
check_dangerous_command=lambda *args, **kwargs: {"approved": True},
check_all_command_guards=lambda *args, **kwargs: {"approved": True},
check_preconfirmed_command_guards=lambda *args, **kwargs: {"approved": True},
load_permanent_allowlist=lambda *args, **kwargs: [],
DANGEROUS_PATTERNS=[],
)
Expand Down
67 changes: 67 additions & 0 deletions tests/tools/test_terminal_force_floor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""``terminal_tool(force=True)`` skips the approval layers, never the floor (#157918).

``force`` says the caller already confirmed the command. That cannot outrank what YOLO and
``approvals.mode: off`` cannot: the hardline floor, the ``sudo -S`` guard, the operator's
``approvals.deny`` rules, and the refusal of a command the hardline scan could not read to the
end. Command strings are only passed to the guards, never run.
"""
import json

import pytest

from tools import approval_context
from tools import terminal_tool

GREP = 'v=$(grep -o "[^\\"]*" f)'
LOCAL = {"env_type": "local"}
ISOLATED_DOCKER = {"env_type": "docker"}
BIND_MOUNTED_DOCKER = {"env_type": "docker", "docker_volumes": ["/home/u/project:/workspace"]}


@pytest.fixture(autouse=True)
def _no_approval_surface(monkeypatch):
for var in ("HERMES_YOLO_MODE", "HERMES_GATEWAY_SESSION", "HERMES_INTERACTIVE",
"HERMES_EXEC_ASK", "HERMES_CRON_SESSION", "SUDO_PASSWORD"):
monkeypatch.delenv(var, raising=False)


def _forced_rejection(command: str, config: dict) -> dict:
with pytest.raises(terminal_tool._Rejected) as exc:
terminal_tool._run_approval_guards(command, config["env_type"], config, force=True)
return json.loads(exc.value.result_json)


@pytest.mark.parametrize("command,config,reason", [
pytest.param("rm -rf /", LOCAL, "hardline", id="hardline-local"),
pytest.param("mkfs.ext4 /dev/sda1", BIND_MOUNTED_DOCKER, "hardline", id="hardline-docker-with-host-mounts"),
pytest.param("echo hunter2 | sudo -S apt install -y x", LOCAL, "sudo", id="sudo-stdin"),
pytest.param("\n".join([GREP] * 500), LOCAL, "too long or complex", id="unread-by-the-scan"),
])
def test_force_does_not_run_what_the_floor_refuses(command, config, reason):
result = _forced_rejection(command, config)
assert result["status"] == "blocked"
assert reason in result["error"]


def test_force_keeps_the_operators_deny_rules_in_an_isolated_container(monkeypatch):
monkeypatch.setattr(approval_context, "_get_approval_config",
lambda: {"mode": "manual", "deny": ["git push --force*"]})
result = _forced_rejection("git push --force origin main", ISOLATED_DOCKER)
assert result["status"] == "blocked" and "approvals.deny" in result["error"]


@pytest.mark.parametrize("command,config", [
pytest.param("ls -la", LOCAL, id="confirmed-command-local"),
pytest.param("rm -rf /", ISOLATED_DOCKER, id="isolated-container-is-its-own-floor"),
])
def test_force_runs_a_confirmed_command_the_floor_allows(command, config):
verdict = terminal_tool._run_approval_guards(command, config["env_type"], config, force=True)
assert verdict.approved_run is True

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: nothing pins the other half of the contract, that force still skips the approval layers.

Both allowed rows (ls -la locally, rm -rf / in an isolated container) are also approved by check_all_command_guards when no approval surface is present. So a change that sends the force branch back through _check_all_guards passes all 7 tests here and the 60 in the four neighbouring files I ran (test_approved_command_clean_slate, test_command_guards, test_approval_deny_rules, tui_gateway/test_backend_dir_entries_preconfirmed, which fakes terminal_tool entirely). That's the regression the completion path's force=True exists to avoid (#115478).

The test below uses cron's default cron_mode: deny as the approval layer. It asserts that the unforced call is refused, so the row isn't vacuous, and that the forced one runs. It passes on this head, and it is the only test that catches that mutant (1 failed of 8). scripts/check --only ruff,health is clean with it.

Suggested change
assert verdict.approved_run is True
assert verdict.approved_run is True
def test_force_skips_the_approval_layers(monkeypatch):
"""Only the floor binds a forced command, not an approval layer that refuses it unforced (cron's default deny)."""
monkeypatch.setenv("HERMES_CRON_SESSION", "1")
with pytest.raises(terminal_tool._Rejected):
terminal_tool._run_approval_guards("rm -rf build/", "local", LOCAL, force=False)
assert terminal_tool._run_approval_guards("rm -rf build/", "local", LOCAL, force=True).approved_run is True

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added as test_force_skips_the_approval_layers in 34e5649, using your cron-default-deny version. Thanks for running the mutation probe.



def test_force_skips_the_approval_layers(monkeypatch):
"""Only the floor binds a forced command, not an approval layer that refuses it unforced (cron's default deny)."""
monkeypatch.setenv("HERMES_CRON_SESSION", "1")
with pytest.raises(terminal_tool._Rejected):
terminal_tool._run_approval_guards("rm -rf build/", "local", LOCAL, force=False)
assert terminal_tool._run_approval_guards("rm -rf build/", "local", LOCAL, force=True).approved_run is True
43 changes: 31 additions & 12 deletions tools/approval.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""Dangerous command approval -- the gate flow and per-session state.

Owns the session state (approvals, yolo, gateway queues, denial breaker), the three guard
entry points (``check_all_command_guards``, ``check_execute_code_guard``,
``request_tool_approval`` / ``_run_approval_gate``) and the shared human-decision engine
behind them. Leaves: ``approval_detection`` (hardline/dangerous patterns), ``approval_context``
Owns the session state (approvals, yolo, gateway queues, denial breaker), the guard
entry points (``check_all_command_guards``, ``check_preconfirmed_command_guards``,
``check_execute_code_guard``, ``request_tool_approval`` / ``_run_approval_gate``) and the
shared human-decision engine behind them. Leaves: ``approval_detection`` (hardline/dangerous patterns), ``approval_context``
(contextvars, config readers), ``approval_floors`` (pre-gate blocks, allowlist match),
``approval_prompt`` (CLI prompt, plugin transports, MCP elicitation), ``approval_gateway_wait``
(blocking gateway round-trip), ``approval_smart`` (guardian LLM), ``approval_human_wait``.
Expand Down Expand Up @@ -664,14 +664,16 @@ def _blocked(message: str, *, pattern_key: str, description: str) -> dict:

def _scan_incomplete_block(why: str) -> dict:
"""Refusal for a command the hardline scan could not finish where no human reviews it (YOLO,
``approvals.mode: off``, cron / -q / unattended approve-mode, no prompt surface). Its hardline
coverage is only the linear fallback, so nothing but a person may wave it through."""
``approvals.mode: off``, cron / -q / unattended approve-mode, no prompt surface, a pre-confirmed
``terminal(force=True)``). Its hardline coverage is only the linear fallback, so nothing but a
person may wave it through."""
return _blocked(_SCAN_INCOMPLETE_BLOCK_MESSAGE.format(why=why),
pattern_key=_SCAN_INCOMPLETE_DESCRIPTION, description=_SCAN_INCOMPLETE_DESCRIPTION)


_NO_REVIEWER_BYPASS = "approvals are bypassed (--yolo, /yolo or approvals.mode: off)"
_NO_REVIEWER_PRESENT = "no human is present to review it"
_NO_REVIEWER_PRECONFIRMED = "Hermes pre-confirmed it without a human reviewing it"


def _user_approved(session_key: str, description: str) -> dict:
Expand Down Expand Up @@ -1399,18 +1401,35 @@ def request_tool_approval(tool_name: str, reason: str, *, rule_key: str = "", ap

# --- Combined pre-exec guard (floors + dangerous command detection) ------------------------------------------------

def _floor_verdict(command: str, env_type: str, has_host_access: bool) -> dict | None:
"""The final verdict no approval setting can change, or None to go on to the approval layers.
An isolated container gets only the operator's deny rules (its isolation stands in for the
floor); everywhere else the full floor runs."""
if _should_skip_container_guards(env_type, has_host_access=has_host_access):
return _user_deny_block(command) or _approved()
return _floor_block(command, sudo_guard=True)


def check_preconfirmed_command_guards(command: str, env_type: str, has_host_access: bool = False) -> dict:
"""Guards for a command its caller already confirmed (``terminal_tool(force=True)``): a
confirmation cannot outrank what YOLO and ``approvals.mode: off`` cannot, so the floor still
applies, and so does the refusal of a command the hardline scan could not read to the end —
the caller vouched for the command, not for what the guard could not see (#157918)."""
if (floor := _floor_verdict(command, env_type, has_host_access)) is not None:
return floor
if hardline_scan_incomplete(command):
return _scan_incomplete_block(_NO_REVIEWER_PRECONFIRMED)
return _approved()


def check_all_command_guards(command: str, env_type: str,
approval_callback=None,
has_host_access: bool = False) -> dict:
"""Run all pre-exec security checks and return a single approval decision. Plugins that
want to veto or escalate a command do it from ``pre_tool_call``.
``has_host_access``: a Docker sandbox with bind-mounted host paths takes the normal flow."""
if _should_skip_container_guards(env_type, has_host_access=has_host_access):
return _user_deny_block(command) or _approved()

blocked = _floor_block(command, sudo_guard=True)
if blocked is not None:
return blocked
if (floor := _floor_verdict(command, env_type, has_host_access)) is not None:
return floor

from agent.terminal_approval_batch import consume_prepared_guard
prepared = consume_prepared_guard(command, env_type, has_host_access)
Expand Down
21 changes: 14 additions & 7 deletions tools/terminal_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ def _container_profile() -> str:

from tools.approval import (
check_all_command_guards as _check_all_guards_impl,
check_preconfirmed_command_guards as _check_preconfirmed_guards,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new check_preconfirmed_command_guards import breaks tests/tools/test_managed_browserbase_and_modal.py, so Python tests / Run tests (3/3) and All required checks pass (v2) are red on this head.

That test installs a types.SimpleNamespace stub as sys.modules["tools.approval"] (lines 169-175). The stub defines check_all_command_guards but not the new name, and this module imports both at load time, so loading terminal_tool under the stub raises ImportError: cannot import name 'check_preconfirmed_command_guards' at this line. It's the only such stub of tools.approval under tests/.

  • CI run 45228287945, job Python tests / Run tests (3/3): 30160 passed, 1 failed, test_terminal_tool_respects_direct_modal_mode_without_falling_back_to_managed, with that error.
  • Locally on this head the file gives 6 passed, 1 failed (same test, same error). With the patch below it's 7 passed, and scripts/check --only ruff,health is clean.

The fix goes in the stub, outside this diff; production code stays as it is:

diff --git a/tests/tools/test_managed_browserbase_and_modal.py b/tests/tools/test_managed_browserbase_and_modal.py
index 6031bdb..5322360 100644
--- a/tests/tools/test_managed_browserbase_and_modal.py
+++ b/tests/tools/test_managed_browserbase_and_modal.py
@@ -170,6 +170,7 @@ def _install_fake_tools_package():
         detect_dangerous_command=lambda *args, **kwargs: None,
         check_dangerous_command=lambda *args, **kwargs: {"approved": True},
         check_all_command_guards=lambda *args, **kwargs: {"approved": True},
+        check_preconfirmed_command_guards=lambda *args, **kwargs: {"approved": True},
         load_permanent_allowlist=lambda *args, **kwargs: [],
         DANGEROUS_PATTERNS=[],
     )

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 34e5649: the tools.approval stub in tests/tools/test_managed_browserbase_and_modal.py now has check_preconfirmed_command_guards. That file passes locally (7/7) together with test_terminal_force_floor.py.

)


Expand Down Expand Up @@ -1179,7 +1180,7 @@ class _ApprovalVerdict:
"""Outcome of the pre-exec guard pass.
``note`` is the audit note attached to the result. ``approved_run`` is True
when the user explicitly approved (or pre-confirmed via ``force``); it drives
when a human approved it or its caller vetted it via ``force``; it drives
the clean-interrupt-slate clear before ``env.execute`` so an approved command
can't be SIGINT-killed by a bit that landed during the approval-wait.
"""
Expand All @@ -1188,12 +1189,17 @@ class _ApprovalVerdict:


def _run_approval_guards(command: str, env_type: str, config: dict[str, Any], *, force: bool) -> _ApprovalVerdict:
"""Run the command guards; ``force`` skips them entirely.
"""Run the command guards; ``force`` skips the approval layers but not the floor
(``check_preconfirmed_command_guards``).
Raises :class:`_Rejected` when the command may not run (denied, or pending
gateway approval)."""
has_host_access = _docker_has_host_access(config)
if force:
return _ApprovalVerdict(approved_run=True)
approval = _check_all_guards(command, env_type, has_host_access=_docker_has_host_access(config))
approval = _check_preconfirmed_guards(command, env_type, has_host_access=has_host_access)
if approval["approved"]:
return _ApprovalVerdict(approved_run=True)
else:
approval = _check_all_guards(command, env_type, has_host_access=has_host_access)
if not approval["approved"]:
if approval.get("status") == "pending_approval": # gateway ask mode
raise _Rejected(_error_json(
Expand Down Expand Up @@ -1584,8 +1590,9 @@ def terminal_tool(
) -> str:
"""Execute *command* in the configured terminal environment; returns a JSON string.
``force`` (internal, not in the model schema) skips the dangerous-command
check after the user confirmed. ``workdir`` is per-command and never
``force`` (internal, not in the model schema) marks a command its caller already
vetted: it skips the approval layers, never the floor.
``workdir`` is per-command and never
recorded as the session cwd. ``pty`` applies to the local backend only.
``notify_on_complete`` and ``watch_patterns`` are mutually exclusive
background-only flags: on conflict watch_patterns is dropped. watch_patterns
Expand Down Expand Up @@ -1666,7 +1673,7 @@ def terminal_tool(
status="error",
))
# Pre-exec security checks (floors + dangerous command detection);
# force=True means the user already confirmed.
# force: the caller already vetted the command; the floor still runs.
verdict = _run_approval_guards(command, env_type, plan.config, force=force)

pty_disabled = pty and _command_requires_pipe_stdin(command)
Expand Down
Loading