Skip to content

The agent that grows with you

fix(cron): make the lifecycle guard total — sanitize at ingestion, not per-syscall

kshitijc8d48b8b138b
diff --git a/cron/lifecycle_guard.py b/cron/lifecycle_guard.py
index df12d613fb2..360d6657d54 100644
--- a/cron/lifecycle_guard.py
+++ b/cron/lifecycle_guard.py
@@ -35,6 +35,7 @@ informative rejection instead of scheduling a job that will only fail
from __future__ import annotations
+import logging
import os
import re
import shlex
@@ -42,6 +43,8 @@ import stat
from pathlib import Path
from typing import Callable, Iterator, Optional
+logger = logging.getLogger(__name__)
+
class GatewayLifecycleBlocked(ValueError):
"""Raised when a cron job spec contains a gateway-lifecycle command."""
@@ -170,10 +173,41 @@ def contains_launchctl_submit_command(command: str) -> bool:
return False
-def _resolve_terminal_script_path(candidate: str, cwd: Optional[str]) -> Path:
- path = Path(candidate).expanduser()
+def _expand_candidate_path(candidate: str) -> Optional[Path]:
+ """Sanitize a tokenized path candidate at the ingestion boundary.
+
+ Candidate tokens come from shlex-splitting arbitrary command text —
+ including text recursively decoded from binaries or remote reads — so
+ they can carry NUL bytes or other junk no real filesystem path can
+ contain. Every OS-facing ``Path`` operation downstream (``expanduser``,
+ ``os.open``, ``resolve``) raises a *different* exception for the same
+ junk (``ValueError: embedded null byte``, ``RuntimeError: Could not
+ determine home directory`` when HOME is unset under launchd, OSError
+ for over-long paths). Rejecting here — once, before any OS call — is
+ the whole-class fix; catching per-syscall was the whack-a-mole that
+ produced #76762, #77703, #77780, and #78256.
+
+ Returns ``None`` for candidates that cannot be a real path (nothing to
+ scan), otherwise the ``expanduser()``-expanded ``Path``.
+ """
+ if not candidate or "\x00" in candidate:
+ return None
+ try:
+ return Path(candidate).expanduser()
+ except (ValueError, RuntimeError, OSError):
+ return None
+
+
+def _resolve_terminal_script_path(candidate: str, cwd: Optional[str]) -> Optional[Path]:
+ path = _expand_candidate_path(candidate)
+ if path is None:
+ return None
if not path.is_absolute():
- path = Path(cwd or Path.cwd()) / path
+ try:
+ path = Path(cwd or Path.cwd()) / path
+ except OSError:
+ # Path.cwd() can raise when the process cwd was deleted.
+ return None
return path
@@ -192,7 +226,9 @@ def _iter_referenced_shell_scripts(
if executable_name in {".", "source"}:
if len(segment) > index + 1:
- yield _resolve_terminal_script_path(segment[index + 1], cwd)
+ resolved = _resolve_terminal_script_path(segment[index + 1], cwd)
+ if resolved is not None:
+ yield resolved
continue
if executable_name in _SHELL_EXECUTABLES:
@@ -216,7 +252,9 @@ def _iter_referenced_shell_scripts(
"-c",
"--command",
}:
- yield _resolve_terminal_script_path(arguments[arg_index], cwd)
+ resolved = _resolve_terminal_script_path(arguments[arg_index], cwd)
+ if resolved is not None:
+ yield resolved
continue
# A bare "/" token is pathlib's division operator in Python sources
@@ -226,7 +264,9 @@ def _iter_referenced_shell_scripts(
# (#77131). Skip pure-separator tokens.
if executable.strip("/"):
if "/" in executable or executable.endswith((".sh", ".bash", ".zsh")):
- yield _resolve_terminal_script_path(executable, cwd)
+ resolved = _resolve_terminal_script_path(executable, cwd)
+ if resolved is not None:
+ yield resolved
def _iter_shell_command_payloads(command: str) -> Iterator[str]:
@@ -246,7 +286,7 @@ def _resolve_script_directory(script_path: str) -> Optional[str]:
"""Return the directory *script_path* resolves to, handling relative names."""
try:
path = _resolve_script_path(script_path)
- if path.is_absolute():
+ if path is not None and path.is_absolute():
return str(path.parent)
except Exception:
pass
@@ -290,6 +330,31 @@ def _read_referenced_script(path: Path) -> tuple[Optional[str], bool]:
return data.decode("utf-8", errors="replace"), False
+def _sanitize_remote_script_text(text: Optional[str]) -> tuple[Optional[str], bool]:
+ """Apply the local-read contract to text from a ``read_remote_script`` callback.
+
+ The recursion boundary must not trust its callbacks: any backend (SSH,
+ Modal, Daytona, or a future one) can hand back raw binary bytes decoded
+ as text, or arbitrarily large output. Mirror
+ ``_read_referenced_script``'s semantics — NUL bytes mean binary
+ (nothing to scan, checked first, #77703), oversized text fails closed
+ like an oversized local file (#76762) — so remote and local reads can
+ never diverge again. The size bound here is in characters rather than
+ bytes: the downstream cost (shlex tokenization of the text) is
+ per-character, and decoded characters never exceed source bytes, so
+ the character bound is at least as strict for scan work. Enforced here
+ rather than inside each callback so the guarantee holds for every
+ callback, not just the ones we hardened.
+ """
+ if not text:
+ return None, False
+ if "\x00" in text:
+ return None, False
+ if len(text) > _MAX_REFERENCED_SCRIPT_BYTES:
+ return None, True
+ return text, False
+
+
def _contains_unsafe_gateway_action(
command: str,
*,
@@ -331,7 +396,14 @@ def _contains_unsafe_gateway_action(
return True
if script_text is None and read_remote_script is not None:
# Local path missing; try the remote backend if one is available.
- script_text = read_remote_script(str(script_path))
+ # The callback's output crosses the same trust boundary as a
+ # local read — sanitize it identically before it enters the
+ # recursion (binary skip + size fail-closed).
+ script_text, unsafe = _sanitize_remote_script_text(
+ read_remote_script(str(script_path))
+ )
+ if unsafe:
+ return True
if not script_text:
continue
# Relative references inside a script resolve against that script's
@@ -354,19 +426,45 @@ def contains_gateway_lifecycle_command_or_referenced_script(
cwd: Optional[str] = None,
read_remote_script: Optional[_ReadRemoteScriptFn] = None,
) -> bool:
- """Detect lifecycle/submit commands, including bounded nested scripts."""
- return _contains_unsafe_gateway_action(
- command,
- cwd=cwd,
- depth=0,
- visited=set(),
- read_remote_script=read_remote_script,
- )
+ """Detect lifecycle/submit commands, including bounded nested scripts.
+
+ Total by construction: this function returns a verdict for *every*
+ input and never raises. The direct scans below are pure string
+ operations; the referenced-script walk touches the filesystem, remote
+ backends, and shlex on arbitrary decoded bytes, so it is best-effort
+ defense-in-depth — any unexpected failure inside it is logged and
+ treated as "walk found nothing" rather than crashing the caller.
+
+ This is the contract #76762 established ("a guarded path must never
+ crash the guard") enforced at the boundary instead of per-syscall: a
+ guard crash propagates out of ``tools/terminal_tool.py`` and breaks
+ every terminal command until the gateway restarts (#77780, #78256),
+ which is strictly worse than either verdict.
+ """
+ if contains_gateway_lifecycle_command(command) or contains_launchctl_submit_command(
+ command
+ ):
+ return True
+ try:
+ return _contains_unsafe_gateway_action(
+ command,
+ cwd=cwd,
+ depth=0,
+ visited=set(),
+ read_remote_script=read_remote_script,
+ )
+ except Exception:
+ logger.warning(
+ "lifecycle guard referenced-script walk failed; "
+ "falling back to direct-scan verdict",
+ exc_info=True,
+ )
+ return False
-def _resolve_script_path(script_path: str) -> Path:
+def _resolve_script_path(script_path: str) -> Optional[Path]:
"""Resolve a cron ``script`` value the same way the scheduler does.
The scheduler (``cron.scheduler``) resolves a bare/relative script path
@@ -376,10 +474,17 @@ def _resolve_script_path(script_path: str) -> Path:
(``~/.hermes/scripts/restart.sh``) but is passed as the bare name
``restart.sh`` would read as a nonexistent relative path and silently
scan prompt-only content, letting the command through.
+
+ Returns ``None`` for values that cannot be a real path (NUL bytes,
+ unexpandable ``~``) — the same ingestion contract as
+ ``_expand_candidate_path``; such a value can never name a file the
+ scheduler would execute, so there is nothing to scan.
"""
from hermes_constants import get_hermes_home
- raw = Path(script_path).expanduser()
+ raw = _expand_candidate_path(script_path)
+ if raw is None:
+ return None
if raw.is_absolute():
return raw
return get_hermes_home() / "scripts" / raw
@@ -389,10 +494,13 @@ def _read_script_for_scanning(script_path: str) -> str:
"""Read a cron script with the bounded terminal-script scanner.
Non-regular or oversized inputs fail closed by returning a lifecycle-shaped
- sentinel, while missing/unreadable paths remain empty so ordinary scheduler
- path validation can report them.
+ sentinel, while missing/unreadable/unresolvable paths remain empty so
+ ordinary scheduler path validation can report them.
"""
- script_text, unsafe = _read_referenced_script(_resolve_script_path(script_path))
+ resolved = _resolve_script_path(script_path)
+ if resolved is None:
+ return ""
+ script_text, unsafe = _read_referenced_script(resolved)
if unsafe:
return "hermes gateway restart"
return script_text or ""
@@ -417,7 +525,8 @@ def check_gateway_lifecycle(
combined = prompt or ""
python_script = False
if script:
- python_script = _resolve_script_path(script).suffix == ".py"
+ resolved_script = _resolve_script_path(script)
+ python_script = resolved_script is not None and resolved_script.suffix == ".py"
script_text = _read_script_for_scanning(script)
if script_text:
combined = f"{combined}\n{script_text}"
diff --git a/tests/hermes_cli/test_gateway_restart_loop.py b/tests/hermes_cli/test_gateway_restart_loop.py
index 51e56dcddc2..c39d2d88cbd 100644
--- a/tests/hermes_cli/test_gateway_restart_loop.py
+++ b/tests/hermes_cli/test_gateway_restart_loop.py
@@ -761,6 +761,112 @@ class TestLifecycleGuardModule:
with pytest.raises(GatewayLifecycleBlocked):
check_gateway_lifecycle("daily ops", str(script))
+ # -- Whole-class regression tests (tilllt's T1-T4 on PR #79454) --------
+
+ def test_tilde_nul_candidate_does_not_crash_terminal_walk(self):
+ """T1: ``Path('~user\\x00...').expanduser()`` raises ValueError one
+ frame *before* ``os.open`` — the per-syscall guards never see it. The
+ ingestion-boundary sanitizer must reject the candidate instead."""
+ from cron.lifecycle_guard import (
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+ result = contains_gateway_lifecycle_command_or_referenced_script(
+ "'~jenkins\x00broken/payload.sh' arg", cwd="/tmp"
+ )
+ assert result is False
+
+ def test_tilde_nul_candidate_does_not_crash_cron_script_resolution(self):
+ """T2: the same ``expanduser`` crash via the cron ``script`` path
+ (``_resolve_script_path`` / ``check_gateway_lifecycle``)."""
+ from cron.lifecycle_guard import check_gateway_lifecycle
+
+ # Must neither raise ValueError nor block: an unresolvable script
+ # value has nothing to scan, and scheduler path validation reports
+ # the bad path separately.
+ check_gateway_lifecycle("daily ops", "~jenkins\x00broken/payload.sh")
+
+ def test_binary_from_remote_callback_never_false_positives(self):
+ """T3: a ``read_remote_script`` callback returning NUL-bearing binary
+ text that *happens to contain* a lifecycle-looking fragment must be
+ skipped as binary at the recursion boundary — not matched and
+ blocked. Hardening one callback (#79454) left every other current or
+ future callback exposed; the boundary sanitizer covers them all."""
+ from cron.lifecycle_guard import (
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+
+ def _remote_read(_path: str):
+ return "MZ\x00\x00\x90\x00 hermes gateway restart \x00\x00junk"
+
+ result = contains_gateway_lifecycle_command_or_referenced_script(
+ "bash /nonexistent/dir/helper.sh",
+ cwd="/tmp",
+ read_remote_script=_remote_read,
+ )
+ assert result is False
+
+ def test_oversized_remote_callback_text_fails_closed(self):
+ """T4: >1 MiB of NUL-free text from a remote callback must follow the
+ local-read contract (oversized regular file → fail closed, #76762)
+ instead of being scanned unbounded — the 179 MiB case from #77729."""
+ from cron.lifecycle_guard import (
+ _MAX_REFERENCED_SCRIPT_BYTES,
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+
+ big = "x" * (_MAX_REFERENCED_SCRIPT_BYTES + 1)
+
+ result = contains_gateway_lifecycle_command_or_referenced_script(
+ "bash /nonexistent/dir/big_helper.sh",
+ cwd="/tmp",
+ read_remote_script=lambda _path: big,
+ )
+ assert result is True
+
+ def test_guard_is_total_against_adversarial_inputs(self, monkeypatch):
+ """The public guard is a total function: no input may raise. Covers
+ the residual class beyond the four named sites — including
+ ``expanduser`` RuntimeError when HOME is unset under launchd."""
+ from cron.lifecycle_guard import (
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+
+ monkeypatch.delenv("HOME", raising=False)
+ adversarial = [
+ "'~\x00' run",
+ "bash '~user\x00/x.sh'",
+ "source /tmp/e\x00vil.sh",
+ "sh ~/scripts/anything.sh", # HOME unset → RuntimeError pre-fix
+ ". '\x00\x00\x00'",
+ "bash " + "A" * 5000 + ".sh", # over-long path → OSError
+ ]
+ for command in adversarial:
+ # Must return a bool, never raise.
+ verdict = contains_gateway_lifecycle_command_or_referenced_script(
+ command, cwd="/tmp"
+ )
+ assert verdict is False
+
+ def test_walk_crash_falls_back_to_direct_scan_verdict(self, monkeypatch):
+ """If the best-effort walk itself crashes, the guard logs and falls
+ back to the direct-scan verdict instead of propagating — a guard
+ crash breaks every terminal command until gateway restart (#77780),
+ strictly worse than either verdict."""
+ import cron.lifecycle_guard as lg
+
+ def _boom(*args, **kwargs):
+ raise RuntimeError("sibling site nobody found yet")
+
+ monkeypatch.setattr(lg, "_contains_unsafe_gateway_action", _boom)
+ # Direct scan still blocks a literal lifecycle command...
+ assert lg.contains_gateway_lifecycle_command_or_referenced_script(
+ "hermes gateway restart"
+ ) is True
+ # ...and a benign command fails open instead of crashing.
+ assert lg.contains_gateway_lifecycle_command_or_referenced_script(
+ "echo hello"
+ ) is False
+
# ---------------------------------------------------------------------------
# Defense 2 (chokepoint): cron.jobs.create_job blocks the AGENT model-tool path
@@ -856,7 +962,7 @@ class TestTerminalToolGatewayLifecycleGuardRemote:
import tools.terminal_tool as tt
# Path only exists on the remote backend; locally it is absent, so the
- # guard must fall back to env.execute('cat ...') to scan it.
+ # guard must fall back to a bounded env.execute('head -c ...') read.
script = "/remote/workspace/remote.sh"
calls = []
@@ -865,7 +971,7 @@ class TestTerminalToolGatewayLifecycleGuardRemote:
cwd = str(tmp_path)
def execute(self, command, **kwargs):
calls.append(command)
- if "cat" in command and "/remote/workspace/remote.sh" in command:
+ if "head -c" in command and "/remote/workspace/remote.sh" in command:
return {"output": "#!/bin/bash\\nhermes gateway restart\\n", "returncode": 0}
return {"output": "", "returncode": 0}
@@ -877,7 +983,7 @@ class TestTerminalToolGatewayLifecycleGuardRemote:
assert result["exit_code"] == 1
assert "referenced script" in result["error"]
- assert any("cat" in c for c in calls)
+ assert any("head -c" in c for c in calls)
class TestCronCreateLifecycleBlockExtra:
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 9253b230951..c7c2e52f707 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -2557,12 +2557,21 @@ def terminal_tool(
except Exception:
pass
# Remote / sandboxed backend: read via the environment's shell.
+ # Bound the read at the source with `head -c` so an oversized
+ # file (e.g. a 166MB ELF invoked by absolute path) never
+ # crosses the wire — `cat` of such a binary previously pinned
+ # the gateway's tool thread on a superlinear shlex scan for
+ # 30+ minutes. One byte over the guard's 1 MiB budget is
+ # enough for lifecycle_guard's sanitizer to fail the
+ # oversized case closed, mirroring the local-read semantics.
try:
- result = env.execute(f"cat {shlex.quote(script_path)}")
+ result = env.execute(
+ f"head -c 1048577 {shlex.quote(script_path)}"
+ )
if result.get("returncode", -1) == 0:
output = result.get("output", "")
if output and "\x00" in output:
- # Binary content from a remote `cat`: skip for the
+ # Binary content from a remote read: skip for the
# same reason as the local branch above (#77703).
return None
return output