safe-chains 0.243.0

Auto-allow safe bash commands in agentic coding tools
Documentation
//! The commands that read an argument as arithmetic, or that set or test a variable by a name that
//! may carry a subscript.

use super::{
    INERT, INTEGER, NUMERIC, UNKNOWN, arithmetic_word_verdict, assigned_verdict, bracketed, expression_verdict, holds_a_number,
    holds_an_expression, is_free, is_integer, is_numeric, read_text, refuse_if, value_verdict,
};
use crate::cst::{SimpleCmd, Word, WordPart};
use crate::parse::Token;
use crate::pathctx::item_shape::{Binding, binding};
use crate::verdict::Verdict;

fn numeric_verdict(cmd: &SimpleCmd, name: &str, args: &[String]) -> Verdict {
    let declares = matches!(name, "declare" | "typeset" | "local" | "export" | "readonly")
        && args.iter().any(|w| w.starts_with(['-', '+']) && w.contains(['i', 'E', 'F']));
    let env = cmd.env.iter().map(|(n, value)| assigned_verdict(n, value)).fold(INERT, Verdict::combine);
    if declares {
        let operands = args.iter().filter(|w| !w.starts_with(['-', '+']));
        let refused: Vec<bool> = operands
            .map(|w| w.split_once('=').map_or((w.as_str(), None), |(n, value)| (n, Some(value))))
            .map(|(n, value)| {
                // zsh evaluates the value a name already holds when it is declared without one, and
                // `+=` adds to it.
                let reads_old = value.is_none() || n.ends_with('+');
                let n = n.trim_end_matches('+');
                let refused = is_free(n) || !is_integer(value.unwrap_or_default()) || (reads_old && holds_an_expression(n));
                NUMERIC.with(|numeric| numeric.borrow_mut().push(n.to_string()));
                if !refused {
                    INTEGER.with(|i| i.borrow_mut().push(n.to_string()));
                }
                refused
            })
            .collect();
        return env.combine(refuse_if(refused.contains(&true)));
    }
    let set = match super::super::opaque::named(cmd) {
        Some(names) => names.iter().map(|n| declared_verdict(name, n, args)).fold(INERT, Verdict::combine),
        // Which names are set is not known: any numeric one could take an expression.
        None => {
            let names_numeric = args.iter().any(|w| is_numeric(w.split('=').next().unwrap_or_default()));
            value_verdict("*", "*").combine(refuse_if(names_numeric || NUMERIC.with(|n| !n.borrow().is_empty())))
        }
    };
    env.combine(set)
}

/// One name a setter sets: `local n=0` gives it a number; `read n`, `local n=$x` and `n+=…` may give
/// it anything.
fn declared_verdict(command: &str, name: &str, args: &[String]) -> Verdict {
    let assigns = matches!(command, "declare" | "typeset" | "local" | "export" | "readonly");
    let mut values = args
        .iter()
        .filter(|w| !w.starts_with(['-', '+']) && w.split('=').next().unwrap_or_default().trim_end_matches('+') == name)
        .map(|w| w.strip_prefix(name).and_then(|rest| rest.strip_prefix('=')))
        .peekable();
    let numbers = values.peek().is_some() && values.all(|v| v.is_some_and(|v| !v.is_empty() && is_integer(v)));
    if assigns && numbers {
        INTEGER.with(|i| i.borrow_mut().push(name.to_string()));
        return INERT;
    }
    value_verdict(name, "*")
}

