Skip to main content

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