#![expect(
clippy::indexing_slicing,
clippy::string_slice,
reason = "Shell parsing tracks byte offsets at character boundaries while validating operator pairs."
)]
mod ast;
use anyhow::Result;
pub use ast::{BashNode, BashTree, prewarm_bash_parser};
fn scanner_crash_shape(script: &str) -> bool {
let mut saw_open_brace = false;
for byte in script.as_bytes() {
match byte {
b'{' => saw_open_brace = true,
0xF0..=0xF7 if saw_open_brace => return true,
_ => {}
}
}
false
}
pub fn parse_shell_commands(script: &str) -> Result<Vec<Vec<String>>, String> {
match parse_with_tree_sitter(script, false) {
Ok(commands) if !commands.is_empty() => return Ok(commands),
Ok(_) => {} Err(e) => {
tracing::debug!("Tree-sitter bash parsing failed: {}, falling back to basic tokenization", e);
}
}
parse_with_basic_tokenization(script)
}
pub fn parse_shell_commands_tree_sitter(script: &str) -> Result<Vec<Vec<String>>, String> {
parse_with_tree_sitter(script, true)
}
pub fn contains_dynamic_shell_syntax(command: &str) -> bool {
enum ShellQuote {
Single,
Double,
}
let mut quote: Option<ShellQuote> = None;
let mut characters = command.chars();
while let Some(character) = characters.next() {
match quote {
Some(ShellQuote::Single) => {
if character == '\'' {
quote = None;
}
}
Some(ShellQuote::Double) => match character {
'"' => quote = None,
'$' | '`' => return true,
'\\'
if characters.next().is_none() => {
return true;
}
_ => {}
},
None => match character {
'\'' => quote = Some(ShellQuote::Single),
'"' => quote = Some(ShellQuote::Double),
'\\' | '$' | '`' | '{' | '}' | '*' | '?' | '[' | ']' => return true,
_ => {}
},
}
}
quote.is_some()
}
pub fn contains_dynamic_find_syntax(script: &str) -> bool {
if let Ok(commands) = parse_shell_commands_tree_sitter(script)
&& commands.iter().any(|command| {
command
.first()
.map(|program| base_command_name(program) == "find")
.unwrap_or(false)
&& command.iter().any(|word| contains_dynamic_shell_syntax(word))
})
{
return true;
}
let has_find_word = script.split_whitespace().any(|word| {
let command = word.trim_matches(|character: char| !character.is_ascii_alphanumeric() && character != '/');
base_command_name(command) == "find"
});
has_find_word && contains_dynamic_shell_syntax(script)
}
pub fn has_only_output_redirections(script: &str) -> bool {
if contains_dynamic_shell_syntax(script) {
return false;
}
if contains_background_operator(script) {
return false;
}
let Ok(tree) = BashTree::parse(script) else {
return false;
};
if tree.has_error() {
return false;
}
let mut saw_redirection = false;
if !collect_output_redirections(tree.root(), &mut saw_redirection) {
return false;
}
saw_redirection
}
pub(crate) fn validate_redirection_paths(script: &str) -> Result<()> {
use anyhow::{Context, anyhow, ensure};
if !script.contains(['<', '>']) {
return Ok(());
}
let tree = BashTree::parse(script).map_err(|error| anyhow!("failed to parse shell redirections: {error}"))?;
ensure!(!tree.has_error(), "cannot validate malformed shell redirections");
let mut pending = vec![tree.root()];
while let Some(node) = pending.pop() {
if node.kind() == "file_redirect" {
let text = node.text();
let operator = text.trim_start_matches(|character: char| character.is_ascii_digit());
let descriptor_route = operator.starts_with(">&") || operator.starts_with("<&");
for destination in node.field_children("destination") {
let raw = destination.text();
ensure!(!contains_dynamic_shell_syntax(raw), "dynamic redirection destination is not allowed");
let words = shell_words::split(raw).context("invalid quoted redirection destination")?;
ensure!(words.len() == 1, "redirection destination must be one literal path");
let path = words.first().context("missing redirection destination")?;
if descriptor_route && (path == "-" || path.chars().all(|character| character.is_ascii_digit())) {
continue;
}
ensure!(!path.starts_with('~'), "home-directory redirection destinations are not allowed");
if path == "/dev/null" {
continue;
}
vtcode_commons::paths::validate_path_safety(path)
.with_context(|| format!("unsafe shell redirection destination: {path}"))?;
}
}
pending.extend(node.named_children());
}
Ok(())
}
fn contains_background_operator(script: &str) -> bool {
let chars = script.chars().collect::<Vec<_>>();
let mut index = 0;
let mut in_single_quote = false;
let mut in_double_quote = false;
while index < chars.len() {
let character = chars[index];
if character == '\'' && !in_double_quote {
in_single_quote.toggle();
index += 1;
continue;
}
if character == '"' && !in_single_quote {
in_double_quote.toggle();
index += 1;
continue;
}
if in_single_quote || in_double_quote {
index += 1;
continue;
}
if character == '&' {
let previous = index.checked_sub(1).and_then(|position| chars.get(position));
let next = chars.get(index + 1);
if next == Some(&'&') {
index += 2;
continue;
}
let part_of_allowed_operator = next == Some(&'&')
|| next == Some(&'>')
|| previous == Some(&'>')
|| previous == Some(&'|')
|| previous == Some(&'<');
if !part_of_allowed_operator {
return true;
}
}
index += 1;
}
false
}
fn collect_output_redirections(node: BashNode<'_>, saw_redirection: &mut bool) -> bool {
match node.kind() {
"file_redirect" => {
*saw_redirection = true;
if !is_output_redirection(node.text()) {
return false;
}
}
"heredoc_redirect" | "herestring_redirect" => return false,
_ => {}
}
node.children()
.iter()
.all(|child| collect_output_redirections(*child, saw_redirection))
}
fn is_output_redirection(text: &str) -> bool {
let redirect = text.trim_start_matches(|character: char| character.is_ascii_digit());
if redirect.starts_with("&>") {
return !redirect.starts_with("&>-");
}
if let Some(destination) = redirect.strip_prefix(">&") {
return destination.trim().chars().all(|character| character.is_ascii_digit());
}
redirect.starts_with('>') && !redirect.starts_with(">&-")
}
fn parse_with_tree_sitter(script: &str, reject_syntax_errors: bool) -> Result<Vec<Vec<String>>, String> {
if scanner_crash_shape(script) {
return Err("shell script matches the tree-sitter-bash #337 scanner crash shape".to_string());
}
let tree = BashTree::parse(script)?;
let mut commands = Vec::new();
if reject_syntax_errors && tree.has_error() {
return Err("Shell script contains syntax errors".to_string());
}
collect_commands_from_node(tree.root(), &mut commands);
Ok(commands)
}
fn collect_commands_from_node(node: BashNode<'_>, commands: &mut Vec<Vec<String>>) {
match node.kind() {
"command" | "simple_command" => {
if let Some(cmd) = extract_command_from_node(node)
&& !cmd.is_empty()
{
commands.push(cmd);
}
}
_ => {
for child in node.children() {
collect_commands_from_node(child, commands);
}
}
}
}
fn extract_command_from_node(node: BashNode<'_>) -> Option<Vec<String>> {
let mut command = Vec::new();
if node.kind() == "pipeline" {
for child in node.children() {
if child.kind() == "command" || child.kind() == "simple_command" {
return extract_command_from_node(child);
}
}
}
for child in node.children() {
if child.kind() == "command_name" {
let trimmed = child.text().trim();
if !trimmed.is_empty() {
command.push(trimmed.to_string());
}
continue;
}
if matches!(child.kind(), "variable_assignment" | "concatenation") {
let trimmed = child.text().trim();
if !trimmed.is_empty() {
command.push(trimmed.to_string());
}
continue;
}
if matches!(
child.kind(),
"word" | "string" | "raw_string" | "ansi_c_string" | "simple_expansion" | "variable_expansion"
) {
let trimmed = child.text().trim();
if !trimmed.is_empty() {
command.push(trimmed.to_string());
}
}
}
if command.is_empty() { None } else { Some(command) }
}
fn parse_with_basic_tokenization(script: &str) -> Result<Vec<Vec<String>>, String> {
let mut commands = Vec::new();
let mut current_command = String::new();
let mut in_quotes = false;
let mut quote_char = ' ';
let mut escaped = false;
for ch in script.chars() {
if escaped {
current_command.push(ch);
escaped = false;
continue;
}
match ch {
'\\' => {
escaped = true;
}
'\'' | '"' if !in_quotes => {
in_quotes = true;
quote_char = ch;
}
c if c == quote_char && in_quotes => {
in_quotes = false;
}
'&' | '|' | ';' if !in_quotes => {
if !current_command.trim().is_empty()
&& let Ok(cmd) = tokenize_command(¤t_command)
{
commands.push(cmd);
}
current_command.clear();
}
_ => current_command.push(ch),
}
}
if !current_command.trim().is_empty()
&& let Ok(cmd) = tokenize_command(¤t_command)
{
commands.push(cmd);
}
Ok(commands)
}
fn tokenize_command(cmd: &str) -> Result<Vec<String>, String> {
shell_words::split(cmd).map_err(|err| format!("failed to tokenize command: {err}"))
}
pub fn parse_bash_lc_commands(command: &[String]) -> Option<Vec<Vec<String>>> {
if command.is_empty() {
return None;
}
let cmd_name = command[0].as_str();
let base_cmd = std::path::Path::new(cmd_name)
.file_name()
.and_then(|osstr| osstr.to_str())
.unwrap_or("");
if base_cmd != "bash" && base_cmd != "zsh" && base_cmd != "sh" {
return None;
}
for window in command.windows(2) {
if matches!(window[0].as_str(), "-lc" | "-c" | "-il" | "-ic") {
let script = &window[1];
return parse_shell_commands(script).ok();
}
}
None
}
use anyhow::{anyhow, bail};
pub(crate) fn quoted_heredoc_delim(rest: &str) -> Option<(String, usize)> {
let mut idx = 0usize;
let bytes = rest.as_bytes();
if bytes.first() == Some(&b'-') {
idx += 1;
}
while idx < bytes.len() && (bytes[idx] == b' ' || bytes[idx] == b'\t') {
idx += 1;
}
let quote = match bytes.get(idx) {
Some(b'\'') | Some(b'"') => bytes[idx],
_ => return None,
};
idx += 1;
let delim_start = idx;
while idx < bytes.len() && bytes[idx] != quote {
idx += 1;
}
if idx >= bytes.len() || idx == delim_start {
return None;
}
let delim = rest[delim_start..idx].to_string();
idx += 1; Some((delim, idx))
}
pub(crate) fn heredoc_body_skip_len(rest: &str, delim: &str) -> Option<usize> {
let bytes = rest.as_bytes();
let mut idx = 0usize;
while idx <= bytes.len() {
let line_end = rest[idx..].find('\n').map(|offset| idx + offset).unwrap_or(bytes.len());
let line = rest[idx..line_end].trim_end_matches('\r');
let next = if line_end < bytes.len() {
line_end + 1
} else {
bytes.len()
};
if line == delim {
return Some(next);
}
if line_end >= bytes.len() {
return None;
}
idx = next;
}
None
}
fn consume_bytes(
chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>,
max_bytes: usize,
fallback: usize,
) -> usize {
let mut consumed = 0usize;
let mut end = fallback;
while consumed < max_bytes
&& let Some((idx, ch)) = chars.next()
{
consumed += ch.len_utf8();
end = idx + ch.len_utf8();
}
end
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum QuoteState {
None,
Single,
Double,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SubstitutionKind {
Backtick,
DollarParen,
}
impl SubstitutionKind {
fn label(self) -> &'static str {
match self {
Self::Backtick => "backtick",
Self::DollarParen => "'$('",
}
}
}
pub(crate) fn substitution_error(kind: SubstitutionKind, byte_idx: usize) -> anyhow::Error {
anyhow!(
"Command injection pattern detected: {} command substitution at byte {byte_idx}; rewrite without dynamic expansion",
kind.label()
)
}
pub(crate) fn split_shell_segments(command: &str) -> Result<Vec<String>> {
let mut segments = Vec::new();
let mut state = QuoteState::None;
let mut escaped = false;
let mut segment_start = 0usize;
let mut pending_heredoc: Option<String> = None;
let mut chars = command.char_indices().peekable();
while let Some((idx, ch)) = chars.next() {
match state {
QuoteState::Single => {
if ch == '\'' {
state = QuoteState::None;
}
}
QuoteState::Double => {
if escaped {
escaped = false;
continue;
}
match ch {
'\\' => escaped = true,
'"' => state = QuoteState::None,
'`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
'$' if matches!(chars.peek(), Some((_, '('))) => {
return Err(substitution_error(SubstitutionKind::DollarParen, idx));
}
_ => {}
}
}
QuoteState::None => {
if escaped {
escaped = false;
if ch == ';' {
bail!("Escaped command chaining detected");
}
continue;
}
match ch {
'\\' => escaped = true,
'\'' => state = QuoteState::Single,
'"' => state = QuoteState::Double,
'<' if matches!(chars.peek(), Some((_, '<'))) => {
let _ = chars.next(); let rest: String = chars.clone().map(|(_, c)| c).collect();
if let Some((delim, token_len)) = quoted_heredoc_delim(&rest) {
let _ = consume_bytes(&mut chars, token_len, idx + ch.len_utf8());
pending_heredoc = Some(delim);
}
}
'`' => return Err(substitution_error(SubstitutionKind::Backtick, idx)),
'$' if matches!(chars.peek(), Some((_, '('))) => {
return Err(substitution_error(SubstitutionKind::DollarParen, idx));
}
';' => bail!("Unquoted command chaining detected"),
'\n' => {
if let Some(delim) = pending_heredoc.take() {
let rest: String = chars.clone().map(|(_, c)| c).collect();
if let Some(skip) = heredoc_body_skip_len(&rest, &delim) {
push_segment(command, segment_start, idx, &mut segments);
segment_start = consume_bytes(&mut chars, skip, command.len());
continue;
}
}
bail!(
"multi-line shell commands are not allowed; write the content with `apply_patch` instead of a heredoc"
);
}
'|' | '&' => {
push_segment(command, segment_start, idx, &mut segments);
segment_start = idx + ch.len_utf8();
if let Some((next_idx, next_ch)) = chars.peek().copied()
&& next_ch == ch
{
let _next = chars.next();
segment_start = next_idx + next_ch.len_utf8();
}
}
_ => {}
}
}
}
}
push_segment(command, segment_start, command.len(), &mut segments);
Ok(segments)
}
fn push_segment(command: &str, start: usize, end: usize, segments: &mut Vec<String>) {
let segment = command[start..end].trim();
if !segment.is_empty() {
segments.push(segment.to_string());
}
}
pub(crate) fn additional_dangerous_pattern(segment: &str) -> Option<&'static str> {
let segment_lower = segment.to_ascii_lowercase();
if segment_lower.starts_with(":(){:|:&};:") {
return Some(":(){:|:&};:");
}
let tokens =
shell_words::split(segment).unwrap_or_else(|_| segment.split_whitespace().map(ToString::to_string).collect());
let first = tokens.first()?;
let command_name = base_command_name(strip_wrapping_quotes(first)).to_ascii_lowercase();
match command_name.as_str() {
"rmdir" => Some("rmdir"),
"wget" => Some("wget"),
"curl" => Some("curl"),
"chmod" if tokens.iter().skip(1).any(|arg| strip_wrapping_quotes(arg).starts_with("777")) => Some("chmod 777"),
"chown"
if tokens.iter().skip(1).any(|arg| {
let arg = strip_wrapping_quotes(arg).to_ascii_lowercase();
arg == "root" || arg.starts_with("root:")
}) =>
{
Some("chown root")
}
_ => None,
}
}
fn strip_wrapping_quotes(token: &str) -> &str {
token
.strip_prefix('\'')
.and_then(|token| token.strip_suffix('\''))
.or_else(|| token.strip_prefix('"').and_then(|token| token.strip_suffix('"')))
.unwrap_or(token)
}
fn base_command_name(command: &str) -> &str {
std::path::Path::new(command)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(command)
}
#[cfg(test)]
mod crash_regression {
use super::*;
#[test]
fn parse_survives_brace_plus_astral_input() {
let parsed = parse_shell_commands("{\u{2FA8E}");
assert!(parsed.is_ok(), "parse must not fail: {parsed:?}");
let parsed = parse_shell_commands("echo {\u{2FA8E}} && echo done").expect("two commands");
assert_eq!(parsed.len(), 2, "both commands must survive: {parsed:?}");
assert!(parsed[0].contains(&"echo".to_string()), "first command tokens: {parsed:?}");
assert_eq!(parsed[1].last().map(String::as_str), Some("done"));
}
#[test]
fn strict_parse_rejects_crash_shape_instead_of_crashing() {
let result = parse_shell_commands_tree_sitter("{\u{2FA8E}");
assert!(result.is_err(), "strict path must reject, not crash: {result:?}");
}
#[test]
fn scanner_crash_shape_matches_issue_337_shape() {
assert!(scanner_crash_shape("{\u{2FA8E}"));
assert!(scanner_crash_shape("echo {a}\u{1F574}"));
assert!(scanner_crash_shape("{x} \u{1F847}"));
assert!(!scanner_crash_shape("\u{2FA8E}{"));
assert!(!scanner_crash_shape("{hello}"));
assert!(!scanner_crash_shape("{\u{CAF}\u{9bf}"));
}
}
#[cfg(test)]
mod tests;