lean_ctx/core/shell_allowlist/tokenizer.rs
1/// Tokenize a shell command segment respecting single/double quotes and backslash escapes.
2/// Returns tokens with outer quotes stripped, matching how the shell would parse them.
3/// E.g. `git -C "Program Files" status` → `["git", "-C", "Program Files", "status"]`
4pub fn shell_tokenize(input: &str) -> Vec<String> {
5 let mut tokens = Vec::new();
6 let mut current = String::new();
7 let mut chars = input.chars().peekable();
8 let mut in_single = false;
9 let mut in_double = false;
10 let mut parameter_depth: u32 = 0;
11
12 while let Some(c) = chars.next() {
13 match c {
14 '\'' if !in_double => in_single = !in_single,
15 '"' if !in_single => in_double = !in_double,
16 '\\' if !in_single => {
17 // #1781: inside double quotes a backslash is literal unless it
18 // precedes `$`, `` ` ``, `"`, `\` or a newline (POSIX 2.2.3).
19 // The old arm consumed it unconditionally, so a quoted Windows
20 // path — `Start-Process "C:\Program Files\Docker\Docker Desktop.exe"`
21 // — tokenized as `C:Program FilesDockerDocker Desktop.exe`, and
22 // the allowlist then refused a fragment that was never a command
23 // and asked the user to report it. Outside quotes the escape
24 // still applies to any character, which `tokenize_backslash_escape`
25 // pins.
26 let escapes_next =
27 !in_double || matches!(chars.peek(), Some('$' | '`' | '"' | '\\' | '\n'));
28 if escapes_next {
29 if let Some(next) = chars.next() {
30 current.push(next);
31 }
32 } else {
33 current.push('\\');
34 }
35 }
36 '$' if !in_single && chars.peek() == Some(&'{') => {
37 parameter_depth += 1;
38 current.push(c);
39 }
40 '}' if !in_single && parameter_depth > 0 => {
41 parameter_depth -= 1;
42 current.push(c);
43 }
44 c if c.is_whitespace() && !in_single && !in_double && parameter_depth == 0 => {
45 if !current.is_empty() {
46 tokens.push(std::mem::take(&mut current));
47 }
48 }
49 _ => current.push(c),
50 }
51 }
52 if !current.is_empty() {
53 tokens.push(current);
54 }
55 tokens
56}
57
58/// Returns the byte length of the first shell token in `input`, respecting quotes
59/// and `(...)` nesting. Used by `skip_env_assignments` to advance past env
60/// assignments with quoted values like `FOO="bar baz"` — and, critically, past
61/// assignments whose value is a command substitution like `FOO=$(cmd a b)`
62/// (#855): without paren-depth tracking, whitespace *inside* the unclosed
63/// `$(...)` looked like the end of the token, splitting `s=$(gh pr view …)`
64/// into a bogus token `s=$(gh` plus a leftover `pr` that got misread as the
65/// base command.
66pub(super) fn quote_aware_token_end(input: &str) -> usize {
67 let bytes = input.as_bytes();
68 let len = bytes.len();
69 let mut i = 0;
70 let mut in_single = false;
71 let mut in_double = false;
72 let mut paren_depth: u32 = 0;
73 let mut parameter_depth: u32 = 0;
74
75 while i < len {
76 let ch = bytes[i];
77 match ch {
78 b'\'' if !in_double => {
79 in_single = !in_single;
80 i += 1;
81 }
82 b'"' if !in_single => {
83 in_double = !in_double;
84 i += 1;
85 }
86 b'\\' if !in_single => {
87 i = (i + 2).min(len);
88 }
89 b'(' if !in_single && !in_double => {
90 paren_depth += 1;
91 i += 1;
92 }
93 b')' if !in_single && !in_double && paren_depth > 0 => {
94 paren_depth -= 1;
95 i += 1;
96 }
97 b'$' if !in_single && !in_double && bytes.get(i + 1) == Some(&b'{') => {
98 parameter_depth += 1;
99 i += 1;
100 }
101 b'}' if !in_single && parameter_depth > 0 => {
102 parameter_depth -= 1;
103 i += 1;
104 }
105 b if b.is_ascii_whitespace()
106 && !in_single
107 && !in_double
108 && paren_depth == 0
109 && parameter_depth == 0 =>
110 {
111 return i;
112 }
113 _ => i += 1,
114 }
115 }
116 len
117}
118/// Extract ALL command segments from a compound shell command.
119/// Splits on: &&, ||, ;, | (pipe), and handles subshell grouping.
120pub(super) fn extract_all_commands(command: &str) -> Vec<String> {
121 split_on_operators(command)
122 .into_iter()
123 .map(|s| s.trim().to_string())
124 .filter(|s| !s.is_empty())
125 .collect()
126}
127
128/// One lexical context.
129///
130/// A command substitution starts a **fresh** one. POSIX says quoting restarts
131/// inside `$( … )`, so in `echo "$(python3 -c "a;b")"` the inner `"…"` is its
132/// own string and its `;` separates nothing (GH #1646). Tracking quotes as two
133/// flat booleans could not express that: the scanner never noticed `$(` while
134/// inside double quotes, so the inner opening quote *closed* the outer one,
135/// `a;b` looked unquoted, and the `;` split a bogus command out of a Python
136/// source line — which the allowlist then rejected with an unusable suggestion.
137///
138/// Treating the substitution as one word here loses no enforcement: its real
139/// contents are re-split and checked by `substitution::extract_substitution_commands`,
140/// which is where commands that a substitution genuinely *runs* are caught.
141#[derive(Clone, Copy)]
142struct Frame {
143 in_single_quote: bool,
144 in_double_quote: bool,
145 paren_depth: u32,
146 /// #939: brace groups (`{ cmd; }`) need the same operator-shielding as
147 /// `( cmd )` subshells — otherwise a `}` that closes a `{` opened on an
148 /// earlier physical line (e.g. after heredoc-body stripping collapses the
149 /// body between them) is misread as its own bare command segment.
150 brace_depth: u32,
151 /// #1793: `[[ … ]]` is a bash conditional *construct*, not a command, and
152 /// the `&&`/`||` inside it join predicates rather than commands. Without
153 /// shielding, `[[ -x a && -x b ]]` was split mid-condition into fragments
154 /// like `[[ -x a` and `-x b ]]`, none of which resolve to a real command.
155 bracket_depth: u32,
156 kind: FrameKind,
157}
158
159#[derive(Clone, Copy, PartialEq, Eq)]
160enum FrameKind {
161 /// The command line itself. Separators split only at this level.
162 Base,
163 /// Opened by `$(`, closed by the matching `)`.
164 DollarParen,
165 /// Opened and closed by a backtick — the older substitution form, same
166 /// quoting-restart rule.
167 Backtick,
168}
169
170impl Frame {
171 const fn new(kind: FrameKind) -> Self {
172 Self {
173 in_single_quote: false,
174 in_double_quote: false,
175 paren_depth: 0,
176 brace_depth: 0,
177 bracket_depth: 0,
178 kind,
179 }
180 }
181
182 /// Inside quotes, or inside a group whose closing delimiter is still open.
183 const fn shields_operators(&self) -> bool {
184 self.in_single_quote
185 || self.in_double_quote
186 || self.paren_depth > 0
187 || self.brace_depth > 0
188 || self.bracket_depth > 0
189 }
190}
191
192/// True when the two bytes at `i` form a standalone `[[` token — the opener of
193/// a bash conditional (#1793).
194///
195/// Bash requires `[[` to be its own word, and so does this: a word boundary
196/// before and whitespace after. That distinction is what keeps a glob character
197/// class (`ls a[[:alpha:]]`) or a nested array subscript (`${arr[[i]]}`) from
198/// opening a depth that would never close and swallow the rest of the line.
199fn opens_double_bracket(bytes: &[u8], i: usize) -> bool {
200 if bytes.get(i) != Some(&b'[') || bytes.get(i + 1) != Some(&b'[') {
201 return false;
202 }
203 let boundary_before = i == 0
204 || matches!(
205 bytes[i - 1],
206 b' ' | b'\t' | b'\n' | b'\r' | b';' | b'&' | b'|' | b'('
207 );
208 let space_after = matches!(bytes.get(i + 2), Some(b' ' | b'\t' | b'\n' | b'\r'));
209 boundary_before && space_after
210}
211
212/// True when the two bytes at `i` form a standalone `]]` token closing a
213/// conditional opened by [`opens_double_bracket`]. Mirrors its word-boundary
214/// rule: whitespace before, and a separator or end of input after.
215fn closes_double_bracket(bytes: &[u8], i: usize) -> bool {
216 if bytes.get(i) != Some(&b']') || bytes.get(i + 1) != Some(&b']') {
217 return false;
218 }
219 let space_before = i > 0 && matches!(bytes[i - 1], b' ' | b'\t' | b'\n' | b'\r');
220 let separator_after = matches!(
221 bytes.get(i + 2),
222 None | Some(b' ' | b'\t' | b'\n' | b'\r' | b';' | b'&' | b'|' | b')')
223 );
224 space_before && separator_after
225}
226
227/// Split command string on shell operators: ;, &&, ||, |
228/// Respects single/double quotes, parentheses nesting, and backslash escapes
229/// outside single quotes (GL #1160): `rg split\.label\|quantityLabel` is ONE
230/// command — the escaped pipe is regex data, not an operator. The old scanner
231/// split there and blocked the pattern fragment as an unknown command; same
232/// for `find … -exec rm {} \;`.
233pub(super) fn split_on_operators(command: &str) -> Vec<&str> {
234 split_with_separators(command)
235 .into_iter()
236 .map(|(segment, _)| segment)
237 .collect()
238}
239
240/// The operator that ends a command segment.
241///
242/// Where a segment runs can depend on it (#1850): a `cd` followed by `&&`
243/// moves the next command, one followed by `||` only runs the next command if
244/// it failed, and one in a pipeline or in the background moves nothing at all.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub enum Separator {
247 /// `;`, a newline or a carriage return.
248 Sequence,
249 /// `&&`
250 And,
251 /// `||`
252 Or,
253 /// `|`
254 Pipe,
255 /// A single `&`.
256 Background,
257}
258
259/// Every segment together with the separator that ends it; the last segment
260/// has none. Same scanner as `split_on_operators`, so the two never disagree
261/// about where a command ends.
262pub fn segments_with_separators(command: &str) -> Vec<(String, Option<Separator>)> {
263 split_with_separators(command)
264 .into_iter()
265 .map(|(segment, sep)| (segment.trim().to_string(), sep))
266 .filter(|(segment, _)| !segment.is_empty())
267 .collect()
268}
269
270fn split_with_separators(command: &str) -> Vec<(&str, Option<Separator>)> {
271 let mut segments = Vec::new();
272 let mut start = 0;
273 let bytes = command.as_bytes();
274 let len = bytes.len();
275 let mut i = 0;
276 // Stack, not booleans: see [`Frame`]. Index 0 is always the command line.
277 let mut stack: Vec<Frame> = vec![Frame::new(FrameKind::Base)];
278
279 while i < len {
280 let ch = bytes[i];
281 // `$(` and a backtick open a substitution wherever the shell would
282 // expand one: unquoted, or inside double quotes. Single quotes inhibit
283 // it entirely, which the single-quote arm below handles by consuming
284 // everything to the closing quote.
285 let opens_substitution = |i: usize| -> Option<(FrameKind, usize)> {
286 match bytes[i] {
287 b'$' if i + 1 < len && bytes[i + 1] == b'(' => Some((FrameKind::DollarParen, 2)),
288 b'`' => Some((FrameKind::Backtick, 1)),
289 _ => None,
290 }
291 };
292
293 let frame = *stack.last().expect("base frame is never popped");
294
295 if frame.in_single_quote {
296 if ch == b'\'' {
297 stack.last_mut().expect("frame").in_single_quote = false;
298 }
299 i += 1;
300 continue;
301 }
302
303 if frame.in_double_quote {
304 match ch {
305 // \" stays inside the string; \\ consumes both so `"x\\"` closes.
306 b'\\' => i = (i + 2).min(len),
307 b'"' => {
308 stack.last_mut().expect("frame").in_double_quote = false;
309 i += 1;
310 }
311 _ => {
312 if let Some((kind, width)) = opens_substitution(i) {
313 stack.push(Frame::new(kind));
314 i += width;
315 } else {
316 i += 1;
317 }
318 }
319 }
320 continue;
321 }
322
323 // Unquoted within the current frame.
324 if let Some((kind, width)) = opens_substitution(i) {
325 if kind == FrameKind::Backtick && frame.kind == FrameKind::Backtick {
326 // The same character closes a backtick substitution.
327 stack.pop();
328 } else {
329 stack.push(Frame::new(kind));
330 }
331 i += width;
332 continue;
333 }
334
335 let at_top = stack.len() == 1;
336 let unshielded = at_top && !frame.shields_operators();
337
338 // #1793: enter/leave a `[[ … ]]` conditional so its internal `&&`/`||`
339 // stay part of the condition. Both delimiters must be standalone words
340 // (see the helpers), so a glob class (`ls a[[:alpha:]]`) or an array
341 // subscript never opens a depth that would swallow the rest of the line.
342 if ch == b'[' && opens_double_bracket(bytes, i) {
343 stack.last_mut().expect("frame").bracket_depth += 1;
344 i += 2;
345 continue;
346 }
347 if ch == b']' && frame.bracket_depth > 0 && closes_double_bracket(bytes, i) {
348 let top = stack.last_mut().expect("frame");
349 top.bracket_depth = top.bracket_depth.saturating_sub(1);
350 i += 2;
351 continue;
352 }
353
354 match ch {
355 b'\\' => {
356 // Escaped char is data (bash semantics outside quotes) — never
357 // an operator or quote opener.
358 i = (i + 2).min(len);
359 }
360 b'\'' => {
361 stack.last_mut().expect("frame").in_single_quote = true;
362 i += 1;
363 }
364 b'"' => {
365 stack.last_mut().expect("frame").in_double_quote = true;
366 i += 1;
367 }
368 b'(' => {
369 stack.last_mut().expect("frame").paren_depth += 1;
370 i += 1;
371 }
372 b')' => {
373 let top = stack.last_mut().expect("frame");
374 if top.kind == FrameKind::DollarParen && top.paren_depth == 0 {
375 // Matching close of `$(` — back to the enclosing context,
376 // whose quoting resumes exactly where it left off.
377 stack.pop();
378 } else {
379 top.paren_depth = top.paren_depth.saturating_sub(1);
380 }
381 i += 1;
382 }
383 b'{' => {
384 stack.last_mut().expect("frame").brace_depth += 1;
385 i += 1;
386 }
387 b'}' => {
388 let top = stack.last_mut().expect("frame");
389 top.brace_depth = top.brace_depth.saturating_sub(1);
390 i += 1;
391 }
392 b'\n' | b'\r' | b';' if unshielded => {
393 segments.push((&command[start..i], Some(Separator::Sequence)));
394 i += 1;
395 start = i;
396 }
397 b'&' if unshielded => {
398 if i + 1 < len && bytes[i + 1] == b'&' {
399 // &&
400 segments.push((&command[start..i], Some(Separator::And)));
401 i += 2;
402 start = i;
403 } else if (i > 0 && bytes[i - 1] == b'>') || (i + 1 < len && bytes[i + 1] == b'>') {
404 // Redirect operator, NOT a separator: `2>&1`, `1>&2`, `>&file` (prev is '>')
405 // or `&>file`, `&>>file` (next is '>'). The '&' belongs to the current
406 // command — splitting here would mistake the fd/target (e.g. `1`) for a
407 // standalone command and falsely block it (#334).
408 i += 1;
409 } else {
410 // single & (background operator) — still a command separator
411 segments.push((&command[start..i], Some(Separator::Background)));
412 i += 1;
413 start = i;
414 }
415 }
416 b'|' if unshielded => {
417 if i + 1 < len && bytes[i + 1] == b'|' {
418 // ||
419 segments.push((&command[start..i], Some(Separator::Or)));
420 i += 2;
421 start = i;
422 } else if i > 0 && bytes[i - 1] == b'>' {
423 // `>|` (noclobber redirect), NOT a pipe: the '|' belongs to
424 // the redirect operator and the following token is a file
425 // path, not a command. Splitting here treated the target
426 // (e.g. `out` in `date >| out`) as a command and falsely
427 // blocked it against the allowlist (#387).
428 i += 1;
429 } else {
430 // pipe
431 segments.push((&command[start..i], Some(Separator::Pipe)));
432 i += 1;
433 start = i;
434 }
435 }
436 _ => {
437 i += 1;
438 }
439 }
440 }
441
442 if start < len {
443 segments.push((&command[start..], None));
444 }
445
446 segments
447}
448
449/// Extract the base command name from a single segment (no operators).
450pub(super) fn extract_base_from_segment(segment: &str) -> String {
451 let trimmed = segment.trim();
452 if trimmed.is_empty() {
453 return String::new();
454 }
455
456 let cmd_part = skip_powershell_assignment(skip_env_assignments(trimmed));
457 if cmd_part.is_empty() {
458 return String::new();
459 }
460 if is_powershell_value_expression(cmd_part) {
461 return String::new();
462 }
463
464 let tokens = shell_tokenize(cmd_part);
465 // #939: a leading `{` brace-group token (e.g. from
466 // `agent_wrapper::rebuild`'s `{ <real command>\n} && pwd ...` wrapping)
467 // is not itself a command — skip it so the base extracted is the real
468 // command inside the group, not the brace.
469 let mut token_iter = tokens.iter();
470 let first_token = match token_iter.next().map(String::as_str) {
471 Some("{") => token_iter.next().map_or("", String::as_str),
472 other => other.unwrap_or(""),
473 };
474
475 first_token
476 .rsplit('/')
477 .next()
478 .unwrap_or(first_token)
479 .to_string()
480}
481
482/// Skip a local PowerShell assignment (`$result = Get-Content …`) so the
483/// wrapped cmdlet is validated. Environment/scoped variables contain `:` and
484/// intentionally remain unrecognized, preventing `$env:PATH = …` bypasses.
485pub(super) fn skip_powershell_assignment(segment: &str) -> &str {
486 let trimmed = segment.trim_start();
487 let Some(variable_end) = powershell_local_variable_end(trimmed) else {
488 return trimmed;
489 };
490 let after_variable = trimmed[variable_end..].trim_start();
491 let Some(after_equals) = after_variable.strip_prefix('=') else {
492 return trimmed;
493 };
494 after_equals.trim_start()
495}
496
497fn powershell_local_variable_end(segment: &str) -> Option<usize> {
498 let bytes = segment.as_bytes();
499 if bytes.first() != Some(&b'$') {
500 return None;
501 }
502 let mut end = 1;
503 let first = *bytes.get(end)?;
504 if !(first.is_ascii_alphabetic() || first == b'_') {
505 return None;
506 }
507 end += 1;
508 while bytes
509 .get(end)
510 .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')
511 {
512 end += 1;
513 }
514 (bytes.get(end) != Some(&b':')).then_some(end)
515}
516
517/// A bare local variable or simple index lookup is pipeline data, not a command.
518/// Method calls and scoped variables deliberately fall through to deny-by-default.
519fn is_powershell_value_expression(segment: &str) -> bool {
520 let trimmed = segment.trim();
521 let Some(variable_end) = powershell_local_variable_end(trimmed) else {
522 return false;
523 };
524 let suffix = trimmed[variable_end..].trim();
525 suffix.is_empty()
526 || (suffix.starts_with('[')
527 && suffix.ends_with(']')
528 && !suffix.contains(['(', ')', ';', '|', '&', '=']))
529}
530
531/// #1488: detect whether a segment is a shell function definition.
532/// Pattern: `NAME() {` or `function NAME {` or `function NAME() {`.
533/// Returns the function name if it is a definition, `None` otherwise.
534pub(super) fn detect_function_def(segment: &str) -> Option<String> {
535 let cmd_part = skip_env_assignments(segment.trim());
536 if cmd_part.is_empty() {
537 return None;
538 }
539 let tokens = shell_tokenize(cmd_part);
540 if tokens.len() < 2 {
541 return None;
542 }
543
544 // Form 1: NAME() { ... }
545 if tokens[0].ends_with("()") && tokens.get(1).map(String::as_str) == Some("{") {
546 let name = tokens[0].trim_end_matches("()");
547 if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
548 return Some(name.to_string());
549 }
550 }
551
552 // Form 2: function NAME { ... } or function NAME() { ... }
553 if tokens[0] == "function" && tokens.len() >= 3 {
554 let name_tok = &tokens[1];
555 let name = name_tok.trim_end_matches("()");
556 if tokens.get(2).map(String::as_str) == Some("{")
557 && !name.is_empty()
558 && name.chars().all(|c| c.is_alphanumeric() || c == '_')
559 {
560 return Some(name.to_string());
561 }
562 }
563
564 None
565}
566
567/// #1488: extract the body commands from a function definition segment.
568/// Given `greet() { echo hi; echo bye; }`, returns `["echo hi", "echo bye"]`.
569pub(super) fn extract_function_body_commands(segment: &str) -> Vec<String> {
570 let trimmed = segment.trim();
571 // Find the opening `{` and closing `}`
572 let Some(open) = trimmed.find('{') else {
573 return vec![];
574 };
575 let Some(close) = trimmed.rfind('}').filter(|&i| i > open) else {
576 return vec![];
577 };
578 let body = &trimmed[open + 1..close];
579 // Split the body on `;` (simple split — nested braces are rare in
580 // single-line function defs, and the allowlist already handles segments).
581 body.split(';')
582 .map(|s| s.trim().to_string())
583 .filter(|s| !s.is_empty())
584 .collect()
585}
586
587/// Shell builtins that legitimately export or mutate environment variables.
588/// A segment beginning with one of these (`export PATH=…`, `readonly FOO=bar`)
589/// is not a bare inline `PATH=… cmd` hijack — skip the builtin and any
590/// following `VAR=value` tokens so export-only segments contribute no leaf
591/// command and `export PATH=… ; python3 …` resolves to `python3`.
592const ENV_SETTING_BUILTINS: &[&str] =
593 &["export", "unset", "readonly", "local", "declare", "typeset"];
594
595/// Skip leading KEY=VALUE environment variable assignments.
596/// Uses quote-aware scanning so `FOO="bar baz" git status` correctly
597/// skips the entire `FOO="bar baz"` token.
598pub(super) fn skip_env_assignments(segment: &str) -> &str {
599 let mut rest = segment;
600 loop {
601 let rest_trimmed = rest.trim_start();
602 if rest_trimmed.is_empty() {
603 return rest_trimmed;
604 }
605 let end = quote_aware_token_end(rest_trimmed);
606 if end == 0 {
607 return rest_trimmed;
608 }
609 let raw_token = &rest_trimmed[..end];
610 let unquoted: String = raw_token
611 .chars()
612 .filter(|c| *c != '"' && *c != '\'')
613 .collect();
614 let base_token = unquoted.rsplit('/').next().unwrap_or(unquoted.as_str());
615 if ENV_SETTING_BUILTINS.contains(&base_token) {
616 rest = &rest_trimmed[end..];
617 continue;
618 }
619 let is_posix_assignment = unquoted.split_once('=').is_some_and(|(name, _)| {
620 let mut bytes = name.bytes();
621 bytes
622 .next()
623 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
624 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
625 });
626 if is_posix_assignment {
627 rest = &rest_trimmed[end..];
628 } else {
629 return rest_trimmed;
630 }
631 }
632}
633/// Public accessor for extracting all command segments.
634pub fn extract_all_commands_pub(command: &str) -> Vec<String> {
635 extract_all_commands(command)
636}
637// Legacy compat: single-segment extraction (used by other callers)
638pub fn extract_base_command(command: &str) -> String {
639 let first_seg = split_on_operators(command)
640 .into_iter()
641 .next()
642 .unwrap_or(command);
643 extract_base_from_segment(first_seg)
644}