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/// Parses shell script using tree-sitter bash grammar.
298fn parse_with_tree_sitter(script: &str, reject_syntax_errors: bool) -> Result<Vec<Vec<String>>, String> {
299    // Never hand the scanner an input upstream tree-sitter-bash #337 crashes
300    // on: the guard covers both the lenient route (parse_shell_commands falls
301    // back to basic tokenization on Err) and every strict caller, which
302    // already handle Err fail-closed.
303    if scanner_crash_shape(script) {
304        return Err("shell script matches the tree-sitter-bash #337 scanner crash shape".to_string());
305    }
306    let tree = BashTree::parse(script)?;
307
308    let mut commands = Vec::new();
309    if reject_syntax_errors && tree.has_error() {
310        return Err("Shell script contains syntax errors".to_string());
311    }
312
313    // Walk the full tree so commands inside loops/conditionals are remembered
314    // for approval and checked for safety.  Top-level-only extraction misses
315    // common read loops such as `for f in ...; do grep ...; done`.
316    collect_commands_from_node(tree.root(), &mut commands);
317
318    Ok(commands)
319}
320
321fn collect_commands_from_node(node: BashNode<'_>, commands: &mut Vec<Vec<String>>) {
322    match node.kind() {
323        "command" | "simple_command" => {
324            if let Some(cmd) = extract_command_from_node(node)
325                && !cmd.is_empty()
326            {
327                commands.push(cmd);
328            }
329        }
330        _ => {
331            for child in node.children() {
332                collect_commands_from_node(child, commands);
333            }
334        }
335    }
336}
337
338/// Extracts a command vector from a bash AST node
339fn extract_command_from_node(node: BashNode<'_>) -> Option<Vec<String>> {
340    let mut command = Vec::new();
341
342    // For pipeline nodes, extract the first command in the pipeline
343    if node.kind() == "pipeline" {
344        for child in node.children() {
345            if child.kind() == "command" || child.kind() == "simple_command" {
346                return extract_command_from_node(child);
347            }
348        }
349    }
350
351    // Extract arguments from command node
352    for child in node.children() {
353        if child.kind() == "command_name" {
354            let trimmed = child.text().trim();
355            if !trimmed.is_empty() {
356                command.push(trimmed.to_string());
357            }
358            continue;
359        }
360
361        // Leading `KEY=value` prefixes and concatenated assignment values
362        // (`NODE_OPTIONS='--require ./x'`) are part of the command's
363        // environment contract. Keep them as one word so intent/activity
364        // classification can inspect injection keys;
365        // `command_words_after_environment_prefix` still strips them before
366        // locating the executable. `concatenation` must use the full span
367        // text — its children are only the `NAME=` and quoted value pieces.
368        if matches!(child.kind(), "variable_assignment" | "concatenation") {
369            let trimmed = child.text().trim();
370            if !trimmed.is_empty() {
371                command.push(trimmed.to_string());
372            }
373            continue;
374        }
375
376        if matches!(
377            child.kind(),
378            "word" | "string" | "raw_string" | "ansi_c_string" | "simple_expansion" | "variable_expansion"
379        ) {
380            let trimmed = child.text().trim();
381            if !trimmed.is_empty() {
382                command.push(trimmed.to_string());
383            }
384        }
385    }
386
387    if command.is_empty() { None } else { Some(command) }
388}
389
390/// Fallback: Parses shell script with simple tokenization
391fn parse_with_basic_tokenization(script: &str) -> Result<Vec<Vec<String>>, String> {
392    let mut commands = Vec::new();
393    let mut current_command = String::new();
394    let mut in_quotes = false;
395    let mut quote_char = ' ';
396    let mut escaped = false;
397
398    for ch in script.chars() {
399        if escaped {
400            current_command.push(ch);
401            escaped = false;
402            continue;
403        }
404
405        match ch {
406            '\\' => {
407                escaped = true;
408            }
409            '\'' | '"' if !in_quotes => {
410                in_quotes = true;
411                quote_char = ch;
412            }
413            c if c == quote_char && in_quotes => {
414                in_quotes = false;
415            }
416            '&' | '|' | ';' if !in_quotes => {
417                if !current_command.trim().is_empty()
418                    && let Ok(cmd) = tokenize_command(&current_command)
419                {
420                    commands.push(cmd);
421                }
422                current_command.clear();
423            }
424            _ => current_command.push(ch),
425        }
426    }
427
428    if !current_command.trim().is_empty()
429        && let Ok(cmd) = tokenize_command(&current_command)
430    {
431        commands.push(cmd);
432    }
433
434    Ok(commands)
435}
436
437/// Splits a command string into arguments
438/// Respects quoted strings and escapes
439fn tokenize_command(cmd: &str) -> Result<Vec<String>, String> {
440    shell_words::split(cmd).map_err(|err| format!("failed to tokenize command: {err}"))
441}
442
443/// Parses `bash -lc "script"` style invocations
444///
445/// # Example
446/// ```text
447/// Input:  vec!["bash", "-lc", "git status && rm /"]
448/// Output: Some([["git", "status"], ["rm", "/"]])
449/// ```
450pub fn parse_bash_lc_commands(command: &[String]) -> Option<Vec<Vec<String>>> {
451    if command.is_empty() {
452        return None;
453    }
454
455    let cmd_name = command[0].as_str();
456    let base_cmd = std::path::Path::new(cmd_name)
457        .file_name()
458        .and_then(|osstr| osstr.to_str())
459        .unwrap_or("");
460
461    if base_cmd != "bash" && base_cmd != "zsh" && base_cmd != "sh" {
462        return None;
463    }
464
465    // Look for -lc or -c pattern
466    for window in command.windows(2) {
467        if matches!(window[0].as_str(), "-lc" | "-c" | "-il" | "-ic") {
468            let script = &window[1];
469            return parse_shell_commands(script).ok();
470        }
471    }
472
473    None
474}
475
476// === Injection detection (moved from tools::validation::commands) ===
477
478use anyhow::{anyhow, bail};
479
480/// Delimiter token of a quoted heredoc starting just after `<<` / `<<-`.
481///
482/// Returns `(delimiter, token_byte_len)` where the token covers the optional
483/// `-`, surrounding whitespace, and the quoted delimiter word. Bare
484/// (unquoted) delimiters return `None`: those bodies still allow substitution.
485pub(crate) fn quoted_heredoc_delim(rest: &str) -> Option<(String, usize)> {
486    let mut idx = 0usize;
487    let bytes = rest.as_bytes();
488    if bytes.first() == Some(&b'-') {
489        idx += 1;
490    }
491    while idx < bytes.len() && (bytes[idx] == b' ' || bytes[idx] == b'\t') {
492        idx += 1;
493    }
494    let quote = match bytes.get(idx) {
495        Some(b'\'') | Some(b'"') => bytes[idx],
496        _ => return None,
497    };
498    idx += 1;
499    let delim_start = idx;
500    while idx < bytes.len() && bytes[idx] != quote {
501        idx += 1;
502    }
503    if idx >= bytes.len() || idx == delim_start {
504        return None;
505    }
506    let delim = rest[delim_start..idx].to_string();
507    idx += 1; // closing quote
508    Some((delim, idx))
509}
510
511/// Byte length of a quoted heredoc body starting just after the opener line's
512/// newline, through the closing delimiter line (inclusive). Returns `None`
513/// when the closing delimiter never appears so callers keep scanning the
514/// unterminated body and fail closed on anything executable inside it.
515pub(crate) fn heredoc_body_skip_len(rest: &str, delim: &str) -> Option<usize> {
516    let bytes = rest.as_bytes();
517    let mut idx = 0usize;
518    while idx <= bytes.len() {
519        let line_end = rest[idx..].find('\n').map(|offset| idx + offset).unwrap_or(bytes.len());
520        let line = rest[idx..line_end].trim_end_matches('\r');
521        let next = if line_end < bytes.len() {
522            line_end + 1
523        } else {
524            bytes.len()
525        };
526        if line == delim {
527            return Some(next);
528        }
529        if line_end >= bytes.len() {
530            return None;
531        }
532        idx = next;
533    }
534    None
535}
536
537/// Advance a `CharIndices` iterator by at most `max_bytes`, returning the byte
538/// index just past the last consumed char (or `fallback` when nothing remains).
539fn consume_bytes(
540    chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>,
541    max_bytes: usize,
542    fallback: usize,
543) -> usize {
544    let mut consumed = 0usize;
545    let mut end = fallback;
546    while consumed < max_bytes
547        && let Some((idx, ch)) = chars.next()
548    {
549        consumed += ch.len_utf8();
550        end = idx + ch.len_utf8();
551    }
552    end
553}
554
555/// Quote state for shell segment splitting.
556#[derive(Clone, Copy, Eq, PartialEq)]
557enum QuoteState {
558    None,
559    Single,
560    Double,
561}
562
563/// Command substitution construct that tripped an injection scan.
564#[derive(Clone, Copy, Debug, PartialEq, Eq)]
565pub(crate) enum SubstitutionKind {
566    Backtick,
567    DollarParen,
568}
569
570impl SubstitutionKind {
571    fn label(self) -> &'static str {
572        match self {
573            Self::Backtick => "backtick",
574            Self::DollarParen => "'$('",
575        }
576    }
577}
578
579/// Actionable injection error: names the construct and its byte offset so the
580/// caller can locate the rejected span in its own command. Keeps the legacy
581/// "Command injection pattern detected" prefix so downstream policy matchers
582/// (`preflight_policy_correction`) keep routing to the security-policy branch.
583pub(crate) fn substitution_error(kind: SubstitutionKind, byte_idx: usize) -> anyhow::Error {
584    anyhow!(
585        "Command injection pattern detected: {} command substitution at byte {byte_idx}; rewrite without dynamic expansion",
586        kind.label()
587    )
588}
589
590/// Split a shell command into segments on unquoted `|` and `&` boundaries,
591/// while detecting injection patterns (`;`, backticks, `$()`, newlines).
592pub(crate) fn split_shell_segments(command: &str) -> Result<Vec<String>> {
593    let mut segments = Vec::new();
594    let mut state = QuoteState::None;
595    let mut escaped = false;
596    let mut segment_start = 0usize;
597    // Delimiter of a `<<'EOF'`-shaped heredoc whose opener line has not ended
598    // yet. The opener line stays live shell; the body is skipped at the
599    // unquoted newline.
600    let mut pending_heredoc: Option<String> = None;
601    let mut chars = command.char_indices().peekable();
602
603    while let Some((idx, ch)) = chars.next() {
604        match state {
605            QuoteState::Single => {
606                if ch == '\'' {
607                    state = QuoteState::None;
608                }
609            }
610            QuoteState::Double => {
611                if escaped {
612                    escaped = false;
613                    continue;
614                }
615
616                match ch {
617                    '\\' => escaped = true,
618                    '"' => state = QuoteState::None,
619                    '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
620                    '$' if matches!(chars.peek(), Some((_, '('))) => {
621                        return Err(substitution_error(SubstitutionKind::DollarParen, idx));
622                    }
623                    _ => {}
624                }
625            }
626            QuoteState::None => {
627                if escaped {
628                    escaped = false;
629                    // A backslash-escaped semicolon is a literal in bash but a
630                    // statement separator in PowerShell (which escapes with
631                    // `^`, not `\`). Reject it here so this platform-agnostic
632                    // validator cannot be blinded to command chaining by `\;`.
633                    if ch == ';' {
634                        bail!("Escaped command chaining detected");
635                    }
636                    continue;
637                }
638
639                match ch {
640                    '\\' => escaped = true,
641                    '\'' => state = QuoteState::Single,
642                    '"' => state = QuoteState::Double,
643                    // Quoted heredoc bodies are literal data (newlines, backticks
644                    // included). Arm the skip here but keep scanning: everything
645                    // after the delimiter on the opener line is live shell, so
646                    // operators there must still split segments or bail. The
647                    // body is skipped at the unquoted opener newline below.
648                    '<' if matches!(chars.peek(), Some((_, '<'))) => {
649                        let _ = chars.next(); // second '<'
650                        let rest: String = chars.clone().map(|(_, c)| c).collect();
651                        if let Some((delim, token_len)) = quoted_heredoc_delim(&rest) {
652                            let _ = consume_bytes(&mut chars, token_len, idx + ch.len_utf8());
653                            pending_heredoc = Some(delim);
654                        }
655                    }
656                    '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
657                    '$' if matches!(chars.peek(), Some((_, '('))) => {
658                        return Err(substitution_error(SubstitutionKind::DollarParen, idx));
659                    }
660                    ';' => bail!("Unquoted command chaining detected"),
661                    '\n' => {
662                        // The opener line ended in unquoted context: the quoted
663                        // heredoc body starts here and is literal data. Without
664                        // a closing delimiter the body keeps being scanned, so
665                        // executable content in it still fails closed.
666                        if let Some(delim) = pending_heredoc.take() {
667                            let rest: String = chars.clone().map(|(_, c)| c).collect();
668                            if let Some(skip) = heredoc_body_skip_len(&rest, &delim) {
669                                // The opener line is a live command; the body
670                                // belongs to no segment.
671                                push_segment(command, segment_start, idx, &mut segments);
672                                segment_start = consume_bytes(&mut chars, skip, command.len());
673                                continue;
674                            }
675                        }
676                        bail!(
677                            "multi-line shell commands are not allowed; write the content with `apply_patch` instead of a heredoc"
678                        );
679                    }
680                    '|' | '&' => {
681                        push_segment(command, segment_start, idx, &mut segments);
682                        segment_start = idx + ch.len_utf8();
683                        if let Some((next_idx, next_ch)) = chars.peek().copied()
684                            && next_ch == ch
685                        {
686                            let _next = chars.next();
687                            segment_start = next_idx + next_ch.len_utf8();
688                        }
689                    }
690                    _ => {}
691                }
692            }
693        }
694    }
695
696    push_segment(command, segment_start, command.len(), &mut segments);
697    Ok(segments)
698}
699
700fn push_segment(command: &str, start: usize, end: usize, segments: &mut Vec<String>) {
701    let segment = command[start..end].trim();
702    if !segment.is_empty() {
703        segments.push(segment.to_string());
704    }
705}
706
707/// Check for additional dangerous patterns not covered by the central dangerous-command detector.
708pub(crate) fn additional_dangerous_pattern(segment: &str) -> Option<&'static str> {
709    let segment_lower = segment.to_ascii_lowercase();
710    if segment_lower.starts_with(":(){:|:&};:") {
711        return Some(":(){:|:&};:");
712    }
713
714    let tokens =
715        shell_words::split(segment).unwrap_or_else(|_| segment.split_whitespace().map(ToString::to_string).collect());
716    let first = tokens.first()?;
717    let command_name = base_command_name(strip_wrapping_quotes(first)).to_ascii_lowercase();
718
719    match command_name.as_str() {
720        "rmdir" => Some("rmdir"),
721        "wget" => Some("wget"),
722        "curl" => Some("curl"),
723        "chmod" if tokens.iter().skip(1).any(|arg| strip_wrapping_quotes(arg).starts_with("777")) => Some("chmod 777"),
724        "chown"
725            if tokens.iter().skip(1).any(|arg| {
726                let arg = strip_wrapping_quotes(arg).to_ascii_lowercase();
727                arg == "root" || arg.starts_with("root:")
728            }) =>
729        {
730            Some("chown root")
731        }
732        _ => None,
733    }
734}
735
736fn strip_wrapping_quotes(token: &str) -> &str {
737    token
738        .strip_prefix('\'')
739        .and_then(|token| token.strip_suffix('\''))
740        .or_else(|| token.strip_prefix('"').and_then(|token| token.strip_suffix('"')))
741        .unwrap_or(token)
742}
743
744fn base_command_name(command: &str) -> &str {
745    std::path::Path::new(command)
746        .file_name()
747        .and_then(|name| name.to_str())
748        .unwrap_or(command)
749}
750#[cfg(test)]
751mod crash_regression {
752    use super::*;
753
754    /// tree-sitter-bash #337: `{` + U+2FA8E (the delta-minimal reproducer,
755    /// found by fuzzing on linux) SIGSEGV'd the external scanner and killed
756    /// the process; the guard routes such input to the basic tokenizer.
757    #[test]
758    fn parse_survives_brace_plus_astral_input() {
759        let parsed = parse_shell_commands("{\u{2FA8E}");
760        assert!(parsed.is_ok(), "parse must not fail: {parsed:?}");
761
762        // A real command containing the crash shape keeps its tokens, and a
763        // following command survives too.
764        let parsed = parse_shell_commands("echo {\u{2FA8E}} && echo done").expect("two commands");
765        assert_eq!(parsed.len(), 2, "both commands must survive: {parsed:?}");
766        assert!(parsed[0].contains(&"echo".to_string()), "first command tokens: {parsed:?}");
767        assert_eq!(parsed[1].last().map(String::as_str), Some("done"));
768    }
769
770    #[test]
771    fn strict_parse_rejects_crash_shape_instead_of_crashing() {
772        // parse_shell_commands_tree_sitter has no fallback: strict callers
773        // (validate_bang_shell_command, is_valid_bash_grammar,
774        // looks_like_shell_command) handle Err fail-closed.
775        let result = parse_shell_commands_tree_sitter("{\u{2FA8E}");
776        assert!(result.is_err(), "strict path must reject, not crash: {result:?}");
777    }
778
779    #[test]
780    fn scanner_crash_shape_matches_issue_337_shape() {
781        assert!(scanner_crash_shape("{\u{2FA8E}"));
782        assert!(scanner_crash_shape("echo {a}\u{1F574}"));
783        assert!(scanner_crash_shape("{x} \u{1F847}"));
784        // No brace before the 4-byte lead: safe for the scanner.
785        assert!(!scanner_crash_shape("\u{2FA8E}{"));
786        // No 4-byte lead at all.
787        assert!(!scanner_crash_shape("{hello}"));
788        // 3-byte and 2-byte leads do not trigger the upstream crash.
789        assert!(!scanner_crash_shape("{\u{CAF}\u{9bf}"));
790    }
791}
792
793#[cfg(test)]
794mod tests;