Skip to content

Commit 10e8e56

Browse files
committed
fix(commands): reject unterminated-quote commands from auto-approval
Add findUnterminatedQuote, a quote-aware state-machine scanner that detects a command containing an unclosed quote (a shell syntax error, common in LLM-generated commands with nested quotes). parseCommand now returns such input as a single opaque token instead of splitting on embedded newlines, so a line intended to live inside the unclosed quote cannot surface as an independently auto-approvable sub-command. The scanner returns { quoteType, openIndex } to support a future execution-layer rejection that surfaces a located error to the model; that pre-execution rejection is intentionally deferred to a follow-up.
1 parent f05687a commit 10e8e56

3 files changed

Lines changed: 244 additions & 2 deletions

File tree

‎.changeset/fix-multiline-quoted-command-parsing.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,6 @@
22
"zoo-code": patch
33
---
44

5-
Fix command auto-approval for a single command that wraps a multi-line script in a quoted argument (e.g. `sh -c '...'`). The parser previously split on every newline before handling quotes, so newlines inside a quoted argument were treated as separate commands, which defeated allowlist auto-approval and produced a noisy command-pattern breakdown. Single-quoted and ANSI-C (`$'...'`) strings are now masked correctly so embedded newlines and operators stay within their command. Genuine unquoted newlines still split into separate sub-commands, each of which must be allowlisted for auto-approval.
5+
Fix command auto-approval for a single command that wraps a multi-line script in a quoted argument (e.g. `sh -c '...'`). The parser previously split on every newline before handling quotes, so newlines inside a quoted argument were treated as separate commands, which defeated allowlist auto-approval and produced a noisy command-pattern breakdown. Single-quoted and ANSI-C (`$'...'`) strings are now masked correctly so embedded newlines and operators stay within their command. Genuine unquoted newlines still split into separate sub-commands, each of which must be allowlisted for auto-approval. Commands with an unterminated quote (a shell syntax error, common in LLM-generated commands with nested quotes) are now detected with a quote-aware scanner and returned as a single opaque token, so a line intended to live inside the unclosed quote can no longer surface as an independently auto-approvable command.
6+
7+
Note: this change only prevents *auto-approval* of fragments from a malformed command; it does not reject malformed commands before execution, which will be addressed in a separate PR to keep the scope focused here.

‎src/shared/__tests__/parse-command.spec.ts‎

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { parseCommand } from "../parse-command"
1+
import { findUnterminatedQuote, parseCommand } from "../parse-command"
22

