Skip to main content

vtcode_safety/command_safety/shell_parser/
mod.rs

1#![expect(
2    clippy::indexing_slicing,
3    clippy::string_slice,
4    reason = "Shell parsing tracks byte offsets at character boundaries while validating operator pairs."
5)]
6
7//! Shell script parser for `bash -lc` and similar commands.
8//!
9//! This module parses shell commands like:
10//! ```sh
11//! bash -lc "git status && cargo check"
12//! ```
13//!
14//! Into individual command vectors for independent safety checking:
15//! ```text
16//! [["git", "status"], ["cargo", "check"]]
17//! ```
18//!
19//! **Phase 4 Implementation**: Uses tree-sitter for accurate bash AST parsing.
20//! Falls back to basic tokenization for minimal shell syntax.
21
22mod ast;
23
24use anyhow::Result;
25
26pub use ast::{BashNode, BashTree, prewarm_bash_parser};
27
28/// Parses a shell script into individual commands using tree-sitter bash grammar
29///
30/// # Example
31/// ```text
32/// Input:  "git status && cargo check"
33/// Output: Ok([["git", "status"], ["cargo", "check"]])
34/// ```
35///
36/// # Fallback
37/// Upstream tree-sitter-bash #337: the bash external scanner SIGSEGVs when a
38/// `{` is followed anywhere later in the input by a 4-byte UTF-8 lead byte
39/// (0xF0..=0xF7) — e.g. `{` + U+2FA8E — crashing the whole process instead of
40/// returning an error. The minimal reproducer is two characters. A safety
41/// classifier may never crash the agent that calls it, so inputs with that
42/// shape skip the scanner and parse with the basic tokenizer directly.
43fn scanner_crash_shape(script: &str) -> bool {
44    let mut saw_open_brace = false;
45    for byte in script.as_bytes() {
46        match byte {
47            b'{' => saw_open_brace = true,
48            0xF0..=0xF7 if saw_open_brace => return true,
49            _ => {}
50        }
51    }
52    false
53}
54
55/// Parse a shell script into command/argument lists.
56///
57/// If tree-sitter parsing fails, falls back to simple tokenization.
58pub fn parse_shell_commands(script: &str) -> Result<Vec<Vec<String>>, String> {
59    // Try tree-sitter parsing first; crash-shape input is rejected inside
60    // parse_with_tree_sitter and lands in the basic tokenizer via the Err arm.
61    match parse_with_tree_sitter(script, false) {
62        Ok(commands) if !commands.is_empty() => return Ok(commands),
63        Ok(_) => {} // Empty result, fall through to basic parsing
64        Err(e) => {
65            tracing::debug!("Tree-sitter bash parsing failed: {}, falling back to basic tokenization", e);
66        }
67    }
68
69    // Fallback to simple tokenization
70    parse_with_basic_tokenization(script)
71}
72
73/// Parses a shell script using tree-sitter bash grammar only (no fallback tokenization).
74///
75/// Use this when caller behavior must be strictly gated on bash grammar validity.
76pub fn parse_shell_commands_tree_sitter(script: &str) -> Result<Vec<Vec<String>>, String> {
77    parse_with_tree_sitter(script, true)
78}
79
80/// Returns whether a shell command contains syntax whose meaning depends on
81/// shell expansion rather than the literal argument text.
82///
83/// Safety-sensitive classification must only operate on static command
84/// shapes. Parameter expansion, command substitution, brace expansion,
85/// globbing, and unquoted backslash escapes can otherwise turn a
86/// harmless-looking token into a different executable argument at runtime.
87/// Backslash escapes inside double-quoted arguments are consumed as literal
88/// argument syntax so patterns such as `rg -n "\\[profile"` remain classifiable.
89pub fn contains_dynamic_shell_syntax(command: &str) -> bool {
90    enum ShellQuote {
91        Single,
92        Double,
93    }
94
95    let mut quote: Option<ShellQuote> = None;
96    let mut characters = command.chars();
97
98    while let Some(character) = characters.next() {
99        match quote {
100            Some(ShellQuote::Single) => {
101                if character == '\'' {
102                    quote = None;
103                }
104            }
105            Some(ShellQuote::Double) => match character {
106                '"' => quote = None,
107                '$' | '`' => return true,
108                '\\'
109                    // Backslash escapes inside double quotes are literal
110                    // argument syntax. Consume the escaped character so an
111                    // escaped quote cannot incorrectly end the quoted region;
112                    // unquoted escapes remain rejected below because they can
113                    // alter the command token or its shell structure.
114                    if characters.next().is_none() => {
115                        return true;
116                    }
117                _ => {}
118            },
119            None => match character {
120                '\'' => quote = Some(ShellQuote::Single),
121                '"' => quote = Some(ShellQuote::Double),
122                '\\' | '$' | '`' | '{' | '}' | '*' | '?' | '[' | ']' => return true,
123                _ => {}
124            },
125        }
126    }
127
128    quote.is_some()
129}
130
131/// Returns whether a `find` command contains shell syntax that can change the
132/// literal option tokens after approval-time tokenization.
133pub fn contains_dynamic_find_syntax(script: &str) -> bool {
134    if let Ok(commands) = parse_shell_commands_tree_sitter(script)
135        && commands.iter().any(|command| {
136            command
137                .first()
138                .map(|program| base_command_name(program) == "find")
139                .unwrap_or(false)
140                && command.iter().any(|word| contains_dynamic_shell_syntax(word))
141        })
142    {
143        return true;
144    }
145
146    // Be conservative when the grammar cannot identify the command shape: a
147    // raw script containing a find invocation and dynamic syntax must not pass
148    // preflight just because parsing was incomplete.
149    let has_find_word = script.split_whitespace().any(|word| {
150        let command = word.trim_matches(|character: char| !character.is_ascii_alphanumeric() && character != '/');
151        base_command_name(command) == "find"
152    });
153    has_find_word && contains_dynamic_shell_syntax(script)
154}
155
156/// Returns whether every redirection in a static shell script only routes
157/// command output. Input, heredoc, and descriptor-closing redirections remain
158/// unsupported so progress classification can fail closed.
159pub fn has_only_output_redirections(script: &str) -> bool {
160    if contains_dynamic_shell_syntax(script) {
161        return false;
162    }
163    if contains_background_operator(script) {
164        return false;
165    }
166
167    let Ok(tree) = BashTree::parse(script) else {
168        return false;
169    };
170    if tree.has_error() {
171        return false;
172    }
173
174    let mut saw_redirection = false;
175    if !collect_output_redirections(tree.root(), &mut saw_redirection) {
176        return false;
177    }
178    saw_redirection
179}
180
181/// Validate literal file-redirection targets before command classification drops them.
182/// Descriptor routing carries no path; unresolved shell expansion fails closed.
183pub(crate) fn validate_redirection_paths(script: &str) -> Result<()> {
184    use anyhow::{Context, anyhow, ensure};
185    if !script.contains(['<', '>']) {
186        return Ok(());
187    }
188    let tree = BashTree::parse(script).map_err(|error| anyhow!("failed to parse shell redirections: {error}"))?;
189    ensure!(!tree.has_error(), "cannot validate malformed shell redirections");
190    let mut pending = vec![tree.root()];
191    while let Some(node) = pending.pop() {
192        if node.kind() == "file_redirect" {
193            let text = node.text();
194            let operator = text.trim_start_matches(|character: char| character.is_ascii_digit());
195            let descriptor_route = operator.starts_with(">&") || operator.starts_with("<&");
196            for destination in node.field_children("destination") {
197                let raw = destination.text();
198                ensure!(!contains_dynamic_shell_syntax(raw), "dynamic redirection destination is not allowed");
199                let words = shell_words::split(raw).context("invalid quoted redirection destination")?;
200                ensure!(words.len() == 1, "redirection destination must be one literal path");
201                let path = words.first().context("missing redirection destination")?;
202                if descriptor_route && (path == "-" || path.chars().all(|character| character.is_ascii_digit())) {
203                    continue;
204                }
205                // `sh` expands a leading `~` after validation, so treating it
206                // as a relative literal would let a redirection escape the
207                // workspace (for example, `> ~/.config`). Require callers to
208                // provide an explicit, policy-checked destination instead.
209                ensure!(!path.starts_with('~'), "home-directory redirection destinations are not allowed");
210                // The null sink is the one intentional device path used by normal commands.
211                if path == "/dev/null" {
212                    continue;
213                }
214                vtcode_commons::paths::validate_path_safety(path)
215                    .with_context(|| format!("unsafe shell redirection destination: {path}"))?;
216            }
217        }
218        pending.extend(node.named_children());
219    }
220    Ok(())
221}
222
223fn contains_background_operator(script: &str) -> bool {
224    let chars = script.chars().collect::<Vec<_>>();
225    let mut index = 0;
226    let mut in_single_quote = false;
227    let mut in_double_quote = false;
228
229    while index < chars.len() {
230        let character = chars[index];
231        if character == '\'' && !in_double_quote {
232            in_single_quote.toggle();
233            index += 1;
234            continue;
235        }
236        if character == '"' && !in_single_quote {
237            in_double_quote.toggle();
238            index += 1;
239            continue;
240        }
241        if in_single_quote || in_double_quote {
242            index += 1;
243            continue;
244        }
245
246        if character == '&' {
247            let previous = index.checked_sub(1).and_then(|position| chars.get(position));
248            let next = chars.get(index + 1);
249            if next == Some(&'&') {
250                index += 2;
251                continue;
252            }
253            let part_of_allowed_operator = next == Some(&'&')
254                || next == Some(&'>')
255                || previous == Some(&'>')
256                || previous == Some(&'|')
257                || previous == Some(&'<');
258            if !part_of_allowed_operator {
259                return true;
260            }
261        }
262        index += 1;
263    }
264
265    false
266}
267
268fn collect_output_redirections(node: BashNode<'_>, saw_redirection: &mut bool) -> bool {
269    match node.kind() {
270        "file_redirect" => {
271            *saw_redirection = true;
272            if !is_output_redirection(node.text()) {
273                return false;
274            }
275        }
276        "heredoc_redirect" | "herestring_redirect" => return false,
277        _ => {}
278    }
279
280    node.children()
281        .iter()
282        .all(|child| collect_output_redirections(*child, saw_redirection))
283}
284
285fn is_output_redirection(text: &str) -> bool {
286    let redirect = text.trim_start_matches(|character: char| character.is_ascii_digit());
287    if redirect.starts_with("&>") {
288        return !redirect.starts_with("&>-");
289    }
290    if let Some(destination) = redirect.strip_prefix(">&") {
291        return destination.trim().chars().all(|character| character.is_ascii_digit());
292    }
293
294    redirect.starts_with('>') && !redirect.starts_with(">&-")
295}
296
297/// Literal file paths that a static shell script opens for writing.
298///
299/// Command classification cannot see redirections (`cat > .git/config` looks
300/// like a read), so the sandbox preflight uses these destinations to check
301/// writes against the active policy. Descriptor routing (`2>&1`), input and
302/// heredoc redirections carry no file target and are ignored. Dynamic
303/// destinations are skipped because [`validate_redirection_paths`] rejects
304/// them before execution — never guess a path from an unresolved expansion.
305/// Malformed scripts yield no destinations; the strict validators fail closed
306/// on them before this function is reached.
307pub fn output_redirection_destinations(script: &str) -> Vec<String> {
308    let mut destinations = Vec::new();
309    collect_output_destinations(script, &mut destinations, 0);
310    destinations
311}
312
313/// Bound the recursion for nested `sh -c` scripts: a script that generates
314/// another shell script with an ever-growing payload must not hang preflight.
315const MAX_NESTED_SHELL_DEPTH: u8 = 2;
316
317fn collect_output_destinations(script: &str, destinations: &mut Vec<String>, depth: u8) {
318    if !script.contains('>') {
319        return;
320    }
321    let Ok(tree) = BashTree::parse(script) else {
322        return;
323    };
324    if tree.has_error() {
325        return;
326    }
327
328    // Depth-first pre-order: named children are in source order and the stack
329    // is pushed in reverse, so the caller reports blocked targets stably.
330    let mut pending = vec![tree.root()];
331    while let Some(node) = pending.pop() {
332        if node.kind() == "file_redirect" && is_output_redirection(node.text()) {
333            for destination in node.field_children("destination") {
334                let raw = destination.text();
335                if contains_dynamic_shell_syntax(raw) {
336                    continue;
337                }
338                let Ok(words) = shell_words::split(raw) else {
339                    continue;
340                };
341                if let [path] = words.as_slice()
342                    && !path.is_empty()
343                    && !path.bytes().all(|byte| byte.is_ascii_digit())
344                    && path != "-"
345                    // Process substitution (`>(cmd)`) and globbing are not
346                    // literal file paths. Never guess where they write.
347                    && !path.contains(['$', '`', '(', ')', '<', '>', '|', ';', '&', '*', '?', '['])
348                {
349                    destinations.push(path.clone());
350                }
351            }
352        }
353        for child in node.named_children().into_iter().rev() {
354            pending.push(child);
355        }
356    }
357
358    // A nested interpreter keeps its redirections inside a quoted argument, so
359    // the AST walk above cannot see them. Use the canonical command extractor
360    // (which already unwraps loops/conditionals) and descend into literal shell
361    // invocations, sharing prefix unwrapping with command-safety classification.
362    if depth >= MAX_NESTED_SHELL_DEPTH {
363        return;
364    }
365    for command in parse_shell_commands(script).unwrap_or_default() {
366        let Some(script) = shell_inline_script(&command) else {
367            continue;
368        };
369        if contains_dynamic_shell_syntax(script) {
370            continue;
371        }
372        let inner = super::dangerous_commands::strip_nested_script_quotes(script);
373        collect_output_destinations(inner, destinations, depth + 1);
374    }
375}
376
377/// Return the inline script of a literal `sh`/`bash`/`zsh` invocation.
378///
379/// Shell short options cluster freely (`-c`, `-lc`, `-ilc`, `-lic`, `-icl`,
380/// `-x -c`), so matching a fixed list misses valid forms. In every cluster the
381/// `c` option takes the *next* argument as the script, regardless of the other
382/// letters around it. Program runner prefixes are unwrapped with the shared
383/// helper so a wrapped interpreter (`env bash -c '…'`) is not skipped either.
384pub(crate) fn shell_inline_script(command: &[String]) -> Option<&str> {
385    let command = super::dangerous_commands::unwrap_command_prefix(command)?;
386    let executable = command.first()?;
387    let name = std::path::Path::new(executable)
388        .file_name()
389        .and_then(|name| name.to_str())
390        .unwrap_or_default();
391    if !matches!(name, "sh" | "bash" | "zsh") {
392        return None;
393    }
394    for (index, argument) in command.iter().enumerate().skip(1) {
395        let Some(flags) = argument.strip_prefix('-') else {
396            continue;
397        };
398        // Long options never bundle `c`; only short-option clusters do.
399        if flags.starts_with('-') {
400            continue;
401        }
402        if flags.contains('c') {
403            return command.get(index + 1).map(String::as_str);
404        }
405    }
406    None
407}
408
409/// Parses shell script using tree-sitter bash grammar.
410fn parse_with_tree_sitter(script: &str, reject_syntax_errors: bool) -> Result<Vec<Vec<String>>, String> {
411    // Never hand the scanner an input upstream tree-sitter-bash #337 crashes
412    // on: the guard covers both the lenient route (parse_shell_commands falls
413    // back to basic tokenization on Err) and every strict caller, which
414    // already handle Err fail-closed.
415    if scanner_crash_shape(script) {
416        return Err("shell script matches the tree-sitter-bash #337 scanner crash shape".to_string());
417    }
418    let tree = BashTree::parse(script)?;
419
420    let mut commands = Vec::new();
421    if reject_syntax_errors && tree.has_error() {
422        return Err("Shell script contains syntax errors".to_string());
423    }
424
425    // Walk the full tree so commands inside loops/conditionals are remembered
426    // for approval and checked for safety.  Top-level-only extraction misses
427    // common read loops such as `for f in ...; do grep ...; done`.
428    collect_commands_from_node(tree.root(), &mut commands);
429
430    Ok(commands)
431}
432
433fn collect_commands_from_node(node: BashNode<'_>, commands: &mut Vec<Vec<String>>) {
434    match node.kind() {
435        "command" | "simple_command" => {
436            if let Some(cmd) = extract_command_from_node(node)
437                && !cmd.is_empty()
438            {
439                commands.push(cmd);
440            }
441        }
442        _ => {
443            for child in node.children() {
444                collect_commands_from_node(child, commands);
445            }
446        }
447    }
448}
449
450/// Extracts a command vector from a bash AST node
451fn extract_command_from_node(node: BashNode<'_>) -> Option<Vec<String>> {
452    let mut command = Vec::new();
453
454    // For pipeline nodes, extract the first command in the pipeline
455    if node.kind() == "pipeline" {
456        for child in node.children() {
457            if child.kind() == "command" || child.kind() == "simple_command" {
458                return extract_command_from_node(child);
459            }
460        }
461    }
462
463    // Extract arguments from command node
464    for child in node.children() {
465        if child.kind() == "command_name" {
466            let trimmed = child.text().trim();
467            if !trimmed.is_empty() {
468                command.push(trimmed.to_string());
469            }
470            continue;
471        }
472
473        // Leading `KEY=value` prefixes and concatenated assignment values
474        // (`NODE_OPTIONS='--require ./x'`) are part of the command's
475        // environment contract. Keep them as one word so intent/activity
476        // classification can inspect injection keys;
477        // `command_words_after_environment_prefix` still strips them before
478        // locating the executable. `concatenation` must use the full span
479        // text — its children are only the `NAME=` and quoted value pieces.
480        if matches!(child.kind(), "variable_assignment" | "concatenation") {
481            let trimmed = child.text().trim();
482            if !trimmed.is_empty() {
483                command.push(trimmed.to_string());
484            }
485            continue;
486        }
487
488        if matches!(
489            child.kind(),
490            "word" | "string" | "raw_string" | "ansi_c_string" | "simple_expansion" | "variable_expansion"
491        ) {
492            let trimmed = child.text().trim();
493            if !trimmed.is_empty() {
494                command.push(trimmed.to_string());
495            }
496        }
497    }
498
499    if command.is_empty() { None } else { Some(command) }
500}
501
502/// Fallback: Parses shell script with simple tokenization
503fn parse_with_basic_tokenization(script: &str) -> Result<Vec<Vec<String>>, String> {
504    let mut commands = Vec::new();
505    let mut current_command = String::new();
506    let mut in_quotes = false;
507    let mut quote_char = ' ';
508    let mut escaped = false;
509
510    for ch in script.chars() {
511        if escaped {
512            current_command.push(ch);
513            escaped = false;
514            continue;
515        }
516
517        match ch {
518            '\\' => {
519                escaped = true;
520            }
521            '\'' | '"' if !in_quotes => {
522                in_quotes = true;
523                quote_char = ch;
524            }
525            c if c == quote_char && in_quotes => {
526                in_quotes = false;
527            }
528            '&' | '|' | ';' if !in_quotes => {
529                if !current_command.trim().is_empty()
530                    && let Ok(cmd) = tokenize_command(&current_command)
531                {
532                    commands.push(cmd);
533                }
534                current_command.clear();
535            }
536            _ => current_command.push(ch),
537        }
538    }
539
540    if !current_command.trim().is_empty()
541        && let Ok(cmd) = tokenize_command(&current_command)
542    {
543        commands.push(cmd);
544    }
545
546    Ok(commands)
547}
548
549/// Splits a command string into arguments
550/// Respects quoted strings and escapes
551fn tokenize_command(cmd: &str) -> Result<Vec<String>, String> {
552    shell_words::split(cmd).map_err(|err| format!("failed to tokenize command: {err}"))
553}
554
555/// Parses `bash -lc "script"` style invocations
556///
557/// # Example
558/// ```text
559/// Input:  vec!["bash", "-lc", "git status && rm /"]
560/// Output: Some([["git", "status"], ["rm", "/"]])
561/// ```
562pub fn parse_bash_lc_commands(command: &[String]) -> Option<Vec<Vec<String>>> {
563    if command.is_empty() {
564        return None;
565    }
566
567    let cmd_name = command[0].as_str();
568    let base_cmd = std::path::Path::new(cmd_name)
569        .file_name()
570        .and_then(|osstr| osstr.to_str())
571        .unwrap_or("");
572
573    if base_cmd != "bash" && base_cmd != "zsh" && base_cmd != "sh" {
574        return None;
575    }
576
577    // Look for -lc or -c pattern
578    for window in command.windows(2) {
579        if matches!(window[0].as_str(), "-lc" | "-c" | "-il" | "-ic") {
580            let script = &window[1];
581            return parse_shell_commands(script).ok();
582        }
583    }
584
585    None
586}
587
588// === Injection detection (moved from tools::validation::commands) ===
589
590use anyhow::{anyhow, bail};
591
592/// Delimiter token of a quoted heredoc starting just after `<<` / `<<-`.
593///
594/// Returns `(delimiter, token_byte_len)` where the token covers the optional
595/// `-`, surrounding whitespace, and the quoted delimiter word. Bare
596/// (unquoted) delimiters return `None`: those bodies still allow substitution.
597pub(crate) fn quoted_heredoc_delim(rest: &str) -> Option<(String, usize)> {
598    let mut idx = 0usize;
599    let bytes = rest.as_bytes();
600    if bytes.first() == Some(&b'-') {
601        idx += 1;
602    }
603    while idx < bytes.len() && (bytes[idx] == b' ' || bytes[idx] == b'\t') {
604        idx += 1;
605    }
606    let quote = match bytes.get(idx) {
607        Some(b'\'') | Some(b'"') => bytes[idx],
608        _ => return None,
609    };
610    idx += 1;
611    let delim_start = idx;
612    while idx < bytes.len() && bytes[idx] != quote {
613        idx += 1;
614    }
615    if idx >= bytes.len() || idx == delim_start {
616        return None;
617    }
618    let delim = rest[delim_start..idx].to_string();
619    idx += 1; // closing quote
620    Some((delim, idx))
621}
622
623/// Byte length of a quoted heredoc body starting just after the opener line's
624/// newline, through the closing delimiter line (inclusive). Returns `None`
625/// when the closing delimiter never appears so callers keep scanning the
626/// unterminated body and fail closed on anything executable inside it.
627pub(crate) fn heredoc_body_skip_len(rest: &str, delim: &str) -> Option<usize> {
628    let bytes = rest.as_bytes();
629    let mut idx = 0usize;
630    while idx <= bytes.len() {
631        let line_end = rest[idx..].find('\n').map(|offset| idx + offset).unwrap_or(bytes.len());
632        let line = rest[idx..line_end].trim_end_matches('\r');
633        let next = if line_end < bytes.len() {
634            line_end + 1
635        } else {
636            bytes.len()
637        };
638        if line == delim {
639            return Some(next);
640        }
641        if line_end >= bytes.len() {
642            return None;
643        }
644        idx = next;
645    }
646    None
647}
648
649/// Advance a `CharIndices` iterator by at most `max_bytes`, returning the byte
650/// index just past the last consumed char (or `fallback` when nothing remains).
651fn consume_bytes(
652    chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>,
653    max_bytes: usize,
654    fallback: usize,
655) -> usize {
656    let mut consumed = 0usize;
657    let mut end = fallback;
658    while consumed < max_bytes
659        && let Some((idx, ch)) = chars.next()
660    {
661        consumed += ch.len_utf8();
662        end = idx + ch.len_utf8();
663    }
664    end
665}
666
667/// Quote state for shell segment splitting.
668#[derive(Clone, Copy, Eq, PartialEq)]
669enum QuoteState {
670    None,
671    Single,
672    Double,
673}
674
675/// Command substitution construct that tripped an injection scan.
676#[derive(Clone, Copy, Debug, PartialEq, Eq)]
677pub(crate) enum SubstitutionKind {
678    Backtick,
679    DollarParen,
680}
681
682impl SubstitutionKind {
683    fn label(self) -> &'static str {
684        match self {
685            Self::Backtick => "backtick",
686            Self::DollarParen => "'$('",
687        }
688    }
689}
690
691/// Actionable injection error: names the construct and its byte offset so the
692/// caller can locate the rejected span in its own command. Keeps the legacy
693/// "Command injection pattern detected" prefix so downstream policy matchers
694/// (`preflight_policy_correction`) keep routing to the security-policy branch.
695pub(crate) fn substitution_error(kind: SubstitutionKind, byte_idx: usize) -> anyhow::Error {
696    anyhow!(
697        "Command injection pattern detected: {} command substitution at byte {byte_idx}; rewrite without dynamic expansion",
698        kind.label()
699    )
700}
701
702/// Split a shell command into segments on unquoted `|` and `&` boundaries,
703/// while detecting injection patterns (`;`, backticks, `$()`, newlines).
704pub(crate) fn split_shell_segments(command: &str) -> Result<Vec<String>> {
705    let mut segments = Vec::new();
706    let mut state = QuoteState::None;
707    let mut escaped = false;
708    let mut segment_start = 0usize;
709    // Delimiter of a `<<'EOF'`-shaped heredoc whose opener line has not ended
710    // yet. The opener line stays live shell; the body is skipped at the
711    // unquoted newline.
712    let mut pending_heredoc: Option<String> = None;
713    let mut chars = command.char_indices().peekable();
714
715    while let Some((idx, ch)) = chars.next() {
716        match state {
717            QuoteState::Single => {
718                if ch == '\'' {
719                    state = QuoteState::None;
720                }
721            }
722            QuoteState::Double => {
723                if escaped {
724                    escaped = false;
725                    continue;
726                }
727
728                match ch {
729                    '\\' => escaped = true,
730                    '"' => state = QuoteState::None,
731                    '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
732                    '$' if matches!(chars.peek(), Some((_, '('))) => {
733                        return Err(substitution_error(SubstitutionKind::DollarParen, idx));
734                    }
735                    _ => {}
736                }
737            }
738            QuoteState::None => {
739                if escaped {
740                    escaped = false;
741                    // A backslash-escaped semicolon is a literal in bash but a
742                    // statement separator in PowerShell (which escapes with
743                    // `^`, not `\`). Reject it here so this platform-agnostic
744                    // validator cannot be blinded to command chaining by `\;`.
745                    if ch == ';' {
746                        bail!("Escaped command chaining detected");
747                    }
748                    continue;
749                }
750
751                match ch {
752                    '\\' => escaped = true,
753                    '\'' => state = QuoteState::Single,
754                    '"' => state = QuoteState::Double,
755                    // Quoted heredoc bodies are literal data (newlines, backticks
756                    // included). Arm the skip here but keep scanning: everything
757                    // after the delimiter on the opener line is live shell, so
758                    // operators there must still split segments or bail. The
759                    // body is skipped at the unquoted opener newline below.
760                    '<' if matches!(chars.peek(), Some((_, '<'))) => {
761                        let _ = chars.next(); // second '<'
762                        let rest: String = chars.clone().map(|(_, c)| c).collect();
763                        if let Some((delim, token_len)) = quoted_heredoc_delim(&rest) {
764                            let _ = consume_bytes(&mut chars, token_len, idx + ch.len_utf8());
765                            pending_heredoc = Some(delim);
766                        }
767                    }
768                    '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
769                    '$' if matches!(chars.peek(), Some((_, '('))) => {
770                        return Err(substitution_error(SubstitutionKind::DollarParen, idx));
771                    }
772                    ';' => bail!("Unquoted command chaining detected"),
773                    '\n' => {
774                        // The opener line ended in unquoted context: the quoted
775                        // heredoc body starts here and is literal data. Without
776                        // a closing delimiter the body keeps being scanned, so
777                        // executable content in it still fails closed.
778                        if let Some(delim) = pending_heredoc.take() {
779                            let rest: String = chars.clone().map(|(_, c)| c).collect();
780                            if let Some(skip) = heredoc_body_skip_len(&rest, &delim) {
781                                // The opener line is a live command; the body
782                                // belongs to no segment.
783                                push_segment(command, segment_start, idx, &mut segments);
784                                segment_start = consume_bytes(&mut chars, skip, command.len());
785                                continue;
786                            }
787                        }
788                        bail!(
789                            "multi-line shell commands are not allowed; write the content with `apply_patch` instead of a heredoc"
790                        );
791                    }
792                    '|' | '&' => {
793                        push_segment(command, segment_start, idx, &mut segments);
794                        segment_start = idx + ch.len_utf8();
795                        if let Some((next_idx, next_ch)) = chars.peek().copied()
796                            && next_ch == ch
797                        {
798                            let _next = chars.next();
799                            segment_start = next_idx + next_ch.len_utf8();
800                        }
801                    }
802                    _ => {}
803                }
804            }
805        }
806    }
807
808    push_segment(command, segment_start, command.len(), &mut segments);
809    Ok(segments)
810}
811
812fn push_segment(command: &str, start: usize, end: usize, segments: &mut Vec<String>) {
813    let segment = command[start..end].trim();
814    if !segment.is_empty() {
815        segments.push(segment.to_string());
816    }
817}
818
819/// Check for additional dangerous patterns not covered by the central dangerous-command detector.
820pub(crate) fn additional_dangerous_pattern(segment: &str) -> Option<&'static str> {
821    let segment_lower = segment.to_ascii_lowercase();
822    if segment_lower.starts_with(":(){:|:&};:") {
823        return Some(":(){:|:&};:");
824    }
825
826    let tokens =
827        shell_words::split(segment).unwrap_or_else(|_| segment.split_whitespace().map(ToString::to_string).collect());
828    let first = tokens.first()?;
829    let command_name = base_command_name(strip_wrapping_quotes(first)).to_ascii_lowercase();
830
831    match command_name.as_str() {
832        "rmdir" => Some("rmdir"),
833        "wget" => Some("wget"),
834        "curl" => Some("curl"),
835        "chmod" if tokens.iter().skip(1).any(|arg| strip_wrapping_quotes(arg).starts_with("777")) => Some("chmod 777"),
836        "chown"
837            if tokens.iter().skip(1).any(|arg| {
838                let arg = strip_wrapping_quotes(arg).to_ascii_lowercase();
839                arg == "root" || arg.starts_with("root:")
840            }) =>
841        {
842            Some("chown root")
843        }
844        _ => None,
845    }
846}
847
848fn strip_wrapping_quotes(token: &str) -> &str {
849    token
850        .strip_prefix('\'')
851        .and_then(|token| token.strip_suffix('\''))
852        .or_else(|| token.strip_prefix('"').and_then(|token| token.strip_suffix('"')))
853        .unwrap_or(token)
854}
855
856fn base_command_name(command: &str) -> &str {
857    std::path::Path::new(command)
858        .file_name()
859        .and_then(|name| name.to_str())
860        .unwrap_or(command)
861}
862#[cfg(test)]
863mod crash_regression {
864    use super::*;
865
866    /// tree-sitter-bash #337: `{` + U+2FA8E (the delta-minimal reproducer,
867    /// found by fuzzing on linux) SIGSEGV'd the external scanner and killed
868    /// the process; the guard routes such input to the basic tokenizer.
869    #[test]
870    fn parse_survives_brace_plus_astral_input() {
871        let parsed = parse_shell_commands("{\u{2FA8E}");
872        assert!(parsed.is_ok(), "parse must not fail: {parsed:?}");
873
874        // A real command containing the crash shape keeps its tokens, and a
875        // following command survives too.
876        let parsed = parse_shell_commands("echo {\u{2FA8E}} && echo done").expect("two commands");
877        assert_eq!(parsed.len(), 2, "both commands must survive: {parsed:?}");
878        assert!(parsed[0].contains(&"echo".to_string()), "first command tokens: {parsed:?}");
879        assert_eq!(parsed[1].last().map(String::as_str), Some("done"));
880    }
881
882    #[test]
883    fn strict_parse_rejects_crash_shape_instead_of_crashing() {
884        // parse_shell_commands_tree_sitter has no fallback: strict callers
885        // (validate_bang_shell_command, is_valid_bash_grammar,
886        // looks_like_shell_command) handle Err fail-closed.
887        let result = parse_shell_commands_tree_sitter("{\u{2FA8E}");
888        assert!(result.is_err(), "strict path must reject, not crash: {result:?}");
889    }
890
891    #[test]
892    fn scanner_crash_shape_matches_issue_337_shape() {
893        assert!(scanner_crash_shape("{\u{2FA8E}"));
894        assert!(scanner_crash_shape("echo {a}\u{1F574}"));
895        assert!(scanner_crash_shape("{x} \u{1F847}"));
896        // No brace before the 4-byte lead: safe for the scanner.
897        assert!(!scanner_crash_shape("\u{2FA8E}{"));
898        // No 4-byte lead at all.
899        assert!(!scanner_crash_shape("{hello}"));
900        // 3-byte and 2-byte leads do not trigger the upstream crash.
901        assert!(!scanner_crash_shape("{\u{CAF}\u{9bf}"));
902    }
903}
904
905#[cfg(test)]
906mod tests;