Skip to content

The agent that grows with you

fix(approval): a grep inside "$(...)" no longer trips the hardline "malformed payload" block

Tekniumd41f62107148
diff --git a/tests/tools/test_approval_grep_in_substitution.py b/tests/tools/test_approval_grep_in_substitution.py
new file mode 100644
index 00000000000..abfff1359b1
--- /dev/null
+++ b/tests/tools/test_approval_grep_in_substitution.py
@@ -0,0 +1,41 @@
+"""A grep nested inside a command substitution must lex as its own simple command.
+
+The quoted-grep scanner tokenizes from the grep's position to decide which quoted operand is inert data.
+It used to read to the end of the segment, so for ``"$(grep … | cut …)"`` it swallowed the enclosing
+command's closing quote, called the quoting unbalanced, and the whole command was reported as a hardline
+block. Every such report was a false positive (546 in one run); the lexer now stops at the end of the
+simple command: an unquoted ``;`` ``|`` ``&`` newline, or the ``)`` / backtick closing its substitution.
+"""
+import pytest
+
+from tools.approval_detection import _quoted_grep_pattern_spans, _shell_tokens_with_spans, detect_hardline_command
+
+
[email protected]("command", [
+ 'sed -n "$(grep -n X f | cut -d: -f1),+3p" f',
+ 'sed -n "$(grep -n \'^### 1.\' d.md | cut -d: -f1),$(grep -n \'^### 3.\' d.md | cut -d: -f1)p" d.md',
+ 'echo "$(grep -c x f)"',
+ 'x="$(grep -n foo bar | head -1)"; echo $x',
+ 'for f in a b; do echo "$f sig=$(grep -cE \'^x\' $f)"; done',
+ 'echo `grep -c x f`',
+])
+def test_grep_inside_a_substitution_is_not_malformed(command):
+ _spans, malformed = _quoted_grep_pattern_spans(command)
+ assert malformed is False
+ assert detect_hardline_command(command) == (False, None)
+
+
+def test_lexer_stops_at_the_end_of_the_simple_command():
+ seg = 'sed -n "$(grep -n X f | cut -d: -f1),+3p" f'
+ toks = _shell_tokens_with_spans(seg, seg.index("grep"))
+ assert [t[0] for t in toks] == ["grep", "-n", "X", "f"]
+
+
+def test_genuinely_unbalanced_quoting_still_fails_closed():
+ assert _shell_tokens_with_spans("grep 'unterminated", 0) is None
+ assert detect_hardline_command("grep 'unterminated")[0] is True
+
+
+def test_hardline_patterns_unchanged():
+ for command in ("rm -rf /", 'echo "$(rm -rf /)"', "sudo shutdown -h now"):
+ assert detect_hardline_command(command)[0] is True, command
diff --git a/tools/approval_detection.py b/tools/approval_detection.py
index 1ef703670a4..23b7613abda 100644
--- a/tools/approval_detection.py
+++ b/tools/approval_detection.py
@@ -581,8 +581,16 @@ def _command_parser_limit_exceeded(command: str) -> bool:
def _shell_tokens_with_spans(segment: str, start: int):
"""Return shell words as ``(value, start, end, quoted)`` or ``None`` on malformed quoting.
Deliberately small lexer that never expands shell syntax; it exists to keep source spans (which
- ``shlex`` does not expose) for deciding which quoted grep operand is data, not another command."""
+ ``shlex`` does not expose) for deciding which quoted grep operand is data, not another command.
+
+ Lexing stops at the end of the simple command that begins at *start*: an unquoted ``;``, ``|``,
+ ``&`` or newline, or the ``)`` / backtick that closes the substitution the command sits inside.
+ Without that, a grep nested as ``"$(grep … | cut …)"`` was lexed together with the enclosing
+ command's closing quote, read as unbalanced quoting, and reported as a hardline block (546
+ blocked turns in one run, every one a false positive; ``sed -n "$(grep -n X f | cut -d: -f1),+3p" f``
+ is the canonical shape)."""
tokens, value, token_start, quote = [], [], None, None
+ depth = 0 # $(...) nesting opened AFTER start; a closer at depth 0 ends the enclosing substitution
def flush(end: int) -> None:
raw = segment[token_start:end]
@@ -591,26 +599,39 @@ def _shell_tokens_with_spans(segment: str, start: int):
inert = (raw.startswith("'") and raw.endswith("'")) or ("='" in raw and raw.endswith("'"))
tokens.append(("".join(value), token_start, end, inert))
+ end_at = len(segment)
for kind, i, _, _ in _scan_shell(segment, start):
- if kind == "char" and not quote and segment[i].isspace():
- if token_start is not None:
- flush(i)
- value, token_start = [], None
- continue
+ ch = segment[i]
+ if kind == "char" and not quote:
+ if ch.isspace() and ch != "\n":
+ if token_start is not None:
+ flush(i)
+ value, token_start = [], None
+ continue
+ if segment.startswith("$(", i):
+ depth += 1
+ elif ch == ")" or ch == "`":
+ if depth == 0:
+ end_at = i
+ break
+ depth -= 1
+ elif ch in ";|&\n":
+ end_at = i
+ break
if token_start is None:
token_start = i
if kind == "quote":
- quote = None if quote else segment[i]
+ quote = None if quote else ch
elif kind == "esc":
value.append(segment[i + 1])
- elif segment[i] == "\\" and not quote:
+ elif ch == "\\" and not quote:
return None # dangling backslash
else:
- value.append(segment[i])
+ value.append(ch)
if quote:
return None
if token_start is not None:
- flush(len(segment))
+ flush(end_at)
return tokens