Skip to content

Commit f070880

Browse files
committed
fix(commands): treat multi-line quoted argument as a single command for auto-approval
parseCommand split on every newline before any quote handling, so newlines inside a quoted argument (e.g. a multi-line script passed to sh -c) were treated as separate commands. Single-quoted and ANSI-C ($'...') strings were also not fully masked, leaking placeholders and bogus sub-commands. This defeated allowlist auto-approval and produced a noisy command-pattern breakdown in the UI. Mask quoted strings (single, double, ANSI-C) before splitting on unquoted newlines, using a single left-to-right alternation so a quote of one style inside the other does not start a spurious match. Genuine unquoted newlines still split into separate sub-commands.
1 parent 5bf98fc commit f070880

5 files changed

Lines changed: 292 additions & 13 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"zoo-code": patch
3+
---
4+
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.

‎src/core/auto-approval/__tests__/commands.spec.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,51 @@ describe("getCommandDecision — integration with dangerous substitution checks"
9999
expect(getCommandDecision('echo "${var@P}"', allowedCommands)).toBe("ask_user")
100100
})
101101
})
102+
103+
describe("getCommandDecision — multi-line script wrapped in a quoted argument", () => {
104+
// A wrapper command (e.g. sh -c '...') carrying a multi-line script as a
105+
// single quoted argument must be treated as one command. The embedded
106+
// newlines belong to the quoted string and must not be mistaken for a
107+
// multi-statement sequence that would defeat allowlist auto-approval.
108+
const wrappedSingleQuoted = [
109+
`sh -c 'kubectl exec pod -- python3 -c "`,
110+
`import urllib.request`,
111+
`url = \\"http://127.0.0.1:49527/\\"`,
112+
`try:`,
113+
` with urllib.request.urlopen(url, timeout=10) as r:`,
114+
` print(r.status)`,
115+
`except Exception as e:`,
116+
` print(\\"fetch failed:\\", e)`,
117+
`"'`,
118+
].join("\n")
119+
120+
it("auto-approves a multi-line single-quoted script when the wrapper prefix is allowed", () => {
121+
expect(getCommandDecision(wrappedSingleQuoted, ["sh"])).toBe("auto_approve")
122+
})
123+
124+
it("auto-approves a multi-line double-quoted script when the wrapper prefix is allowed", () => {
125+
const wrappedDoubleQuoted = 'sh -c "echo line1\necho line2"'
126+
expect(getCommandDecision(wrappedDoubleQuoted, ["sh"])).toBe("auto_approve")
127+
})
128+
129+
it("asks user when the wrapper prefix is not in the allowlist", () => {
130+
expect(getCommandDecision(wrappedSingleQuoted, ["git"])).toBe("ask_user")
131+
})
132+
133+
it("still splits genuine multi-statement scripts and asks when a statement is not allowed", () => {
134+
// Real unquoted newlines separate independent statements; each must be on
135+
// the allowlist for auto-approval to engage.
136+
const multiStatement = "echo hello\nrm -rf /tmp/x"
137+
expect(getCommandDecision(multiStatement, ["echo"])).toBe("ask_user")
138+
})
139+
140+
it("auto-approves a genuine multi-statement script when every statement is allowed", () => {
141+
const multiStatement = "echo hello\nls -la"
142+
expect(getCommandDecision(multiStatement, ["echo", "ls"])).toBe("auto_approve")
143+
})
144+
145+
it("auto-approves an ANSI-C quoted ($'...') multi-line argument when the wrapper prefix is allowed", () => {
146+
const ansiC = "sh -c $'echo 1\necho 2'"
147+
expect(getCommandDecision(ansiC, ["sh"])).toBe("auto_approve")
148+
})
149+
})
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import { parseCommand } from "../parse-command"
2+
3+
describe("parseCommand", () => {
4+
describe("basic chaining", () => {
5+
it("returns empty array for empty input", () => {
6+
expect(parseCommand("")).toEqual([])
7+
expect(parseCommand(" ")).toEqual([])
8+
})
9+
10+
it("returns a single command unchanged", () => {
11+
expect(parseCommand("git status")).toEqual(["git status"])
12+
})
13+
14+
it("splits on &&", () => {
15+
expect(parseCommand("git add . && git commit")).toEqual(["git add .", "git commit"])
16+
})
17+
18+
it("splits on ||, ;, and |", () => {
19+
expect(parseCommand("a || b")).toEqual(["a", "b"])
20+
expect(parseCommand("a ; b")).toEqual(["a", "b"])
21+
expect(parseCommand("a | b")).toEqual(["a", "b"])
22+
})
23+
})
24+
25+
describe("genuine multi-statement scripts (unquoted newlines)", () => {
26+
it("splits unquoted newlines into separate sub-commands", () => {
27+
const input = "echo a\necho b\necho c"
28+
expect(parseCommand(input)).toEqual(["echo a", "echo b", "echo c"])
29+
})
30+
31+
it("handles Windows and old-Mac line endings", () => {
32+
expect(parseCommand("echo a\r\necho b")).toEqual(["echo a", "echo b"])
33+
expect(parseCommand("echo a\recho b")).toEqual(["echo a", "echo b"])
34+
})
35+
36+
it("ignores blank lines", () => {
37+
expect(parseCommand("echo a\n\n\necho b")).toEqual(["echo a", "echo b"])
38+
})
39+
})
40+
41+
describe("newlines inside single-quoted strings", () => {
42+
it("treats a multi-line single-quoted argument as one command", () => {
43+
const input = "sh -c 'echo a\necho b'"
44+
expect(parseCommand(input)).toEqual(["sh -c 'echo a\necho b'"])
45+
})
46+
47+
it("does not split operators that appear inside single quotes", () => {
48+
const input = "sh -c 'echo a && echo b | grep x'"
49+
expect(parseCommand(input)).toEqual(["sh -c 'echo a && echo b | grep x'"])
50+
})
51+
52+
it("preserves the embedded newline in the restored command", () => {
53+
const input = "sh -c 'echo 1\necho 2'"
54+
const result = parseCommand(input)
55+
expect(result).toEqual(["sh -c 'echo 1\necho 2'"])
56+
expect(result[0]).toContain("\n")
57+
})
58+
})
59+
60+
describe("ANSI-C quoting ($'...')", () => {
61+
it("does not leak a placeholder for a $'...' multi-line argument", () => {
62+
const input = "sh -c $'echo 1\necho 2'"
63+
const result = parseCommand(input)
64+
// The placeholder used internally must never appear in the output.
65+
expect(result.join(" ")).not.toContain("SQUOTE")
66+
expect(result.join(" ")).not.toContain("__")
67+
})
68+
})
69+
70+
describe("newlines inside double-quoted strings", () => {
71+
it("treats a multi-line double-quoted argument as one command", () => {
72+
const input = 'sh -c "echo a\necho b"'
73+
expect(parseCommand(input)).toEqual(['sh -c "echo a\necho b"'])
74+
})
75+
76+
it("does not split operators that appear inside double quotes", () => {
77+
const input = 'sh -c "echo a && echo b | grep x"'
78+
expect(parseCommand(input)).toEqual(['sh -c "echo a && echo b | grep x"'])
79+
})
80+
81+
it("handles escaped quotes inside a double-quoted string", () => {
82+
const input = 'sh -c "echo \\"hello world\\""'
83+
expect(parseCommand(input)).toEqual(['sh -c "echo \\"hello world\\""'])
84+
})
85+
})
86+
87+
describe("mixed quote styles", () => {
88+
it("does not let an apostrophe inside double quotes start a single-quoted region", () => {
89+
const input = `echo "don't" && echo ok`
90+
expect(parseCommand(input)).toEqual([`echo "don't"`, "echo ok"])
91+
})
92+
93+
it("does not let a double quote inside single quotes start a double-quoted region", () => {
94+
const input = `echo 'a " b' && echo ok`
95+
expect(parseCommand(input)).toEqual([`echo 'a " b'`, "echo ok"])
96+
})
97+
})
98+
99+
describe("real-world wrapped multi-line script (regression)", () => {
100+
it("treats a wrapper command with an embedded multi-line script as a single command", () => {
101+
const input = [
102+
`sh -c 'kubectl exec pod -- python3 -c "`,
103+
`import urllib.request`,
104+
`url = \\"http://127.0.0.1:49527/\\"`,
105+
`try:`,
106+
` with urllib.request.urlopen(url, timeout=10) as r:`,
107+
` for k, v in r.headers.items():`,
108+
` print(f\\"{k}: {v}\\")`,
109+
`except Exception as e:`,
110+
` print(\\"fetch failed:\\", type(e).__name__, e)`,
111+
`"'`,
112+
].join("\n")
113+
114+
const result = parseCommand(input)
115+
expect(result).toHaveLength(1)
116+
expect(result[0]).toBe(input)
117+
})
118+
})
119+
120+
describe("subshells still split", () => {
121+
it("extracts subshell content as separate commands", () => {
122+
const result = parseCommand("echo $(whoami)")
123+
expect(result).toContain("whoami")
124+
})
125+
})
126+
})