/// The commands whose arguments are arithmetic, assignments through a subscript (`a[x]=1`), values
/// given to a numeric variable, and the names a command sets or tests.
pub(crate) fn command_verdict(cmd: &SimpleCmd) -> Verdict {
    let subscripts = cmd.env.iter().filter_map(|(name, _)| name.split_once('[')).map(|(_, s)| expression_verdict(s));
    let words: Vec<String> = cmd.words.iter().map(Word::eval).collect();
    let start = words.iter().take_while(|w| matches!(command_name(w).as_str(), "builtin" | "command")).count();
    let descriptor = descriptor_verdict(cmd);
    let Some(name) = words.get(start).map(|w| command_name(w)) else {
        return subscripts.fold(numeric_verdict(cmd, "", &[]).combine(descriptor), Verdict::combine);
    };
    let args = &words[start + 1..];
    let arg_words = &cmd.words[start + 1..];
    let numeric = numeric_verdict(cmd, &name, args);
    let fanned = || arg_words.iter().map(fans_out).collect::<Vec<bool>>();
    let arithmetic: Vec<usize> = match name.as_str() {
        "shift" | "return" | "break" | "continue" => (0..args.len()).collect(),
        "printf" => formatted(args, &fanned()),
        "print" => print_formatted(args, &fanned()),
        "read" => option_values(args, &['t', 'k', 'u']),
        _ => Vec::new(),
    };
    let named: Vec<usize> = match name.as_str() {
        "read" | "getopts" | "unset" | "mapfile" | "readarray" => (0..args.len()).collect(),
        // A word braces or a tilde fan out may be `-v` and the name it tests (`{-v,'a[x]'}`), and a
        // glob may match files named `-v` and `a[HOME=1]` (see [`may_glob_a_name`]). A word the shell
        // builds (`$o`, `$(echo -v)`) may be `-v`, so the word after it may be a name.
        "test" | "[" if arg_words.iter().any(|w| fans_out(w) && !globbed(w)) => (0..args.len()).collect(),
        "test" | "[" => {
            let globs = arg_words.iter().enumerate().filter(|(_, w)| may_glob_a_name(w)).map(|(i, _)| i);
            let after_built = args.iter().enumerate().filter(|(_, w)| built(w)).map(|(i, _)| i + 1).filter(|&i| i < args.len());
            tested_names(args).into_iter().chain(globs).chain(after_built).collect()
        }
        _ => Vec::new(),
    };
    let arithmetic = arithmetic.into_iter().map(|i| arithmetic_word_verdict(&arg_words[i]));
    // Outside `[[ ]]` a name is globbed, and can match a file named `a[HOME=1]`.
    let named = named.into_iter().map(|i| name_verdict(&arg_words[i]).combine(refuse_if(globbed(&arg_words[i]))));
    arithmetic.chain(named).chain(subscripts).fold(numeric.combine(descriptor), Verdict::combine)
}

