Skip to content

The agent that grows with you

fix(cron): make gateway lifecycle matching shell-token aware (#80269)

Axel Vanni6d501c295880
diff --git a/cron/lifecycle_guard.py b/cron/lifecycle_guard.py
index 4c42c052349..758c66d4f59 100644
--- a/cron/lifecycle_guard.py
+++ b/cron/lifecycle_guard.py
@@ -166,7 +166,28 @@ def _named_profile_is_current(named: str) -> bool:
def contains_gateway_lifecycle_command(text: str) -> bool:
- """Return True if *text* contains a gateway lifecycle command pattern."""
+ """Return True if *text* contains a gateway lifecycle command pattern.
+
+ Matches in two passes. The first is the raw-text regex above — cheap,
+ and the only pass that can fire on non-shell inputs shlex can't
+ tokenize (e.g. a Python source string). The second re-runs the same
+ pattern against each command segment after shell tokenization, where
+ quotes and backslash escapes have already been resolved.
+
+ That second pass exists because a real shell resolves quote-splicing
+ (``kick"start"``) and backslash-escaping (``kick\\start``) into one
+ literal word — ``kickstart`` — before the command ever runs. The raw
+ text still has the quote or backslash sitting between the verb's two
+ halves, so the first pass alone lets a spliced verb reach
+ ``launchctl``/``systemctl`` untouched while still executing as the
+ blocked lifecycle command (#80269, reported against #80260's bootout
+ parity fix). Tokenizing closes that gap while keeping the same
+ gateway-label anchoring (``_GATEWAY_LIFECYCLE_PATTERN`` still requires
+ a ``hermes``/``gateway`` token) — this function is the single choke
+ point ``_contains_unsafe_gateway_action`` calls at every recursion
+ level, so referenced-script and ``sh -c`` payload scanning inherit the
+ fix automatically.
+ """
if not text:
return False
normalized = _SHELL_LINE_CONTINUATION.sub(" ", text)
@@ -187,6 +208,14 @@ def contains_gateway_lifecycle_command(text: str) -> bool:
named = named.strip().strip("\"'")
if _named_profile_is_current(named):
return True
+ # Token-aware second pass (#80269): re-run the pattern on shell-tokenized
+ # segments where quotes/escapes are resolved, closing splice bypasses
+ # like `kick"start"`. Runs after the profile-flag check so both passes
+ # apply independently.
+ for segment in _iter_command_segments(normalized):
+ joined = " ".join(segment)
+ if joined and _GATEWAY_LIFECYCLE_PATTERN.search(joined):
+ return True
return False
diff --git a/tests/hermes_cli/test_gateway_restart_loop.py b/tests/hermes_cli/test_gateway_restart_loop.py
index 2cefd812ab0..441c5346093 100644
--- a/tests/hermes_cli/test_gateway_restart_loop.py
+++ b/tests/hermes_cli/test_gateway_restart_loop.py
@@ -66,6 +66,56 @@ class TestGatewayLifecyclePattern:
)
assert not _contains_gateway_lifecycle_command(text), f"Should NOT match: {text!r}"
+ @pytest.mark.parametrize("text", [
+ # #80269: the shell resolves quote-splicing and backslash-escaping
+ # into a single literal word BEFORE the command runs, so
+ # `launchctl kick"start" ... ai.hermes.gateway` executes exactly as
+ # the blocked `kickstart` form. Raw-text matching sees the quote (or
+ # backslash) wedged between the verb's halves and misses it, leaving
+ # the bypassable approval layer as the only cover.
+ 'launchctl kick"start" -k gui/501/ai.hermes.gateway',
+ "launchctl kick'start' -k gui/501/ai.hermes.gateway",
+ "launchctl kick\\start -k gui/501/ai.hermes.gateway",
+ 'launchctl "kickstart" -k gui/501/ai.hermes.gateway',
+ # Splices on the newer/legacy unload spellings this PR added.
+ 'launchctl boot"out" gui/501/ai.hermes.gateway',
+ "launchctl dis\\able gui/501/ai.hermes.gateway",
+ # The gateway identifier itself can be spliced just as easily.
+ 'launchctl bootout gui/501/ai.hermes."gateway"',
+ # Same class on the systemctl and hermes-CLI branches.
+ 'systemctl re"start" hermes-gateway',
+ 'hermes gateway re"start"',
+ ])
+ def test_shell_token_spliced_lifecycle_verbs(self, text):
+ assert _contains_gateway_lifecycle_command(text), f"Should match: {text!r}"
+
+ def test_spliced_verb_inside_shell_c_payload_is_blocked(self):
+ # A splice nested in a `sh -c` payload resolves one level deeper than
+ # the flat scan: POSIX single quotes preserve the inner double quotes
+ # verbatim, so the outer tokenization yields the payload with the
+ # splice still intact. The recursion re-scans that payload through the
+ # same choke point, where it collapses to `kickstart`. This is the
+ # entry point terminal_tool.py calls in gateway sessions, so it is the
+ # boundary that matters.
+ from cron.lifecycle_guard import (
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+
+ command = 'sh -c \'launchctl kick"start" -k gui/501/ai.hermes.gateway\''
+ assert contains_gateway_lifecycle_command_or_referenced_script(command)
+
+ @pytest.mark.parametrize("text", [
+ # The tokenizing pass must not widen the blast radius: prose and
+ # non-gateway services stay allowed even though tokenization now
+ # strips their quotes too.
+ 'echo "restart the payment gateway"',
+ 'launchctl kick"start" -k gui/501/ai.hermes.update-checker',
+ 'systemctl re"start" hermes-meta.service',
+ "Summarize how the API gateway handles a restart after rate limiting",
+ ])
+ def test_tokenizing_pass_does_not_overmatch(self, text):
+ assert not _contains_gateway_lifecycle_command(text), f"Should NOT match: {text!r}"
+
@pytest.mark.parametrize("text", [
"restart the server application",
diff --git a/tests/tools/test_approval.py b/tests/tools/test_approval.py
index 24a74be21f9..4d34df04612 100644
--- a/tests/tools/test_approval.py
+++ b/tests/tools/test_approval.py
@@ -849,6 +849,36 @@ class TestLaunchctlGatewayLifecycle:
dangerous, _, _ = detect_dangerous_command(cmd)
assert dangerous is False, cmd
+ def test_quote_spliced_verbs_detected(self):
+ """#80269: the shell joins ``kick"start"`` into the literal verb
+ ``kickstart`` before execution, so the spliced form runs exactly as
+ the gated one. Backslash splices already normalized here; quote
+ splices sit in an argument position that word-scoped deobfuscation
+ deliberately does not touch, so they auto-approved.
+ """
+ for cmd in (
+ 'launchctl kick"start" -k gui/501/ai.hermes.gateway',
+ "launchctl kick'start' -k gui/501/ai.hermes.gateway",
+ 'launchctl boot"out" gui/501/ai.hermes.gateway',
+ 'launchctl bootout gui/501/ai.hermes."gateway"',
+ 'hermes gateway re"start"',
+ 'systemctl re"start" hermes-gateway',
+ ):
+ dangerous, _, _ = detect_dangerous_command(cmd)
+ assert dangerous is True, cmd
+
+ def test_spliced_detection_does_not_flag_prose_or_other_services(self):
+ """The splice pass must not widen the blast radius: it is anchored on
+ a hermes-gateway identifier, so quoted prose and non-gateway hermes
+ services stay auto-approved."""
+ for cmd in (
+ 'launchctl kick"start" -k gui/501/ai.hermes.update-checker',
+ 'echo "restart the payment gateway"',
+ 'git commit -m "document the api gateway restart flow"',
+ ):
+ dangerous, _, _ = detect_dangerous_command(cmd)
+ assert dangerous is False, cmd
+
class TestGitDestructiveOps:
"""git reset --hard, push --force, clean -f, branch -D can destroy
diff --git a/tools/approval.py b/tools/approval.py
index ac5f4c3ee7a..83c2c18742a 100644
--- a/tools/approval.py
+++ b/tools/approval.py
@@ -2318,6 +2318,38 @@ def _is_verification_artifact_cleanup(command: str) -> bool:
return re.fullmatch(r"hermes-(?:verify|ad-hoc)-[A-Za-z0-9_.-]+", basename) is not None
+_GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION = (
+ "stop/restart hermes gateway via shell-spliced verb (kills running agents)"
+)
+
+
+def _is_shell_token_spliced_gateway_lifecycle(command: str) -> bool:
+ """Catch gateway-lifecycle verbs spelled with quote/backslash splicing.
+
+ ``_normalize_command_for_detection`` strips backslash escapes, so
+ ``kick\\start`` already reaches the launchctl pattern above. Quote
+ splicing does not: ``_deobfuscate_shell_word_for_detection`` is
+ deliberately scoped to command-position words (widening it would let
+ quoted prose like ``git commit -m "rm -rf /"`` match the destructive
+ patterns), and the spliced verb sits in an ARGUMENT position. So
+ ``launchctl kick"start" -k gui/501/ai.hermes.gateway`` auto-approved
+ while executing exactly as the gated ``kickstart`` form (#80269).
+
+ Delegate to ``cron.lifecycle_guard``, which tokenizes with shlex and is
+ anchored on a hermes-gateway identifier — reusing its prose
+ false-positive coverage instead of loosening the generic pattern
+ engine. This runs last, so an ordinary pattern match still wins and
+ keeps its more specific reason string. Unlike the guard's use inside
+ ``terminal_tool``, this layer only raises an approval prompt; the
+ non-bypassable block still lives in ``cron.lifecycle_guard``.
+ """
+ try:
+ from cron.lifecycle_guard import contains_gateway_lifecycle_command
+ except Exception:
+ return False
+ return contains_gateway_lifecycle_command(command)
+
+
def detect_dangerous_command(command: str) -> tuple:
"""Check if a command matches any dangerous patterns.
@@ -2338,6 +2370,12 @@ def detect_dangerous_command(command: str) -> tuple:
normalized = _normalize_command_for_detection(command)
for description, _ in _execution_flag_findings(normalized):
return (True, description, description)
+ if _is_shell_token_spliced_gateway_lifecycle(command):
+ return (
+ True,
+ _GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION,
+ _GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION,
+ )
return (False, None, None)