‎src/shared/parse-command.ts‎

Lines changed: 77 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,66 @@ export type ShellToken = string | { op: string } | { command: string }
44

55
/**
66
* Split a command string into individual sub-commands by
7-
* chaining operators (&&, ||, ;, |, or &) and newlines.
7+
* chaining operators (&&, ||, ;, |, or &) and unquoted newlines.
88
*
99
* Uses shell-quote to properly handle:
10-
* - Quoted strings (preserves quotes)
10+
* - Quoted strings (preserves quotes, including multi-line quoted strings)
1111
* - Subshell commands ($(cmd), `cmd`, <(cmd), >(cmd))
1212
* - PowerShell redirections (2>&1)
1313
* - Chain operators (&&, ||, ;, |, &)
14-
* - Newlines as command separators
14+
* - Newlines as command separators (only when outside quoted strings)
15+
*
16+
* Key invariant: newlines that appear inside a quoted string (single or double)
17+
* are part of that string argument and must NOT be treated as command separators.
18+
* Only unquoted newlines split commands. For example:
19+
*
20+
* sh -c 'python3 -c "
21+
* import sys
22+
* print(sys.version)
23+
* "'
24+
*
25+
* ...is a single command, not multiple commands split at each newline.
1526
*/
1627
export function parseCommand(command: string): string[] {
1728
if (!command?.trim()) {
1829
return []
1930
}
2031

21-
// Split by newlines first (handle different line ending formats)
22-
// This regex splits on \r\n (Windows), \n (Unix), or \r (old Mac)
23-
const lines = command.split(/\r\n|\r|\n/)
32+
// Mask quoted strings (both single and double) before splitting on newlines.
33+
// This ensures that newlines embedded inside a quoted argument are not
34+
// mistaken for command separators. Both quote styles are handled here because
35+
// either can span multiple lines (e.g. a heredoc-style script passed as a
36+
// single argument to sh -c '...' or a double-quoted multi-line string).
37+
//
38+
// A single left-to-right scan with an alternation is used (rather than two
39+
// separate passes) so that whichever quote opens first wins. This prevents a
40+
// quote of one style that appears inside a string of the other style from
41+
// starting a spurious match -- e.g. the apostrophe in "don't" must not begin
42+
// a single-quoted region, and a double quote inside 'a "b' must not begin a
43+
// double-quoted region. Negated character classes match newlines, so
44+
// multi-line quoted strings are captured whole.
45+
const topLevelQuotes: string[] = []
46+
47+
const masked = command.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, (match) => {
48+
topLevelQuotes.push(match)
49+
return `__TOPLEVEL_QUOTE_${topLevelQuotes.length - 1}__`
50+
})
51+
52+
// Split on unquoted newlines (all line-ending formats).
53+
const lines = masked.split(/\r\n|\r|\n/)
2454
const allCommands: string[] = []
2555