/// `echo hi {HOME}>/dev/null` opens a descriptor and assigns its number to HOME, in bash and zsh.
/// The parser keeps the `{HOME}` as a word, so any such word beside a redirect counts.
fn descriptor_verdict(cmd: &SimpleCmd) -> Verdict {
    let braced_name = |w: &Word| {
        let text = w.eval();
        text.strip_prefix('{')
            .and_then(|t| t.strip_suffix('}'))
            .is_some_and(|name| !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
    };
    refuse_if(!cmd.redirs.is_empty() && cmd.words.iter().any(braced_name))
}

/// A name a command sets or tests: `read 'a[HOME=1]'` and `test -v 'a[HOME=1]'` evaluate the
/// subscript. A name held in a variable or a command's output could carry any subscript, and a
/// brace expansion (`read {x,'a[HOME=1]'}`) may give several names, each read.
fn name_verdict(word: &Word) -> Verdict {
    let text = word.eval();
    let (read, v) = read_text(word);
    let names = word.expand();
    let built = built(&text) || names.iter().any(|name| built(name));
    names
        .iter()
        .map(|name| subscript_verdict(name))
        .fold(v.combine(refuse_if(built)), Verdict::combine)
        .combine(subscript_verdict(&read))
}

/// A word the shell turns into a number of words it does not show: a brace expansion (`%{d,s}`,
/// `{-v,x}`), an unquoted glob, which can match a file named `%d`, or a tilde, which can give a
/// directory whose name holds one (`~+`, `~-`, `~1`; `~/x` is only the home directory). An unquoted expansion or substitution is split into
/// words too, so `$x` may be `-v a[HOME=1]`.
fn fans_out(word: &Word) -> bool {
    let tilde = matches!(word.0.first(), Some(WordPart::Lit(s)) if s.strip_prefix('~').is_some_and(|rest| rest.starts_with(['+', '-']) || rest.starts_with(|c: char| c.is_ascii_digit())));
    let split = literal_runs(word).iter().any(|s| literal(s).any(|(at, c)| c == '$' && !one_word(&s[at + 1..])))
        || word.0.iter().any(|part| match part {
            WordPart::CmdSub(_) | WordPart::Backtick(_) => read_text(&Word(vec![part.clone()])).0.contains(UNKNOWN),
            _ => false,
        });
    globbed(word) || tilde || split || word.expand() != [word.eval()]
}

/// A glob that may match `-v` or a subscripted name. One under a directory (`src/*`) gives paths
/// (a bracket could hold the `/`, so one with a bracket does not count),
/// and one with a `.` after its last glob character (`*.txt`) gives names ending in that text,
/// never `-v` nor a name ending in `]`.
fn may_glob_a_name(word: &Word) -> bool {
    let text = word.eval();
    let tail = text.rsplit(['*', '?', '[', ']']).next().unwrap_or_default();
    let under_a_directory = text.contains('/') && !text.contains('[');
    globbed(word) && !under_a_directory && !tail.contains('.')
}

/// Whether the expansion after a `$` gives one word: a count (`$#`, `${#x}`), a name holding a
/// number, or a name whose known value holds nothing the default `IFS` or a glob acts on.
fn one_word(after: &str) -> bool {
    let braced = after.strip_prefix('{').map(|body| bracketed(body, '{', '}'));
    let body = braced.unwrap_or(after);
    let end = body.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(body.len());
    let name = &body[..end];
    if name.is_empty() {
        return body.starts_with(['#', '?', '$', '!']) && braced.is_none_or(|b| b.len() == 1 || b.starts_with('#'));
    }
    if braced.is_some_and(|b| b != name) {
        return false;
    }
    let known = match binding(name) {
        Binding::Value(value) => {
            value != crate::cst::scope_budget::UNCERTAIN_VALUE
                && !value.is_empty()
                && !value.contains([' ', '\t', '\n', '*', '?', '['])
                && matches!(binding("IFS"), Binding::Unbound)
        }
        _ => false,
    };
    // Asked only once the name is known to hold one: asking records the name, and a line that
    // gives it something else elsewhere is then refused whole.
    known || (holds_a_number(name) && !holds_an_expression(name))
}

/// The word's unquoted text, adjacent literal parts joined: the parser keeps `$$` as two parts.
fn literal_runs(word: &Word) -> Vec<String> {
    fn text(part: &WordPart) -> Option<&str> {
        match part {
            WordPart::Lit(s) => Some(s),
            _ => None,
        }
    }
    word.0
        .chunk_by(|a, b| text(a).is_some() && text(b).is_some())
        .filter_map(|run| run.iter().map(text).collect::<Option<String>>())
        .collect()
}

/// Unquoted text's characters with their offsets, less the special parameter a `$` names: the
/// `?` of `$?` is not a glob, and the second `$` of `$$` starts no expansion of its own.
fn literal(s: &str) -> impl Iterator<Item = (usize, char)> + '_ {
    s.char_indices()
        .scan(false, |after_dollar, (at, c)| {
            let named = *after_dollar && matches!(c, '$' | '?' | '*' | '#' | '!' | '@' | '-');
            *after_dollar = c == '$' && !named;
            Some((at, c, named))
        })
        .filter(|&(_, _, named)| !named)
        .map(|(at, c, _)| (at, c))
}

fn globbed(word: &Word) -> bool {
    literal_runs(word).iter().any(|s| literal(s).any(|(_, c)| matches!(c, '*' | '?' | '[')))
}

/// Text the shell finishes building when it runs: an expansion, or a substitution's output.
fn built(text: &str) -> bool {
    text.contains('$') || text.contains("__SAFE_CHAINS_")
}

fn subscript_verdict(text: &str) -> Verdict {
    let name = text.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(text.len());
    text[name..]
        .strip_prefix('[')
        .filter(|_| name > 0)
        .map_or(INERT, |s| expression_verdict(bracketed(s, '[', ']')))
}

/// The operands of `-v`, which names a variable to test.
fn tested_names(args: &[String]) -> Vec<usize> {
    args.iter()
        .enumerate()
        .filter(|(_, w)| *w == "-v")
        .map(|(i, _)| i + 1)
        .filter(|&i| i < args.len())
        .collect()
}

/// The arguments a format string reads as numbers: every one after the format, unless the format
/// is known to hold no numeric conversion. An option word the shell builds may be `-v` or the
/// format itself, so every word after it counts. A word that fans out (see [`fans_out`]) up to the
/// format may hold an option, the format and arguments at once, so every word counts; one after the
/// format shifts which argument fills which slot, so every argument counts.
fn formatted(args: &[String], fanned: &[bool]) -> Vec<usize> {
    let mut i = 0;
    while let Some(arg) = args.get(i).filter(|w| w.starts_with('-') && w.len() > 1) {
        if built(arg) {
            return (i + 1..args.len()).collect();
        }
        i += if arg == "-v" { 2 } else { 1 };
        if arg == "--" {
            break;
        }
    }
    if fanned[..args.len().min(i + 1)].contains(&true) {
        return (0..args.len()).collect();
    }
    let Some(format) = args.get(i) else { return Vec::new() };
    let slots = numeric_slots(format);
    if !slots.contains(&true) {
        return Vec::new();
    }
    // `fanned[i]`, the format, was looked at above.
    if fanned[i..].contains(&true) {
        return (i + 1..args.len()).collect();
    }
    // The format is reused until the arguments run out, so argument k fills slot k mod its length.
    (i + 1..args.len()).filter(|k| slots[(k - i - 1) % slots.len()]).collect()
}

