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 normalized command tokens from a single segment (no operators):
450/// skip env assignments, skip a PowerShell assignment, return empty for a
451/// PowerShell value expression, skip a leading `{` brace-group token (#939 —
452/// lean-ctx's own agent wrapper emits this form), and take the basename of
453/// the first token. Shared by `extract_base_from_segment` (which returns just
454/// the first token) and the subcommand-scoped allowlist matcher (which needs
455/// the rest of the tokens too), so the two normalizations cannot drift
456/// (GH #1419 follow-up).
457pub(super) fn extract_command_tokens_from_segment(segment: &str) -> Vec<String> {
458 let trimmed = segment.trim();
459 if trimmed.is_empty() {
460 return Vec::new();
461 }
462
463 let cmd_part = skip_powershell_assignment(skip_env_assignments(trimmed));
464 if cmd_part.is_empty() {
465 return Vec::new();
466 }
467 if is_powershell_value_expression(cmd_part) {
468 return Vec::new();
469 }
470
471 let tokens = shell_tokenize(cmd_part);
472 // #939: a leading `{` brace-group token (e.g. from
473 // `agent_wrapper::rebuild`'s `{ <real command>\n} && pwd ...` wrapping)
474 // is not itself a command — skip it so the base extracted is the real
475 // command inside the group, not the brace.
476 let mut token_iter = tokens.into_iter();
477 let first_token = match token_iter.next() {
478 Some(t) if t == "{" => token_iter.next(),
479 other => other,
480 };
481 let Some(first_token) = first_token else {
482 return Vec::new();
483 };
484 let basename = first_token
485 .rsplit('/')
486 .next()
487 .unwrap_or(&first_token)
488 .to_string();
489
490 std::iter::once(basename).chain(token_iter).collect()
491}
492
493/// Extract the base command name from a single segment (no operators).
494pub(super) fn extract_base_from_segment(segment: &str) -> String {
495 extract_command_tokens_from_segment(segment)
496 .into_iter()
497 .next()
498 .unwrap_or_default()
499}
500
501/// Skip a local PowerShell assignment (`$result = Get-Content …`) so the
502/// wrapped cmdlet is validated. Environment/scoped variables contain `:` and
503/// intentionally remain unrecognized, preventing `$env:PATH = …` bypasses.
504pub(super) fn skip_powershell_assignment(segment: &str) -> &str {
505 let trimmed = segment.trim_start();
506 let Some(variable_end) = powershell_local_variable_end(trimmed) else {
507 return trimmed;
508 };
509 let after_variable = trimmed[variable_end..].trim_start();
510 let Some(after_equals) = after_variable.strip_prefix('=') else {
511 return trimmed;
512 };
513 after_equals.trim_start()
514}
515
516fn powershell_local_variable_end(segment: &str) -> Option<usize> {
517 let bytes = segment.as_bytes();
518 if bytes.first() != Some(&b'$') {
519 return None;
520 }
521 let mut end = 1;
522 let first = *bytes.get(end)?;
523 if !(first.is_ascii_alphabetic() || first == b'_') {
524 return None;
525 }
526 end += 1;
527 while bytes
528 .get(end)
529 .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')
530 {
531 end += 1;
532 }
533 (bytes.get(end) != Some(&b':')).then_some(end)
534}
535
536/// A bare local variable or simple index lookup is pipeline data, not a command.
537/// Method calls and scoped variables deliberately fall through to deny-by-default.
538fn is_powershell_value_expression(segment: &str) -> bool {
539 let trimmed = segment.trim();
540 let Some(variable_end) = powershell_local_variable_end(trimmed) else {
541 return false;
542 };
543 let suffix = trimmed[variable_end..].trim();
544 suffix.is_empty()
545 || (suffix.starts_with('[')
546 && suffix.ends_with(']')
547 && !suffix.contains(['(', ')', ';', '|', '&', '=']))
548}
549
550/// #1488: detect whether a segment is a shell function definition.
551/// Pattern: `NAME() {` or `function NAME {` or `function NAME() {`.
552/// Returns the function name if it is a definition, `None` otherwise.
553pub(super) fn detect_function_def(segment: &str) -> Option<String> {
554 let cmd_part = skip_env_assignments(segment.trim());
555 if cmd_part.is_empty() {
556 return None;
557 }
558 let tokens = shell_tokenize(cmd_part);
559 if tokens.len() < 2 {
560 return None;
561 }
562
563 // Form 1: NAME() { ... }
564 if tokens[0].ends_with("()") && tokens.get(1).map(String::as_str) == Some("{") {
565 let name = tokens[0].trim_end_matches("()");
566 if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
567 return Some(name.to_string());
568 }
569 }
570
571 // Form 2: function NAME { ... } or function NAME() { ... }
572 if tokens[0] == "function" && tokens.len() >= 3 {
573 let name_tok = &tokens[1];
574 let name = name_tok.trim_end_matches("()");
575 if tokens.get(2).map(String::as_str) == Some("{")
576 && !name.is_empty()
577 && name.chars().all(|c| c.is_alphanumeric() || c == '_')
578 {
579 return Some(name.to_string());
580 }
581 }
582
583 None
584}
585
586/// #1488: the text between the outer `{` and `}` of a function definition
587/// segment — `greet() { echo hi; echo bye; }` gives ` echo hi; echo bye; `.
588/// The allowlist expands it like a top-level command line, so control flow in
589/// a body (`for … do … done`, `if … then … fi`) is not mistaken for commands
590/// (GH #2002).
591pub(super) fn function_body(segment: &str) -> Option<&str> {
592 let trimmed = segment.trim();
593 let open = trimmed.find('{')?;
594 let close = trimmed.rfind('}').filter(|&i| i > open)?;
595 Some(&trimmed[open + 1..close])
596}
597
598/// Shell builtins that legitimately export or mutate environment variables.
599/// A segment beginning with one of these (`export PATH=…`, `readonly FOO=bar`)
600/// is not a bare inline `PATH=… cmd` hijack — skip the builtin and any
601/// following `VAR=value` tokens so export-only segments contribute no leaf
602/// command and `export PATH=… ; python3 …` resolves to `python3`.
603const ENV_SETTING_BUILTINS: &[&str] =
604 &["export", "unset", "readonly", "local", "declare", "typeset"];
605
606/// Skip leading KEY=VALUE environment variable assignments.
607/// Uses quote-aware scanning so `FOO="bar baz" git status` correctly
608/// skips the entire `FOO="bar baz"` token.
609pub(super) fn skip_env_assignments(segment: &str) -> &str {
610 let mut rest = segment;
611 loop {
612 let rest_trimmed = rest.trim_start();
613 if rest_trimmed.is_empty() {
614 return rest_trimmed;
615 }
616 let end = quote_aware_token_end(rest_trimmed);
617 if end == 0 {
618 return rest_trimmed;
619 }
620 let raw_token = &rest_trimmed[..end];
621 let unquoted: String = raw_token
622 .chars()
623 .filter(|c| *c != '"' && *c != '\'')
624 .collect();
625 let base_token = unquoted.rsplit('/').next().unwrap_or(unquoted.as_str());
626 if ENV_SETTING_BUILTINS.contains(&base_token) {
627 rest = &rest_trimmed[end..];
628 continue;
629 }
630 let is_posix_assignment = unquoted.split_once('=').is_some_and(|(name, _)| {
631 let mut bytes = name.bytes();
632 bytes
633 .next()
634 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
635 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
636 });
637 if is_posix_assignment {
638 rest = &rest_trimmed[end..];
639 } else {
640 return rest_trimmed;
641 }
642 }
643}
644/// Public accessor for extracting all command segments.
645pub fn extract_all_commands_pub(command: &str) -> Vec<String> {
646 extract_all_commands(command)
647}
648// Legacy compat: single-segment extraction (used by other callers)
649pub fn extract_base_command(command: &str) -> String {
650 let first_seg = split_on_operators(command)
651 .into_iter()
652 .next()
653 .unwrap_or(command);
654 extract_base_from_segment(first_seg)
655}