2656
for (const line of lines) {
27-
// Skip empty lines
2857
if (!line.trim()) {
2958
continue
3059
}
3160

32-
// Process each line through the existing parsing logic
33-
const lineCommands = parseCommandLine(line)
61+
// Restore top-level quote placeholders before per-line parsing so that
62+
// parseCommandLine sees the original quoted content and can apply its own
63+
// masking for operator splitting.
64+
const restoredLine = line.replace(/__TOPLEVEL_QUOTE_(\d+)__/g, (_, i) => topLevelQuotes[parseInt(i)])
65+
66+
const lineCommands = parseCommandLine(restoredLine)
3467
allCommands.push(...lineCommands)
3568
}
3669

@@ -47,6 +80,7 @@ function parseCommandLine(command: string): string[] {
4780
const redirections: string[] = []
4881
const subshells: string[] = []
4982
const quotes: string[] = []
83+
const singleQuotes: string[] = []
5084
const arrayIndexing: string[] = []
5185
const arithmeticExpressions: string[] = []
5286
const variables: string[] = []
@@ -84,6 +118,17 @@ function parseCommandLine(command: string): string[] {
84118
return `__SUBSH_${subshells.length - 1}__`
85119
})
86120

121+
// Handle ANSI-C quoting: $'...'. This must run before variable masking so the
122+
// leading $ is captured as part of the quoted unit rather than being treated
123+
// as a variable expansion (which would corrupt a following placeholder).
124+
// ANSI-C strings interpret backslash escapes, so the pattern is escape-aware.
125+
// The whole token (including the $ and quotes) is preserved in the single-
126+
// quote bucket so it is restored verbatim.
127+
processedCommand = processedCommand.replace(/\$'(?:[^'\\]|\\.)*'/g, (match) => {
128+
singleQuotes.push(match)
129+
return `__SQUOTE_${singleQuotes.length - 1}__`
130+
})
131+
87132
// Handle simple variable references: $varname pattern
88133
// This prevents shell-quote from splitting $count into separate tokens
89134
processedCommand = processedCommand.replace(/\$[a-zA-Z_][a-zA-Z0-9_]*/g, (match) => {
@@ -108,8 +153,22 @@ function parseCommandLine(command: string): string[] {
108153
return `__SUBSH_${subshells.length - 1}__`
109154
})
110155

111-
// Then handle quoted strings
112-
processedCommand = processedCommand.replace(/"[^"]*"/g, (match) => {
156+
// Mask quoted strings (single and double) so their contents -- including
157+
// operators like &&, |, ; and any embedded newlines -- are not treated as
158+
// command separators. A single left-to-right scan with an alternation is used
159+
// so that whichever quote opens first wins, preventing a quote of one style
160+
// inside a string of the other style from starting a spurious match.
161+
//
162+
// Single quotes are matched literally (POSIX single quotes are fully opaque,
163+
// no escaping inside them). Double quotes use an escape-aware pattern so that
164+
// an escaped quote (\") does not prematurely terminate the match. Negated
165+
// character classes match newlines, so multi-line quoted strings are captured
166+
// as a single token.
167+
processedCommand = processedCommand.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, (match) => {
168+
if (match.startsWith("'")) {
169+
singleQuotes.push(match)
170+
return `__SQUOTE_${singleQuotes.length - 1}__`
171+
}
113172
quotes.push(match)
114173
return `__QUOTE_${quotes.length - 1}__`
115174
})
@@ -132,6 +191,7 @@ function parseCommandLine(command: string): string[] {
132191
restorePlaceholders(
133192
cmd,
134193
quotes,
194+
singleQuotes,
135195
redirections,
136196
arrayIndexing,
137197
arithmeticExpressions,
@@ -177,11 +237,12 @@ function parseCommandLine(command: string): string[] {
177237
commands.push(currentCommand.join(" "))
178238
}
179239

180-
// Restore quotes and redirections
240+
// Restore all placeholders
181241
return commands.map((cmd) =>
182242
restorePlaceholders(
183243
cmd,
184244
quotes,
245+
singleQuotes,
185246
redirections,
186247
arrayIndexing,
187248
arithmeticExpressions,
@@ -198,6 +259,7 @@ function parseCommandLine(command: string): string[] {
198259
function restorePlaceholders(
199260
command: string,
200261
quotes: string[],
262+
singleQuotes: string[],
201263
redirections: string[],
202264
arrayIndexing: string[],
203265
arithmeticExpressions: string[],
@@ -206,8 +268,10 @@ function restorePlaceholders(
206268
subshells: string[],
207269
): string {
208270
let result = command
209-
// Restore quotes
271+
// Restore double-quoted strings
210272
result = result.replace(/__QUOTE_(\d+)__/g, (_, i) => quotes[parseInt(i)])
273+
// Restore single-quoted strings
274+
result = result.replace(/__SQUOTE_(\d+)__/g, (_, i) => singleQuotes[parseInt(i)])
211275
// Restore redirections
212276
result = result.replace(/__REDIR_(\d+)__/g, (_, i) => redirections[parseInt(i)])
213277
// Restore array indexing expressions

‎webview-ui/src/components/chat/__tests__/CommandExecution.spec.tsx‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,4 +605,40 @@ Output:
605605
expect(terminalOutput).toHaveTextContent("0 total")
606606
})
607607
})
608+
609+
describe("multi-line script wrapped in a quoted argument", () => {
610+
// A wrapper command carrying a multi-line script inside a single quoted
611+
// argument must be treated as one command. The pattern breakdown must not
612+
// surface stray fragments from the embedded script lines, which would both
613+
// clutter the UI and defeat allowlist auto-approval.
614+
const wrappedCommand = [
615+
`sh -c 'kubectl exec pod -- python3 -c "`,
616+
`import urllib.request`,
617+
`url = \\"http://127.0.0.1:49527/\\"`,
618+
`print(url)`,
619+
`"'`,
620+
].join("\n")
621+
622+
it("does not surface stray script-line fragments in the pattern selector", () => {
623+
render(
624+
<ExtensionStateWrapper>
625+
<CommandExecution executionId="test-multiline" text={wrappedCommand} />
626+
</ExtensionStateWrapper>,
627+
)
628+
629+
const selector = screen.getByTestId("command-pattern-selector")
630+
631+
// The wrapper command should be present as a single pattern.
632+
expect(selector.textContent).toContain("sh")
633+
634+
// Each script line is rendered as its own <span> only if it was split
635+
// into a separate command. Assert no span exactly equals a script-line
636+
// fragment that would indicate erroneous splitting.
637+
const fragments = Array.from(selector.querySelectorAll("span")).map((s) => s.textContent ?? "")
638+
expect(fragments).not.toContain("import")
639+
expect(fragments).not.toContain("import urllib.request")
640+
expect(fragments).not.toContain("url")
641+
expect(fragments).not.toContain("print")
642+
})
643+
})
608644
})

0 commit comments

Comments
 (0)