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/// If tree-sitter parsing fails, falls back to simple tokenization
38pub fn parse_shell_commands(script: &str) -> Result<Vec<Vec<String>>, String> {
39    // Try tree-sitter parsing first
40    match parse_with_tree_sitter(script, false) {
41        Ok(commands) if !commands.is_empty() => return Ok(commands),
42        Ok(_) => {} // Empty result, fall through to basic parsing
43        Err(e) => {
44            tracing::debug!("Tree-sitter bash parsing failed: {}, falling back to basic tokenization", e);
45        }
46    }
47
48    // Fallback to simple tokenization
49    parse_with_basic_tokenization(script)
50}
51
52/// Parses a shell script using tree-sitter bash grammar only (no fallback tokenization).
53///
54/// Use this when caller behavior must be strictly gated on bash grammar validity.
55pub fn parse_shell_commands_tree_sitter(script: &str) -> Result<Vec<Vec<String>>, String> {
56    parse_with_tree_sitter(script, true)
57}
58
59/// Returns whether a shell command contains syntax whose meaning depends on
60/// shell expansion rather than the literal argument text.
61///
62/// Safety-sensitive classification must only operate on static command
63/// shapes. Parameter expansion, command substitution, brace expansion,
64/// globbing, and unquoted backslash escapes can otherwise turn a
65/// harmless-looking token into a different executable argument at runtime.
66/// Backslash escapes inside double-quoted arguments are consumed as literal
67/// argument syntax so patterns such as `rg -n "\\[profile"` remain classifiable.
68pub fn contains_dynamic_shell_syntax(command: &str) -> bool {
69    enum ShellQuote {
70        Single,
71        Double,
72    }
73
74    let mut quote: Option<ShellQuote> = None;
75    let mut characters = command.chars();
76
77    while let Some(character) = characters.next() {
78        match quote {
79            Some(ShellQuote::Single) => {
80                if character == '\'' {
81                    quote = None;
82                }
83            }
84            Some(ShellQuote::Double) => match character {
85                '"' => quote = None,
86                '$' | '`' => return true,
87                '\\'
88                    // Backslash escapes inside double quotes are literal
89                    // argument syntax. Consume the escaped character so an
90                    // escaped quote cannot incorrectly end the quoted region;
91                    // unquoted escapes remain rejected below because they can
92                    // alter the command token or its shell structure.
93                    if characters.next().is_none() => {
94                        return true;
95                    }
96                _ => {}
97            },
98            None => match character {
99                '\'' => quote = Some(ShellQuote::Single),
100                '"' => quote = Some(ShellQuote::Double),
101                '\\' | '$' | '`' | '{' | '}' | '*' | '?' | '[' | ']' => return true,
102                _ => {}
103            },
104        }
105    }
106
107    quote.is_some()
108}
109
110/// Returns whether a `find` command contains shell syntax that can change the
111/// literal option tokens after approval-time tokenization.
112pub fn contains_dynamic_find_syntax(script: &str) -> bool {
113    if let Ok(commands) = parse_shell_commands_tree_sitter(script)
114        && commands.iter().any(|command| {
115            command
116                .first()
117                .map(|program| base_command_name(program) == "find")
118                .unwrap_or(false)
119                && command.iter().any(|word| contains_dynamic_shell_syntax(word))
120        })
121    {
122        return true;
123    }
124
125    // Be conservative when the grammar cannot identify the command shape: a
126    // raw script containing a find invocation and dynamic syntax must not pass
127    // preflight just because parsing was incomplete.
128    let has_find_word = script.split_whitespace().any(|word| {
129        let command = word.trim_matches(|character: char| !character.is_ascii_alphanumeric() && character != '/');
130        base_command_name(command) == "find"
131    });
132    has_find_word && contains_dynamic_shell_syntax(script)
133}
134
135/// Returns whether every redirection in a static shell script only routes
136/// command output. Input, heredoc, and descriptor-closing redirections remain
137/// unsupported so progress classification can fail closed.
138pub fn has_only_output_redirections(script: &str) -> bool {
139    if contains_dynamic_shell_syntax(script) {
140        return false;
141    }
142    if contains_background_operator(script) {
143        return false;
144    }
145
146    let Ok(tree) = BashTree::parse(script) else {
147        return false;
148    };
149    if tree.has_error() {
150        return false;
151    }
152
153    let mut saw_redirection = false;
154    if !collect_output_redirections(tree.root(), &mut saw_redirection) {
155        return false;
156    }
157    saw_redirection
158}
159
160/// Validate literal file-redirection targets before command classification drops them.
161/// Descriptor routing carries no path; unresolved shell expansion fails closed.
162pub(crate) fn validate_redirection_paths(script: &str) -> Result<()> {
163    use anyhow::{Context, anyhow, ensure};
164    if !script.contains(['<', '>']) {
165        return Ok(());
166    }
167    let tree = BashTree::parse(script).map_err(|error| anyhow!("failed to parse shell redirections: {error}"))?;
168    ensure!(!tree.has_error(), "cannot validate malformed shell redirections");
169    let mut pending = vec![tree.root()];
170    while let Some(node) = pending.pop() {
171        if node.kind() == "file_redirect" {
172            let text = node.text();
173            let operator = text.trim_start_matches(|character: char| character.is_ascii_digit());
174            let descriptor_route = operator.starts_with(">&") || operator.starts_with("<&");
175            for destination in node.field_children("destination") {
176                let raw = destination.text();
177                ensure!(!contains_dynamic_shell_syntax(raw), "dynamic redirection destination is not allowed");
178                let words = shell_words::split(raw).context("invalid quoted redirection destination")?;
179                ensure!(words.len() == 1, "redirection destination must be one literal path");
180                let path = words.first().context("missing redirection destination")?;
181                if descriptor_route && (path == "-" || path.chars().all(|character| character.is_ascii_digit())) {
182                    continue;
183                }
184                // `sh` expands a leading `~` after validation, so treating it
185                // as a relative literal would let a redirection escape the
186                // workspace (for example, `> ~/.config`). Require callers to
187                // provide an explicit, policy-checked destination instead.
188                ensure!(!path.starts_with('~'), "home-directory redirection destinations are not allowed");
189                // The null sink is the one intentional device path used by normal commands.
190                if path == "/dev/null" {
191                    continue;
192                }
193                vtcode_commons::paths::validate_path_safety(path)
194                    .with_context(|| format!("unsafe shell redirection destination: {path}"))?;
195            }
196        }
197        pending.extend(node.named_children());
198    }
199    Ok(())
200}
201
202fn contains_background_operator(script: &str) -> bool {
203    let chars = script.chars().collect::<Vec<_>>();
204    let mut index = 0;
205    let mut in_single_quote = false;
206    let mut in_double_quote = false;
207
208    while index < chars.len() {
209        let character = chars[index];
210        if character == '\'' && !in_double_quote {
211            in_single_quote.toggle();
212            index += 1;
213            continue;
214        }
215        if character == '"' && !in_single_quote {
216            in_double_quote.toggle();
217            index += 1;
218            continue;
219        }
220        if in_single_quote || in_double_quote {
221            index += 1;
222            continue;
223        }
224
225        if character == '&' {
226            let previous = index.checked_sub(1).and_then(|position| chars.get(position));
227            let next = chars.get(index + 1);
228            if next == Some(&'&') {
229                index += 2;
230                continue;
231            }
232            let part_of_allowed_operator = next == Some(&'&')
233                || next == Some(&'>')
234                || previous == Some(&'>')
235                || previous == Some(&'|')
236                || previous == Some(&'<');
237            if !part_of_allowed_operator {
238                return true;
239            }
240        }
241        index += 1;
242    }
243
244    false
245}
246
247fn collect_output_redirections(node: BashNode<'_>, saw_redirection: &mut bool) -> bool {
248    match node.kind() {
249        "file_redirect" => {
250            *saw_redirection = true;
251            if !is_output_redirection(node.text()) {
252                return false;
253            }
254        }
255        "heredoc_redirect" | "herestring_redirect" => return false,
256        _ => {}
257    }
258
259    node.children()
260        .iter()
261        .all(|child| collect_output_redirections(*child, saw_redirection))
262}
263
264fn is_output_redirection(text: &str) -> bool {
265    let redirect = text.trim_start_matches(|character: char| character.is_ascii_digit());
266    if redirect.starts_with("&>") {
267        return !redirect.starts_with("&>-");
268    }
269    if let Some(destination) = redirect.strip_prefix(">&") {
270        return destination.trim().chars().all(|character| character.is_ascii_digit());
271    }
272
273    redirect.starts_with('>') && !redirect.starts_with(">&-")
274}
275
276/// Parses shell script using tree-sitter bash grammar.
277fn parse_with_tree_sitter(script: &str, reject_syntax_errors: bool) -> Result<Vec<Vec<String>>, String> {
278    let tree = BashTree::parse(script)?;
279
280    let mut commands = Vec::new();
281    if reject_syntax_errors && tree.has_error() {
282        return Err("Shell script contains syntax errors".to_string());
283    }
284
285    // Walk the full tree so commands inside loops/conditionals are remembered
286    // for approval and checked for safety.  Top-level-only extraction misses
287    // common read loops such as `for f in ...; do grep ...; done`.
288    collect_commands_from_node(tree.root(), &mut commands);
289
290    Ok(commands)
291}
292
293fn collect_commands_from_node(node: BashNode<'_>, commands: &mut Vec<Vec<String>>) {
294    match node.kind() {
295        "command" | "simple_command" => {
296            if let Some(cmd) = extract_command_from_node(node)
297                && !cmd.is_empty()
298            {
299                commands.push(cmd);
300            }
301        }
302        _ => {
303            for child in node.children() {
304                collect_commands_from_node(child, commands);
305            }
306        }
307    }
308}
309
310/// Extracts a command vector from a bash AST node
311fn extract_command_from_node(node: BashNode<'_>) -> Option<Vec<String>> {
312    let mut command = Vec::new();
313
314    // For pipeline nodes, extract the first command in the pipeline
315    if node.kind() == "pipeline" {
316        for child in node.children() {
317            if child.kind() == "command" || child.kind() == "simple_command" {
318                return extract_command_from_node(child);
319            }
320        }
321    }
322
323    // Extract arguments from command node
324    for child in node.children() {
325        if child.kind() == "command_name" {
326            let trimmed = child.text().trim();
327            if !trimmed.is_empty() {
328                command.push(trimmed.to_string());
329            }
330            continue;
331        }
332
333        // Leading `KEY=value` prefixes and concatenated assignment values
334        // (`NODE_OPTIONS='--require ./x'`) are part of the command's
335        // environment contract. Keep them as one word so intent/activity
336        // classification can inspect injection keys;
337        // `command_words_after_environment_prefix` still strips them before
338        // locating the executable. `concatenation` must use the full span
339        // text — its children are only the `NAME=` and quoted value pieces.
340        if matches!(child.kind(), "variable_assignment" | "concatenation") {
341            let trimmed = child.text().trim();
342            if !trimmed.is_empty() {
343                command.push(trimmed.to_string());
344            }
345            continue;
346        }
347
348        if matches!(
349            child.kind(),
350            "word" | "string" | "raw_string" | "ansi_c_string" | "simple_expansion" | "variable_expansion"
351        ) {
352            let trimmed = child.text().trim();
353            if !trimmed.is_empty() {
354                command.push(trimmed.to_string());
355            }
356        }
357    }
358
359    if command.is_empty() { None } else { Some(command) }
360}
361
362/// Fallback: Parses shell script with simple tokenization
363fn parse_with_basic_tokenization(script: &str) -> Result<Vec<Vec<String>>, String> {
364    let mut commands = Vec::new();
365    let mut current_command = String::new();
366    let mut in_quotes = false;
367    let mut quote_char = ' ';
368    let mut escaped = false;
369
370    for ch in script.chars() {
371        if escaped {
372            current_command.push(ch);
373            escaped = false;
374            continue;
375        }
376
377        match ch {
378            '\\' => {
379                escaped = true;
380            }
381            '\'' | '"' if !in_quotes => {
382                in_quotes = true;
383                quote_char = ch;
384            }
385            c if c == quote_char && in_quotes => {
386                in_quotes = false;
387            }
388            '&' | '|' | ';' if !in_quotes => {
389                if !current_command.trim().is_empty()
390                    && let Ok(cmd) = tokenize_command(&current_command)
391                {
392                    commands.push(cmd);
393                }
394                current_command.clear();
395            }
396            _ => current_command.push(ch),
397        }
398    }
399
400    if !current_command.trim().is_empty()
401        && let Ok(cmd) = tokenize_command(&current_command)
402    {
403        commands.push(cmd);
404    }
405
406    Ok(commands)
407}
408
409/// Splits a command string into arguments
410/// Respects quoted strings and escapes
411fn tokenize_command(cmd: &str) -> Result<Vec<String>, String> {
412    shell_words::split(cmd).map_err(|err| format!("failed to tokenize command: {err}"))
413}
414
415/// Parses `bash -lc "script"` style invocations
416///
417/// # Example
418/// ```text
419/// Input:  vec!["bash", "-lc", "git status && rm /"]
420/// Output: Some([["git", "status"], ["rm", "/"]])
421/// ```
422pub fn parse_bash_lc_commands(command: &[String]) -> Option<Vec<Vec<String>>> {
423    if command.is_empty() {
424        return None;
425    }
426
427    let cmd_name = command[0].as_str();
428    let base_cmd = std::path::Path::new(cmd_name)
429        .file_name()
430        .and_then(|osstr| osstr.to_str())
431        .unwrap_or("");
432
433    if base_cmd != "bash" && base_cmd != "zsh" && base_cmd != "sh" {
434        return None;
435    }
436
437    // Look for -lc or -c pattern
438    for window in command.windows(2) {
439        if matches!(window[0].as_str(), "-lc" | "-c" | "-il" | "-ic") {
440            let script = &window[1];
441            return parse_shell_commands(script).ok();
442        }
443    }
444
445    None
446}
447
448// === Injection detection (moved from tools::validation::commands) ===
449
450use anyhow::{anyhow, bail};
451
452/// Delimiter token of a quoted heredoc starting just after `<<` / `<<-`.
453///
454/// Returns `(delimiter, token_byte_len)` where the token covers the optional
455/// `-`, surrounding whitespace, and the quoted delimiter word. Bare
456/// (unquoted) delimiters return `None`: those bodies still allow substitution.
457pub(crate) fn quoted_heredoc_delim(rest: &str) -> Option<(String, usize)> {
458    let mut idx = 0usize;
459    let bytes = rest.as_bytes();
460    if bytes.first() == Some(&b'-') {
461        idx += 1;
462    }
463    while idx < bytes.len() && (bytes[idx] == b' ' || bytes[idx] == b'\t') {
464        idx += 1;
465    }
466    let quote = match bytes.get(idx) {
467        Some(b'\'') | Some(b'"') => bytes[idx],
468        _ => return None,
469    };
470    idx += 1;
471    let delim_start = idx;
472    while idx < bytes.len() && bytes[idx] != quote {
473        idx += 1;
474    }
475    if idx >= bytes.len() || idx == delim_start {
476        return None;
477    }
478    let delim = rest[delim_start..idx].to_string();
479    idx += 1; // closing quote
480    Some((delim, idx))
481}
482
483/// Byte length of a quoted heredoc body starting just after the opener line's
484/// newline, through the closing delimiter line (inclusive). Returns `None`
485/// when the closing delimiter never appears so callers keep scanning the
486/// unterminated body and fail closed on anything executable inside it.
487pub(crate) fn heredoc_body_skip_len(rest: &str, delim: &str) -> Option<usize> {
488    let bytes = rest.as_bytes();
489    let mut idx = 0usize;
490    while idx <= bytes.len() {
491        let line_end = rest[idx..].find('\n').map(|offset| idx + offset).unwrap_or(bytes.len());
492        let line = rest[idx..line_end].trim_end_matches('\r');
493        let next = if line_end < bytes.len() {
494            line_end + 1
495        } else {
496            bytes.len()
497        };
498        if line == delim {
499            return Some(next);
500        }
501        if line_end >= bytes.len() {
502            return None;
503        }
504        idx = next;
505    }
506    None
507}
508
509/// Advance a `CharIndices` iterator by at most `max_bytes`, returning the byte
510/// index just past the last consumed char (or `fallback` when nothing remains).
511fn consume_bytes(
512    chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>,
513    max_bytes: usize,
514    fallback: usize,
515) -> usize {
516    let mut consumed = 0usize;
517    let mut end = fallback;
518    while consumed < max_bytes
519        && let Some((idx, ch)) = chars.next()
520    {
521        consumed += ch.len_utf8();
522        end = idx + ch.len_utf8();
523    }
524    end
525}
526
527/// Quote state for shell segment splitting.
528#[derive(Clone, Copy, Eq, PartialEq)]
529enum QuoteState {
530    None,
531    Single,
532    Double,
533}
534
535/// Command substitution construct that tripped an injection scan.
536#[derive(Clone, Copy, Debug, PartialEq, Eq)]
537pub(crate) enum SubstitutionKind {
538    Backtick,
539    DollarParen,
540}
541
542impl SubstitutionKind {
543    fn label(self) -> &'static str {
544        match self {
545            Self::Backtick => "backtick",
546            Self::DollarParen => "'$('",
547        }
548    }
549}
550
551/// Actionable injection error: names the construct and its byte offset so the
552/// caller can locate the rejected span in its own command. Keeps the legacy
553/// "Command injection pattern detected" prefix so downstream policy matchers
554/// (`preflight_policy_correction`) keep routing to the security-policy branch.
555pub(crate) fn substitution_error(kind: SubstitutionKind, byte_idx: usize) -> anyhow::Error {
556    anyhow!(
557        "Command injection pattern detected: {} command substitution at byte {byte_idx}; rewrite without dynamic expansion",
558        kind.label()
559    )
560}
561
562/// Split a shell command into segments on unquoted `|` and `&` boundaries,
563/// while detecting injection patterns (`;`, backticks, `$()`, newlines).
564pub(crate) fn split_shell_segments(command: &str) -> Result<Vec<String>> {
565    let mut segments = Vec::new();
566    let mut state = QuoteState::None;
567    let mut escaped = false;
568    let mut segment_start = 0usize;
569    // Delimiter of a `<<'EOF'`-shaped heredoc whose opener line has not ended
570    // yet. The opener line stays live shell; the body is skipped at the
571    // unquoted newline.
572    let mut pending_heredoc: Option<String> = None;
573    let mut chars = command.char_indices().peekable();
574
575    while let Some((idx, ch)) = chars.next() {
576        match state {
577            QuoteState::Single => {
578                if ch == '\'' {
579                    state = QuoteState::None;
580                }
581            }
582            QuoteState::Double => {
583                if escaped {
584                    escaped = false;
585                    continue;
586                }
587
588                match ch {
589                    '\\' => escaped = true,
590                    '"' => state = QuoteState::None,
591                    '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
592                    '$' if matches!(chars.peek(), Some((_, '('))) => {
593                        return Err(substitution_error(SubstitutionKind::DollarParen, idx));
594                    }
595                    _ => {}
596                }
597            }
598            QuoteState::None => {
599                if escaped {
600                    escaped = false;
601                    continue;
602                }
603
604                match ch {
605                    '\\' => escaped = true,
606                    '\'' => state = QuoteState::Single,
607                    '"' => state = QuoteState::Double,
608                    // Quoted heredoc bodies are literal data (newlines, backticks
609                    // included). Arm the skip here but keep scanning: everything
610                    // after the delimiter on the opener line is live shell, so
611                    // operators there must still split segments or bail. The
612                    // body is skipped at the unquoted opener newline below.
613                    '<' if matches!(chars.peek(), Some((_, '<'))) => {
614                        let _ = chars.next(); // second '<'
615                        let rest: String = chars.clone().map(|(_, c)| c).collect();
616                        if let Some((delim, token_len)) = quoted_heredoc_delim(&rest) {
617                            let _ = consume_bytes(&mut chars, token_len, idx + ch.len_utf8());
618                            pending_heredoc = Some(delim);
619                        }
620                    }
621                    '`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
622                    '$' if matches!(chars.peek(), Some((_, '('))) => {
623                        return Err(substitution_error(SubstitutionKind::DollarParen, idx));
624                    }
625                    ';' => bail!("Unquoted command chaining detected"),
626                    '\n' => {
627                        // The opener line ended in unquoted context: the quoted
628                        // heredoc body starts here and is literal data. Without
629                        // a closing delimiter the body keeps being scanned, so
630                        // executable content in it still fails closed.
631                        if let Some(delim) = pending_heredoc.take() {
632                            let rest: String = chars.clone().map(|(_, c)| c).collect();
633                            if let Some(skip) = heredoc_body_skip_len(&rest, &delim) {
634                                // The opener line is a live command; the body
635                                // belongs to no segment.
636                                push_segment(command, segment_start, idx, &mut segments);
637                                segment_start = consume_bytes(&mut chars, skip, command.len());
638                                continue;
639                            }
640                        }
641                        bail!(
642                            "multi-line shell commands are not allowed; write the content with `apply_patch` instead of a heredoc"
643                        );
644                    }
645                    '|' | '&' => {
646                        push_segment(command, segment_start, idx, &mut segments);
647                        segment_start = idx + ch.len_utf8();
648                        if let Some((next_idx, next_ch)) = chars.peek().copied()
649                            && next_ch == ch
650                        {
651                            let _next = chars.next();
652                            segment_start = next_idx + next_ch.len_utf8();
653                        }
654                    }
655                    _ => {}
656                }
657            }
658        }
659    }
660
661    push_segment(command, segment_start, command.len(), &mut segments);
662    Ok(segments)
663}
664
665fn push_segment(command: &str, start: usize, end: usize, segments: &mut Vec<String>) {
666    let segment = command[start..end].trim();
667    if !segment.is_empty() {
668        segments.push(segment.to_string());
669    }
670}
671
672/// Check for additional dangerous patterns not covered by the central dangerous-command detector.
673pub(crate) fn additional_dangerous_pattern(segment: &str) -> Option<&'static str> {
674    let segment_lower = segment.to_ascii_lowercase();
675    if segment_lower.starts_with(":(){:|:&};:") {
676        return Some(":(){:|:&};:");
677    }
678
679    let tokens =
680        shell_words::split(segment).unwrap_or_else(|_| segment.split_whitespace().map(ToString::to_string).collect());
681    let first = tokens.first()?;
682    let command_name = base_command_name(strip_wrapping_quotes(first)).to_ascii_lowercase();
683
684    match command_name.as_str() {
685        "rmdir" => Some("rmdir"),
686        "wget" => Some("wget"),
687        "curl" => Some("curl"),
688        "chmod" if tokens.iter().skip(1).any(|arg| strip_wrapping_quotes(arg).starts_with("777")) => Some("chmod 777"),
689        "chown"
690            if tokens.iter().skip(1).any(|arg| {
691                let arg = strip_wrapping_quotes(arg).to_ascii_lowercase();
692                arg == "root" || arg.starts_with("root:")
693            }) =>
694        {
695            Some("chown root")
696        }
697        _ => None,
698    }
699}
700
701fn strip_wrapping_quotes(token: &str) -> &str {
702    token
703        .strip_prefix('\'')
704        .and_then(|token| token.strip_suffix('\''))
705        .or_else(|| token.strip_prefix('"').and_then(|token| token.strip_suffix('"')))
706        .unwrap_or(token)
707}
708
709fn base_command_name(command: &str) -> &str {
710    std::path::Path::new(command)
711        .file_name()
712        .and_then(|name| name.to_str())
713        .unwrap_or(command)
714}
715#[cfg(test)]
716mod tests;