33
// Toggle that lets a single test force shell-quote's parse() to throw so the
44
// parser's fallback branch can be exercised deterministically.
@@ -169,4 +169,98 @@ describe("parseCommand", () => {
169169
expect(result.join(" ")).not.toContain("__")
170170
})
171171
})
172+
173+
describe("malformed input with unterminated quotes", () => {
174+
// A command with an unterminated quote is a shell syntax error. It must
175+
// be returned as a single opaque token so that an embedded newline cannot
176+
// surface a line as an independent, separately auto-approvable command.
177+
it("returns an unclosed single-quoted command as one opaque token", () => {
178+
const input = "sh -c 'echo test"
179+
expect(parseCommand(input)).toEqual([input])
180+
})
181+
182+
it("does not split an unclosed single quote on an embedded newline", () => {
183+
const input = "sh -c 'echo a\nrm -rf /"
184+
// Without the guard, this would yield ["sh -c echo a", "rm -rf /"],
185+
// exposing `rm -rf /` as a standalone command.
186+
expect(parseCommand(input)).toEqual([input])
187+
})
188+
189+
it("returns an unclosed double-quoted command as one opaque token", () => {
190+
const input = 'sh -c "echo a\necho b'
191+
expect(parseCommand(input)).toEqual([input])
192+
})
193+
194+
it("returns an unclosed ANSI-C quoted command as one opaque token", () => {
195+
const input = "sh -c $'echo a\necho b"
196+
expect(parseCommand(input)).toEqual([input])
197+
})
198+
199+
it("treats odd-quote improper quoting as a single opaque token", () => {
200+
const input = "sh -c 'cmd ''\\\n"
201+
expect(parseCommand(input)).toEqual([input])
202+
})
203+
})
204+
205+
describe("findUnterminatedQuote", () => {
206+
it("returns null for balanced and quote-free input", () => {
207+
expect(findUnterminatedQuote("git status")).toBeNull()
208+
expect(findUnterminatedQuote("echo 'hello'")).toBeNull()
209+
expect(findUnterminatedQuote('echo "hello"')).toBeNull()
210+
expect(findUnterminatedQuote("sh -c 'echo a\necho b'")).toBeNull()
211+
expect(findUnterminatedQuote("sh -c $'echo a\necho b'")).toBeNull()
212+
})
213+
214+
it("detects an unterminated single quote and reports its opening index", () => {
215+
expect(findUnterminatedQuote("echo 'hello")).toEqual({ quoteType: "posix-single", openIndex: 5 })
216+
})
217+
218+
it("detects an unterminated double quote and reports its opening index", () => {
219+
expect(findUnterminatedQuote('echo "hello')).toEqual({ quoteType: "double", openIndex: 5 })
220+
})
221+
222+
it("reports ansi-c style and the $ position for an unterminated ANSI-C quote", () => {
223+
expect(findUnterminatedQuote("echo $'hello")).toEqual({ quoteType: "ansi-c", openIndex: 5 })
224+
})
225+
226+
it("treats a backslash-escaped quote outside a string as literal", () => {
227+
// `echo \'` is a literal quote, not an unterminated region.
228+
expect(findUnterminatedQuote("echo \\'")).toBeNull()
229+
expect(findUnterminatedQuote('echo \\"')).toBeNull()
230+
})
231+
232+
it("ignores a quote that appears inside a comment", () => {
233+
expect(findUnterminatedQuote("echo hi # it's fine")).toBeNull()
234+
})
235+
236+
it("treats # attached to a word as an ordinary character", () => {
237+
expect(findUnterminatedQuote("echo foo#'bar'")).toBeNull()
238+
expect(findUnterminatedQuote("echo foo#'bar")).toEqual({ quoteType: "posix-single", openIndex: 9 })
239+
})
240+
241+
it("does not let an apostrophe inside double quotes open a region", () => {
242+
expect(findUnterminatedQuote(`echo "don't"`)).toBeNull()
243+
})
244+
245+
it("does not let a double quote inside single quotes open a region", () => {
246+
expect(findUnterminatedQuote(`echo 'a " b'`)).toBeNull()
247+
})
248+
249+
it("honors backslash escapes inside double quotes", () => {
250+
// The escaped quote does not close the region; the final quote does.
251+
expect(findUnterminatedQuote('echo "a \\" b"')).toBeNull()
252+
expect(findUnterminatedQuote('echo "a \\"')?.quoteType).toBe("double")
253+
})
254+
255+
it("honors backslash escapes inside ANSI-C quotes", () => {
256+
expect(findUnterminatedQuote("echo $'it\\'s ok'")).toBeNull()
257+
expect(findUnterminatedQuote("echo $'it\\'s ok")?.quoteType).toBe("ansi-c")
258+
})
259+
260+
it("treats POSIX single quotes as opaque to backslashes", () => {
261+
// Inside a POSIX single quote a backslash is literal, so the quote
262+
// closes at the next apostrophe regardless of any preceding backslash.
263+
expect(findUnterminatedQuote("echo 'a\\'")).toBeNull()
264+
})
265+
})
172266
})

‎src/shared/parse-command.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,139 @@ import { parse } from "shell-quote"
22

33
export type ShellToken = string | { op: string } | { command: string }
44