/// zsh's `print -f format`: the format is the option's value, attached (`-f%d`) or the next word,
/// the last `-f` wins and options may follow it. So every format any `-f` could take is read, and
/// when one reads a number every argument after the first `-f` counts. A word the shell builds may
/// be `-f` or its format, so every argument after it counts too, and a word that fans out may be
/// all of them, so every word counts.
fn print_formatted(args: &[String], fanned: &[bool]) -> Vec<usize> {
    if fanned.contains(&true) {
        return (0..args.len()).collect();
    }
    let mut first = None;
    let mut numeric = false;
    for (i, word) in args.iter().enumerate() {
        if built(word) {
            first.get_or_insert(i);
            numeric = true;
            continue;
        }
        let Some(cluster) = word.strip_prefix('-') else { continue };
        let Some((_, glued)) = cluster.split_once('f') else { continue };
        let format = if glued.is_empty() { args.get(i + 1).map(String::as_str) } else { Some(glued) };
        first.get_or_insert(i);
        numeric |= format.is_some_and(|format| numeric_slots(format).contains(&true));
    }
    match first {
        Some(first) if numeric => (first + 1..args.len()).collect(),
        _ => Vec::new(),
    }
}

/// Whether each argument the format takes is read as a number, in order: a `*` width or precision
/// takes one (`printf '%*s' 5 x`), then the conversion. A `%1$d` picks its argument by number, and
/// a format built when the shell runs (`"%s$(cat f)"`) may hold any conversion, so every one counts.
fn numeric_slots(format: &str) -> Vec<bool> {
    if built(format) {
        return vec![true];
    }
    let mut slots = Vec::new();
    for spec in format.replace("%%", "").split('%').skip(1) {
        let width = spec.trim_start_matches(|c: char| "-+ #0123456789.*'".contains(c));
        slots.extend(spec[..spec.len() - width.len()].matches('*').map(|_| true));
        // A length (`%ld`, `%hd`, `%Lf`) still ends in the conversion that reads a number.
        let conversion = width.trim_start_matches(|c: char| "hlLqjzt".contains(c));
        // A `%` ending the format may be zsh's numeric glob, `%<1-9>d`, which the parser reads
        // as a redirect, leaving the `%` and any flags, width or length behind (`%5<->d`).
        slots.push(conversion.is_empty() || conversion.starts_with(|c: char| "diouxXeEfFgGaAc".contains(c)));
    }
    slots
}

/// The values of the options in `letters`: `-t 5` and `-t5` alike.
fn option_values(args: &[String], letters: &[char]) -> Vec<usize> {
    let mut out = Vec::new();
    for (i, arg) in args.iter().enumerate() {
        let Some(cluster) = arg.strip_prefix('-') else { continue };
        if let Some(at) = cluster.find(letters) {
            if at + 1 == cluster.len() {
                out.extend(Some(i + 1).filter(|&next| next < args.len()));
            } else {
                out.push(i);
            }
        }
    }
    out
}

/// `[[ a -eq b ]]` evaluates both sides as arithmetic, in bash and zsh alike, and `-v` names a
/// variable whose subscript is arithmetic.
pub(crate) fn double_bracket_verdict(words: &[Word]) -> Verdict {
    let text: Vec<String> = words.iter().map(Word::eval).collect();
    let mut v = super::super::check::words_sub_verdict(words);
    for (i, w) in text.iter().enumerate() {
        if matches!(w.as_str(), "-eq" | "-ne" | "-lt" | "-le" | "-gt" | "-ge") {
            let sides = i.checked_sub(1).and_then(|l| words.get(l)).into_iter().chain(words.get(i + 1));
            v = sides.map(arithmetic_word_verdict).fold(v, Verdict::combine);
        }
    }
    tested_names(&text).into_iter().map(|i| name_verdict(&words[i])).fold(v, Verdict::combine)
}

fn command_name(word: &str) -> String {
    Token::from_raw(word.to_string()).command_name().to_string()
}