The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(approval): stop treating newlines inside quoted arguments as command starts
Tekniumd127fb219715
diff --git a/tests/tools/test_hardline_blocklist.py b/tests/tools/test_hardline_blocklist.pyindex 44e57b5d40b..40b1c567555 100644--- a/tests/tools/test_hardline_blocklist.py+++ b/tests/tools/test_hardline_blocklist.py@@ -239,6 +239,74 @@ def test_quoted_and_brace_paths_are_hardline_blocked(command):assert desc+# Multi-line QUOTED arguments are data, not command sequences: a newline+# inside quotes is part of the argument the shell passes to the program.+# These previously tripped the hardline floor because the flat command-start+# class treated every raw newline — even inside quotes — as a command+# boundary, blocking `hermes send` message bodies, multi-line+# `git commit -m` messages, and heredoc text that merely MENTION+# shutdown/reboot commands.+_QUOTED_NEWLINE_DATA_ALLOW = [+ # hermes send with a multi-line message body (the reported symptom)+ 'hermes send -t telegram -s "spark1" "console output:\nsudo reboot\ndone"',+ 'hermes send -t telegram "line1\nshutdown -h now\nline3"',+ # git commit -m with a multi-line message+ "git commit -m 'ops notes:\nreboot the box after the deploy'",+ 'git commit -m "fix startup\nsystemctl reboot was flaky here"',+ # heredoc bodies quoting dangerous strings as data+ "python3 - <<'EOF'\nmsg = 'run sudo reboot later'\nprint(msg)\nEOF",+ "cat > /tmp/notes.txt <<'EOF'\nremember: shutdown -h now\nEOF",+ # rm hardline floor is anchored to the same class — quoted prose about it+ # across a line break must stay data too+ 'git commit -m "docs:\nwarn about rm -rf / in the guide"',+]++# The masking must be strictly scoped to quoted data: real command+# boundaries around/inside those same shapes still hit the floor.+_QUOTED_NEWLINE_THREATS_BLOCK = [+ # unquoted newline is a real command separator+ "echo hi\nsudo reboot",+ 'echo "a"\nsudo reboot',+ 'git commit -m "safe message"\nshutdown -h now',+ # command substitution inside double quotes really executes+ 'hermes send -t telegram "$(sudo reboot)"',+ 'echo "`shutdown -h now`"',+ # multi-line quoted data followed by a REAL chained command+ 'hermes send "line1\nline2" && sudo reboot',+ # a heredoc whose body is data, but the delivery command itself is hardline+ "sudo reboot <<'EOF'\nignored\nEOF",+]++[email protected]("command", _QUOTED_NEWLINE_DATA_ALLOW)+def test_quoted_newline_data_not_blocked(command):+ """Newlines inside quoted arguments are data, not command starts."""+ is_hl, desc = detect_hardline_command(command)+ assert not is_hl, (+ f"multi-line quoted data false-positived the hardline floor: "+ f"{command!r} (got: {desc})"+ )++[email protected]("command", _QUOTED_NEWLINE_THREATS_BLOCK)+def test_real_newline_separated_threats_still_blocked(command):+ """Unquoted newlines / $() / backticks remain real command boundaries."""+ is_hl, desc = detect_hardline_command(command)+ assert is_hl, f"real threat leaked through hardline floor: {command!r}"+ assert desc+++def test_quoted_newline_data_not_blocked_by_full_guard_chain(clean_session):+ """End-to-end: the guard chain must not hardline-block a multi-line+ quoted message (yolo on, so only the unconditional floor can block)."""+ enable_session_yolo("hardline_test")+ command = 'hermes send -t telegram "status:\nsudo reboot happened at 3am"'+ result = check_all_command_guards(command, "local")+ assert result["approved"], (+ f"guard chain blocked multi-line quoted data: {result.get('message')}"+ )++# Commands that carry the literal string "rm -rf /" (or a sibling) as DATA in# another command's quoted argument — a PR title, a commit message, an echo /# printf argument. The shell never executes that text as an rm command, so thediff --git a/tools/approval.py b/tools/approval.pyindex 48edfa2f3af..151e5340655 100644--- a/tools/approval.py+++ b/tools/approval.py@@ -2004,6 +2004,54 @@ def _mark_command_starts(command: str) -> str:return "".join(parts)+def _mask_quoted_newlines(command: str) -> str:+ """Replace raw newlines inside single/double quotes with a space.++ Detection-only rewrite. A newline inside a quoted string is DATA to the+ shell — part of the argument, not a command separator — yet the flat+ ``_CMDPOS`` start-position class treats every raw ``\\n`` as a command+ start. That made any multi-line quoted argument (``hermes send`` message+ bodies, ``git commit -m`` messages, heredoc text) trip the hardline+ blocklist when a data line began with e.g. ``sudo reboot``.++ Quote tracking mirrors ``_iter_shell_command_starts``: single quotes are+ literal until the closing quote; inside double quotes a backslash escapes+ the next character. Real command boundaries are unaffected: unquoted+ newlines pass through untouched, ``$(``/backtick remain ``_CMDPOS``+ anchors independent of newlines, and ``_mark_command_starts`` still+ re-inserts newlines at every genuine quote-aware command start. An+ unclosed quote absorbs following newlines exactly as the shell would+ (the quoted word continues across the line break), so masking them+ cannot hide a runnable command.+ """+ if "\n" not in command:+ return command+ out: list[str] = []+ quote: str | None = None+ i = 0+ while i < len(command):+ ch = command[i]+ if quote:+ if ch == "\\" and quote == '"' and i + 1 < len(command):+ out.append(command[i:i + 2])+ i += 2+ continue+ if ch == quote:+ quote = None+ out.append(" " if ch == "\n" else ch)+ i += 1+ continue+ if ch in ("'", '"'):+ quote = ch+ elif ch == "\\" and i + 1 < len(command):+ out.append(command[i:i + 2])+ i += 2+ continue+ out.append(ch)+ i += 1+ return "".join(out)++def _iter_shell_command_word_spans(command: str):"""Yield command-position words that may be executable names."""for command_start in _iter_shell_command_starts(command):@@ -2047,7 +2095,13 @@ def _iter_shell_command_word_spans(command: str):def _command_detection_variants(command: str):- normalized = _normalize_command_for_detection(command)+ # Mask quoted newlines BEFORE normalization: normalization strips+ # backslash-escapes (\" -> ") and empty-string pairs (""), which would+ # corrupt quote tracking — e.g. `echo "a\""` normalizes to `echo "a` (an+ # unterminated quote), so masking the normalized text could swallow a+ # REAL unquoted newline separator that follows. The raw command carries+ # faithful shell quote state.+ normalized = _normalize_command_for_detection(_mask_quoted_newlines(command))# Quote-aware grep parsing hides only structurally identified pattern# operands. Malformed/ambiguous input remains byte-for-byte intact.grep_safe, _ = _grep_safe_detection_variant(normalized)