5+
/**
6+
* The style of quoting that opened a region. Distinguishing `posix-single` from
7+
* `ansi-c` matters because they share the `'` delimiter but follow different
8+
* escaping rules.
9+
*/
10+
export type QuoteType = "posix-single" | "ansi-c" | "double"
11+
12+
/**
13+
* Describes the opening of a quoted region that is never closed.
14+
*
15+
* - `quoteType`: the style of the unterminated quote.
16+
* - `openIndex`: the index in the original command string of the character that
17+
* opened the region. For ANSI-C quoting this points at the leading `$` so a
18+
* caller can render the `$'` opener. This position lets a future caller emit a
19+
* located error (e.g. "unterminated quote near ...") instead of a generic
20+
* message.
21+
*/
22+
export interface UnterminatedQuote {
23+
quoteType: QuoteType
24+
openIndex: number
25+
}
26+
27+
/**
28+
* Scan a command string left-to-right with a small state machine and report the
29+
* first quoted region that is never closed, or `null` when every quoted region
30+
* is properly terminated.
31+
*
32+
* A regex cannot reliably answer "is this command well-quoted?" because quoting
33+
* is context-sensitive: a backslash escapes the next character outside single
34+
* quotes, `#` may begin a comment that should be ignored, and an apostrophe
35+
* inside double quotes (or vice versa) is literal text rather than a delimiter.
36+
* This walk mirrors how a POSIX shell tokenizes quoting so that legitimate
37+
* multi-line quoted arguments are accepted while genuinely unterminated quotes
38+
* (a shell syntax error) are detected.
39+
*
40+
* Rules implemented:
41+
* - Outside any quote, a backslash escapes the following character, so `\'` and
42+
* `\"` are literal and do not open a region.
43+
* - Outside any quote, `#` begins a comment when it is at the start of the input
44+
* or preceded by whitespace; the remainder of that line is ignored. A `#` that
45+
* is attached to a word (e.g. `foo#bar`) is an ordinary character.
46+
* - Single quotes are opaque: no escapes apply, and the region ends only at the
47+
* next `'`.
48+
* - Double quotes honor backslash escapes, so `\"` does not close the region.
49+
* - ANSI-C quoting ($'...') behaves like a single-quoted region for delimiter
50+
* purposes but honors backslash escapes, so `\'` does not close it.
51+
*/
52+
export function findUnterminatedQuote(command: string): UnterminatedQuote | null {
53+
let inSingle = false
54+
let inDouble = false
55+
// Tracks whether the current single-quoted region was opened as ANSI-C
56+
// ($'...'), which -- unlike a POSIX single quote -- honors backslash escapes.
57+
let singleIsAnsiC = false
58+
// Index of the character that opened the currently active quoted region.
59+
let openIndex = -1
60+
61+
for (let i = 0; i < command.length; i++) {
62+
const char = command[i]
63+
64+
if (inSingle) {
65+
if (singleIsAnsiC && char === "\\") {
66+
// Skip the escaped character inside an ANSI-C string.
67+
i++
68+
continue
69+
}
70+
if (char === "'") {
71+
inSingle = false
72+
singleIsAnsiC = false
73+
}
74+
continue
75+
}
76+
77+
if (inDouble) {
78+
if (char === "\\") {
79+
// Skip the escaped character inside a double-quoted string.
80+
i++
81+
continue
82+
}
83+
if (char === '"') {
84+
inDouble = false
85+
}
86+
continue
87+
}
88+
89+
// Outside any quoted region.
90+
if (char === "\\") {
91+
// A backslash escapes the next character, so a following quote is
92+
// literal and must not open a region.
93+
i++
94+
continue
95+
}
96+
97+
if (char === "#" && (i === 0 || /\s/.test(command[i - 1]))) {
98+
// Start of a comment: skip to the end of the current line.
99+
while (i < command.length && command[i] !== "\n" && command[i] !== "\r") {
100+
i++
101+
}
102+
continue
103+
}
104+
105+
if (char === "$" && command[i + 1] === "'") {
106+
// ANSI-C quoting opens an escape-aware single-quoted region. The
107+
// opener position points at the leading $ so callers can show $'.
108+
inSingle = true
109+
singleIsAnsiC = true
110+
openIndex = i
111+
i++
112+
continue
113+
}
114+
115+
if (char === "'") {
116+
inSingle = true
117+
singleIsAnsiC = false
118+
openIndex = i
119+
continue
120+
}
121+
122+
if (char === '"') {
123+
inDouble = true
124+
openIndex = i
125+
continue
126+
}
127+
}
128+
129+
if (inSingle) {
130+
return { quoteType: singleIsAnsiC ? "ansi-c" : "posix-single", openIndex }
131+
}
132+
if (inDouble) {
133+
return { quoteType: "double", openIndex }
134+
}
135+
return null
136+
}
137+
5138
/**
6139
* Split a command string into individual sub-commands by
7140
* chaining operators (&&, ||, ;, |, or &) and unquoted newlines.
@@ -29,6 +162,19 @@ export function parseCommand(command: string): string[] {
29162
return []
30163
}
31164

165+
// Reject syntactically malformed input with an unterminated quote. Splitting
166+
// such a command on newlines is unsafe: a line intended to live inside the
167+
// unclosed quoted region would surface as an independent sub-command and
168+
// could be auto-approved in isolation (e.g. `sh -c 'echo a\nrm -rf /` would
169+
// otherwise yield a standalone `rm -rf /`). Returning the whole raw input as
170+
// a single opaque token forces every auto-approval check to match the entire
171+
// string, which is effectively never on an allowlist, so the user is
172+
// prompted. LLM-generated commands with nested quotes hit this case often
173+
// enough to warrant explicit handling rather than best-effort splitting.
174+
if (findUnterminatedQuote(command) !== null) {
175+
return [command]
176+
}
177+
32178
// Mask quoted strings (both single and double) before splitting on newlines.
33179
// This ensures that newlines embedded inside a quoted argument are not
34180
// mistaken for command separators. Both quote styles are handled here because

0 commit comments

Comments
 (0)