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                // #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    kind: FrameKind,
152}
153
154#[derive(Clone, Copy, PartialEq, Eq)]
155enum FrameKind {
156    /// The command line itself. Separators split only at this level.
157    Base,
158    /// Opened by `$(`, closed by the matching `)`.
159    DollarParen,
160    /// Opened and closed by a backtick — the older substitution form, same
161    /// quoting-restart rule.
162    Backtick,
163}
164
165impl Frame {
166    const fn new(kind: FrameKind) -> Self {
167        Self {
168            in_single_quote: false,
169            in_double_quote: false,
170            paren_depth: 0,
171            brace_depth: 0,
172            kind,
173        }
174    }
175
176    /// Inside quotes, or inside a group whose closing delimiter is still open.
177    const fn shields_operators(&self) -> bool {
178        self.in_single_quote || self.in_double_quote || self.paren_depth > 0 || self.brace_depth > 0
179    }
180}
181
182/// Split command string on shell operators: ;, &&, ||, |
183/// Respects single/double quotes, parentheses nesting, and backslash escapes
184/// outside single quotes (GL #1160): `rg split\.label\|quantityLabel` is ONE
185/// command — the escaped pipe is regex data, not an operator. The old scanner
186/// split there and blocked the pattern fragment as an unknown command; same
187/// for `find … -exec rm {} \;`.
188pub(super) fn split_on_operators(command: &str) -> Vec<&str> {
189    let mut segments = Vec::new();
190    let mut start = 0;
191    let bytes = command.as_bytes();
192    let len = bytes.len();
193    let mut i = 0;
194    // Stack, not booleans: see [`Frame`]. Index 0 is always the command line.
195    let mut stack: Vec<Frame> = vec![Frame::new(FrameKind::Base)];
196
197    while i < len {
198        let ch = bytes[i];
199        // `$(` and a backtick open a substitution wherever the shell would
200        // expand one: unquoted, or inside double quotes. Single quotes inhibit
201        // it entirely, which the single-quote arm below handles by consuming
202        // everything to the closing quote.
203        let opens_substitution = |i: usize| -> Option<(FrameKind, usize)> {
204            match bytes[i] {
205                b'$' if i + 1 < len && bytes[i + 1] == b'(' => Some((FrameKind::DollarParen, 2)),
206                b'`' => Some((FrameKind::Backtick, 1)),
207                _ => None,
208            }
209        };
210
211        let frame = *stack.last().expect("base frame is never popped");
212
213        if frame.in_single_quote {
214            if ch == b'\'' {
215                stack.last_mut().expect("frame").in_single_quote = false;
216            }
217            i += 1;
218            continue;
219        }
220
221        if frame.in_double_quote {
222            match ch {
223                // \" stays inside the string; \\ consumes both so `"x\\"` closes.
224                b'\\' => i = (i + 2).min(len),
225                b'"' => {
226                    stack.last_mut().expect("frame").in_double_quote = false;
227                    i += 1;
228                }
229                _ => {
230                    if let Some((kind, width)) = opens_substitution(i) {
231                        stack.push(Frame::new(kind));
232                        i += width;
233                    } else {
234                        i += 1;
235                    }
236                }
237            }
238            continue;
239        }
240
241        // Unquoted within the current frame.
242        if let Some((kind, width)) = opens_substitution(i) {
243            if kind == FrameKind::Backtick && frame.kind == FrameKind::Backtick {
244                // The same character closes a backtick substitution.
245                stack.pop();
246            } else {
247                stack.push(Frame::new(kind));
248            }
249            i += width;
250            continue;
251        }
252
253        let at_top = stack.len() == 1;
254        let unshielded = at_top && !frame.shields_operators();
255
256        match ch {
257            b'\\' => {
258                // Escaped char is data (bash semantics outside quotes) — never
259                // an operator or quote opener.
260                i = (i + 2).min(len);
261            }
262            b'\'' => {
263                stack.last_mut().expect("frame").in_single_quote = true;
264                i += 1;
265            }
266            b'"' => {
267                stack.last_mut().expect("frame").in_double_quote = true;
268                i += 1;
269            }
270            b'(' => {
271                stack.last_mut().expect("frame").paren_depth += 1;
272                i += 1;
273            }
274            b')' => {
275                let top = stack.last_mut().expect("frame");
276                if top.kind == FrameKind::DollarParen && top.paren_depth == 0 {
277                    // Matching close of `$(` — back to the enclosing context,
278                    // whose quoting resumes exactly where it left off.
279                    stack.pop();
280                } else {
281                    top.paren_depth = top.paren_depth.saturating_sub(1);
282                }
283                i += 1;
284            }
285            b'{' => {
286                stack.last_mut().expect("frame").brace_depth += 1;
287                i += 1;
288            }
289            b'}' => {
290                let top = stack.last_mut().expect("frame");
291                top.brace_depth = top.brace_depth.saturating_sub(1);
292                i += 1;
293            }
294            b'\n' | b'\r' | b';' if unshielded => {
295                segments.push(&command[start..i]);
296                i += 1;
297                start = i;
298            }
299            b'&' if unshielded => {
300                if i + 1 < len && bytes[i + 1] == b'&' {
301                    // &&
302                    segments.push(&command[start..i]);
303                    i += 2;
304                    start = i;
305                } else if (i > 0 && bytes[i - 1] == b'>') || (i + 1 < len && bytes[i + 1] == b'>') {
306                    // Redirect operator, NOT a separator: `2>&1`, `1>&2`, `>&file` (prev is '>')
307                    // or `&>file`, `&>>file` (next is '>'). The '&' belongs to the current
308                    // command — splitting here would mistake the fd/target (e.g. `1`) for a
309                    // standalone command and falsely block it (#334).
310                    i += 1;
311                } else {
312                    // single & (background operator) — still a command separator
313                    segments.push(&command[start..i]);
314                    i += 1;
315                    start = i;
316                }
317            }
318            b'|' if unshielded => {
319                if i + 1 < len && bytes[i + 1] == b'|' {
320                    // ||
321                    segments.push(&command[start..i]);
322                    i += 2;
323                    start = i;
324                } else if i > 0 && bytes[i - 1] == b'>' {
325                    // `>|` (noclobber redirect), NOT a pipe: the '|' belongs to
326                    // the redirect operator and the following token is a file
327                    // path, not a command. Splitting here treated the target
328                    // (e.g. `out` in `date >| out`) as a command and falsely
329                    // blocked it against the allowlist (#387).
330                    i += 1;
331                } else {
332                    // pipe
333                    segments.push(&command[start..i]);
334                    i += 1;
335                    start = i;
336                }
337            }
338            _ => {
339                i += 1;
340            }
341        }
342    }
343
344    if start < len {
345        segments.push(&command[start..]);
346    }
347
348    segments
349}
350
351/// Extract the base command name from a single segment (no operators).
352pub(super) fn extract_base_from_segment(segment: &str) -> String {
353    let trimmed = segment.trim();
354    if trimmed.is_empty() {
355        return String::new();
356    }
357
358    let cmd_part = skip_powershell_assignment(skip_env_assignments(trimmed));
359    if cmd_part.is_empty() {
360        return String::new();
361    }
362    if is_powershell_value_expression(cmd_part) {
363        return String::new();
364    }
365
366    let tokens = shell_tokenize(cmd_part);
367    // #939: a leading `{` brace-group token (e.g. from
368    // `agent_wrapper::rebuild`'s `{ <real command>\n} && pwd ...` wrapping)
369    // is not itself a command — skip it so the base extracted is the real
370    // command inside the group, not the brace.
371    let mut token_iter = tokens.iter();
372    let first_token = match token_iter.next().map(String::as_str) {
373        Some("{") => token_iter.next().map_or("", String::as_str),
374        other => other.unwrap_or(""),
375    };
376
377    first_token
378        .rsplit('/')
379        .next()
380        .unwrap_or(first_token)
381        .to_string()
382}
383
384/// Skip a local PowerShell assignment (`$result = Get-Content …`) so the
385/// wrapped cmdlet is validated. Environment/scoped variables contain `:` and
386/// intentionally remain unrecognized, preventing `$env:PATH = …` bypasses.
387pub(super) fn skip_powershell_assignment(segment: &str) -> &str {
388    let trimmed = segment.trim_start();
389    let Some(variable_end) = powershell_local_variable_end(trimmed) else {
390        return trimmed;
391    };
392    let after_variable = trimmed[variable_end..].trim_start();
393    let Some(after_equals) = after_variable.strip_prefix('=') else {
394        return trimmed;
395    };
396    after_equals.trim_start()
397}
398
399fn powershell_local_variable_end(segment: &str) -> Option<usize> {
400    let bytes = segment.as_bytes();
401    if bytes.first() != Some(&b'$') {
402        return None;
403    }
404    let mut end = 1;
405    let first = *bytes.get(end)?;
406    if !(first.is_ascii_alphabetic() || first == b'_') {
407        return None;
408    }
409    end += 1;
410    while bytes
411        .get(end)
412        .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')
413    {
414        end += 1;
415    }
416    (bytes.get(end) != Some(&b':')).then_some(end)
417}
418
419/// A bare local variable or simple index lookup is pipeline data, not a command.
420/// Method calls and scoped variables deliberately fall through to deny-by-default.
421fn is_powershell_value_expression(segment: &str) -> bool {
422    let trimmed = segment.trim();
423    let Some(variable_end) = powershell_local_variable_end(trimmed) else {
424        return false;
425    };
426    let suffix = trimmed[variable_end..].trim();
427    suffix.is_empty()
428        || (suffix.starts_with('[')
429            && suffix.ends_with(']')
430            && !suffix.contains(['(', ')', ';', '|', '&', '=']))
431}
432
433/// #1488: detect whether a segment is a shell function definition.
434/// Pattern: `NAME() {` or `function NAME {` or `function NAME() {`.
435/// Returns the function name if it is a definition, `None` otherwise.
436pub(super) fn detect_function_def(segment: &str) -> Option<String> {
437    let cmd_part = skip_env_assignments(segment.trim());
438    if cmd_part.is_empty() {
439        return None;
440    }
441    let tokens = shell_tokenize(cmd_part);
442    if tokens.len() < 2 {
443        return None;
444    }
445
446    // Form 1: NAME() { ... }
447    if tokens[0].ends_with("()") && tokens.get(1).map(String::as_str) == Some("{") {
448        let name = tokens[0].trim_end_matches("()");
449        if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
450            return Some(name.to_string());
451        }
452    }
453
454    // Form 2: function NAME { ... } or function NAME() { ... }
455    if tokens[0] == "function" && tokens.len() >= 3 {
456        let name_tok = &tokens[1];
457        let name = name_tok.trim_end_matches("()");
458        if tokens.get(2).map(String::as_str) == Some("{")
459            && !name.is_empty()
460            && name.chars().all(|c| c.is_alphanumeric() || c == '_')
461        {
462            return Some(name.to_string());
463        }
464    }
465
466    None
467}
468
469/// #1488: extract the body commands from a function definition segment.
470/// Given `greet() { echo hi; echo bye; }`, returns `["echo hi", "echo bye"]`.
471pub(super) fn extract_function_body_commands(segment: &str) -> Vec<String> {
472    let trimmed = segment.trim();
473    // Find the opening `{` and closing `}`
474    let Some(open) = trimmed.find('{') else {
475        return vec![];
476    };
477    let Some(close) = trimmed.rfind('}').filter(|&i| i > open) else {
478        return vec![];
479    };
480    let body = &trimmed[open + 1..close];
481    // Split the body on `;` (simple split — nested braces are rare in
482    // single-line function defs, and the allowlist already handles segments).
483    body.split(';')
484        .map(|s| s.trim().to_string())
485        .filter(|s| !s.is_empty())
486        .collect()
487}
488
489/// Shell builtins that legitimately export or mutate environment variables.
490/// A segment beginning with one of these (`export PATH=…`, `readonly FOO=bar`)
491/// is not a bare inline `PATH=… cmd` hijack — skip the builtin and any
492/// following `VAR=value` tokens so export-only segments contribute no leaf
493/// command and `export PATH=… ; python3 …` resolves to `python3`.
494const ENV_SETTING_BUILTINS: &[&str] =
495    &["export", "unset", "readonly", "local", "declare", "typeset"];
496
497/// Skip leading KEY=VALUE environment variable assignments.
498/// Uses quote-aware scanning so `FOO="bar baz" git status` correctly
499/// skips the entire `FOO="bar baz"` token.
500pub(super) fn skip_env_assignments(segment: &str) -> &str {
501    let mut rest = segment;
502    loop {
503        let rest_trimmed = rest.trim_start();
504        if rest_trimmed.is_empty() {
505            return rest_trimmed;
506        }
507        let end = quote_aware_token_end(rest_trimmed);
508        if end == 0 {
509            return rest_trimmed;
510        }
511        let raw_token = &rest_trimmed[..end];
512        let unquoted: String = raw_token
513            .chars()
514            .filter(|c| *c != '"' && *c != '\'')
515            .collect();
516        let base_token = unquoted.rsplit('/').next().unwrap_or(unquoted.as_str());
517        if ENV_SETTING_BUILTINS.contains(&base_token) {
518            rest = &rest_trimmed[end..];
519            continue;
520        }
521        let is_posix_assignment = unquoted.split_once('=').is_some_and(|(name, _)| {
522            let mut bytes = name.bytes();
523            bytes
524                .next()
525                .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
526                && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
527        });
528        if is_posix_assignment {
529            rest = &rest_trimmed[end..];
530        } else {
531            return rest_trimmed;
532        }
533    }
534}
535/// Public accessor for extracting all command segments.
536pub fn extract_all_commands_pub(command: &str) -> Vec<String> {
537    extract_all_commands(command)
538}
539// Legacy compat: single-segment extraction (used by other callers)
540pub fn extract_base_command(command: &str) -> String {
541    let first_seg = split_on_operators(command)
542        .into_iter()
543        .next()
544        .unwrap_or(command);
545    extract_base_from_segment(first_seg)
546}