diff --git a/tests/tools/test_managed_browserbase_and_modal.py b/tests/tools/test_managed_browserbase_and_modal.py index 6031bdb6da342..5322360199162 100644 --- a/tests/tools/test_managed_browserbase_and_modal.py +++ b/tests/tools/test_managed_browserbase_and_modal.py @@ -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=[], ) diff --git a/tests/tools/test_terminal_force_floor.py b/tests/tools/test_terminal_force_floor.py new file mode 100644 index 0000000000000..408814acb7306 --- /dev/null +++ b/tests/tools/test_terminal_force_floor.py @@ -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 + + +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 diff --git a/tools/approval.py b/tools/approval.py index 7e619c6a91786..a3ed2e2546080 100644 --- a/tools/approval.py +++ b/tools/approval.py @@ -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``. @@ -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: @@ -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) diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index 39a032a2fdba1..3943f81332eba 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -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, ) @@ -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. """ @@ -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( @@ -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 @@ -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) diff --git a/website/docs/user-guide/security.md b/website/docs/user-guide/security.md index a2f53ee93583a..32faa6620adeb 100644 --- a/website/docs/user-guide/security.md +++ b/website/docs/user-guide/security.md @@ -146,6 +146,7 @@ Some commands are so catastrophic — irreversible filesystem wipes, fork bombs, - `approvals.mode: off` - Cron jobs running in headless `approve` mode - User explicitly clicking "allow always" +- An internal caller's pre-confirmed command (`terminal(force=True)`, used by the TUI's remote path completion) The blocklist is the floor below `--yolo`. It trips **before** the approval layer even sees the command, and there's no override flag. Patterns currently covered (not exhaustive; kept in sync with `tools/approval_detection.py::HARDLINE_PATTERNS`): @@ -185,6 +186,7 @@ Details: - In the additional executable candidates, whitespace **between** words is collapsed, but quoted argument content and argument paths are retained. An exact rule such as `git status` therefore also matches `env git\tstatus; echo done` (where `\t` represents a tab). Quoted mentions such as `echo 'sudo -n id'` are not promoted to commands. Existing whole-input globs such as `*sudo*` still intentionally match mentions anywhere. - **YAML quoting:** always quote patterns. A bare leading `*` is a YAML alias and fails to parse; `{`, `!`, and `: ` have their own YAML meanings. Single quotes are safest for shell-ish content. - User-defined deny rules apply to all terminal backends, including isolated containers, before any backend-specific approval shortcut. +- A pre-confirmed internal command (`terminal(force=True)`) skips the approval layer (the prompt, smart approval, the allowlist, and the `cron_mode` / `single_query_mode` / `unattended_mode` deny) but not the floor: deny rules, the hardline blocklist and the `sudo -S` guard still apply, and a command too long or complex for the hardline scan to read to the end is refused, as it is under YOLO and `approvals.mode: off`. In an isolated container only the deny rules apply, as for any other command there. - A denied command returns a BLOCKED error to the agent telling it not to retry or rephrase. Nothing runs. Like the rest of the approval config, changes take effect immediately (the config cache is mtime-keyed) — no session restart needed.