safe-chains 0.243.0

Auto-allow safe bash commands in agentic coding tools
Documentation
//! The functions a line defines, so a later call resolves to its body, and the bounds on resolving one.

use super::classify_budget::charge_classify_work;
use super::{Script, SimpleCmd};
use crate::verdict::{SafetyLevel, Verdict};

thread_local! {
    /// Functions DEFINED so far in the current classification, so a later call resolves to its body
    /// (and a definition SHADOWS a same-named built-in — `ls(){ rm -rf /; }; ls` runs rm). Owned
    /// clones (small); a thread-local can't borrow the CST. Latest definition wins.
    static FUNCTIONS: std::cell::RefCell<Vec<(String, Script)>> =
        const { std::cell::RefCell::new(Vec::new()) };
    /// Function names whose CURRENT body we cannot attribute — redefined inside a compound, where
    /// the shell keeps the new body but we cannot say which one ran. A call to one denies, rather
    /// than resolving to a stale definition or to the command the name shadowed.
    static POISONED_FUNCS: std::cell::RefCell<Vec<String>> =
        const { std::cell::RefCell::new(Vec::new()) };
    /// Names currently being resolved — bounds recursion (direct AND mutual) and total call depth,
    /// so `f(){ f; }` or a deep chain can't blow the stack; hitting the bound denies (fail-closed).
    static RESOLVING: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
    /// Every name a definition in this evaluation bound, kept after its scope ends: a loop's next
    /// pass calls a function defined further down its body.
    static DEFINED: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}

const MAX_FUNC_DEPTH: usize = 32;

pub(super) struct FuncScope;
impl Drop for FuncScope {
    fn drop(&mut self) {
        FUNCTIONS.with(|f| {
            f.borrow_mut().pop();
        });
    }
}

pub(super) fn define_function(name: String, body: Script) -> FuncScope {
    DEFINED.with(|d| d.borrow_mut().push(name.clone()));
    FUNCTIONS.with(|f| f.borrow_mut().push((name, body)));
    FuncScope
}

/// Whether `name` may have been redefined with a body we cannot attribute.
pub(super) fn body_unknown(name: &str) -> bool {
    POISONED_FUNCS.with(|p| p.borrow().iter().any(|n| n == name))
}

pub(super) fn lookup_function(name: &str) -> Option<Script> {
    if body_unknown(name) {
        return None;
    }
    FUNCTIONS.with(|f| f.borrow().iter().rev().find(|(n, _)| n == name).map(|(_, b)| b.clone()))
}

/// Called as an outermost scope walk starts: what one command redefined is no fact about the next.
/// Never from a nested walk, whose caller still relies on the marks (`bash -c` inside a command).
pub(super) fn forget_poisoned_functions() {
    POISONED_FUNCS.with(|p| p.borrow_mut().clear());
    DEFINED.with(|d| d.borrow_mut().clear());
}

/// Mark `name`'s body unknown for the rest of this evaluation. Not scoped by a guard: the shell's
/// redefinition is not scoped either, and the outermost scope walk clears the list.
pub(super) fn poison_function(name: String) {
    POISONED_FUNCS.with(|p| p.borrow_mut().push(name));
}

struct ResolveScope;
impl Drop for ResolveScope {
    fn drop(&mut self) {
        RESOLVING.with(|r| {
            r.borrow_mut().pop();
        });
    }
}

/// Begin resolving a call to `name`, unless it recurses, exceeds the depth cap, or exhausts the
/// per-invocation classification budget — then return `None` and the caller treats it as an ordinary
/// (unknown) command, which denies. The budget is what stops exponential FAN-OUT (`f(){ f2; f2; };
/// f2(){ f3; f3; }; …`): the depth cap alone bounds a linear chain, but branching multiplies, so each
/// resolution charges the shared `CLASSIFY_WORK` counter that also caps delegating-handler recursion.
fn begin_resolving(name: &str) -> Option<ResolveScope> {
    if !charge_classify_work(1) {
        return None;
    }
    RESOLVING.with(|r| {
        let mut stack = r.borrow_mut();
        if stack.len() >= MAX_FUNC_DEPTH || stack.iter().any(|n| n == name) {
            None
        } else {
            stack.push(name.to_string());
            Some(ResolveScope)
        }
    })
}

/// The verdict of a call to `name` when a definition rebinds it, `None` when none does.
///
/// The body is judged with $1..$N bound to the call's arguments (certain literals; uncertain →
/// unpinnable). The shadow is UNCONDITIONAL: a body we cannot attribute, or a resolution blocked by
/// recursion, depth or budget, denies and never falls through to the real command. Otherwise
/// `…512 calls…; ls(){ rm -rf /; }; ls` would exhaust the budget and then run the real `ls`.
///
/// A call to `alias` that defines one denies too: an alias rebinds a name for every later line,
/// and zsh's global ones (`alias -g`) any word at all, which no call here can see. Listing does not.
/// So does a `hash` that binds a name to a path (`hash -p /bin/rm ls`, zsh's `hash ls=/bin/rm`):
/// the shell then runs that file for the name, ahead of PATH.
pub(super) fn call_verdict(cmd: &SimpleCmd, name: &str) -> Option<Verdict> {
    if body_unknown(name) || rebinds_a_name(cmd, name) {
        return Some(Verdict::Denied);
    }
    let body = lookup_function(name)?;
    let Some(_resolving) = begin_resolving(name) else {
        return Some(Verdict::Denied);
    };
    // A word that may split or match files moves every later argument to a position not known.
    let mut shifted = false;
    let _args: Vec<crate::pathctx::VarGuard> = cmd.words[1..]
        .iter()
        .enumerate()
        .map(|(i, w)| {
            shifted |= may_split(w);
            let value = if shifted { super::scope_budget::UNCERTAIN_VALUE.to_string() } else { super::check::certain_value(w) };
            crate::pathctx::enter_var((i + 1).to_string(), value)
        })
        .collect();
    Some(super::netargs::with_args(cmd, || super::check::script_verdict(&body)))
}

/// Whether a definition so far rebinds `name`, its body known or not.
pub(crate) fn names_a_function(name: &str) -> bool {
    body_unknown(name) || FUNCTIONS.with(|f| f.borrow().iter().any(|(n, _)| n == name))
}

/// Defining a function has NO effect, so a definition is Inert regardless of its body, which is
/// judged only when the function is CALLED (`call_verdict`). A name the shell itself calls is the
/// exception: its definition is judged as a call, since nothing else in the line need name it.
pub(super) fn definition_verdict(name: &str, body: &Script) -> Verdict {
    if runs_unnamed(name) { super::check::script_verdict(body) } else { Verdict::Allowed(SafetyLevel::Inert) }
}

/// A function the shell runs by its name alone: zsh's signal and exit traps (`TRAPEXIT`,
/// `TRAPZERR`, `TRAPDEBUG` after every command), its hook functions, and both shells'
/// command-not-found handlers.
fn runs_unnamed(name: &str) -> bool {
    name.starts_with("TRAP")
        || matches!(
            name,
            "command_not_found_handler"
                | "command_not_found_handle"
                | "chpwd"
                | "precmd"
                | "preexec"
                | "periodic"
                | "zshexit"
                | "zshaddhistory"
                | "zsh_directory_name"
        )
}

/// Whether an `alias` or `hash` call binds a name: an argument holding `=`, one we cannot read, or
/// `hash`'s `-p` in any cluster of its short flags.
fn rebinds_a_name(cmd: &SimpleCmd, name: &str) -> bool {
    let values = || cmd.words[1..].iter().map(super::check::certain_value);
    let binds = || values().any(|v| v == super::scope_budget::UNCERTAIN_VALUE || v.contains('='));
    match name {
        "alias" => binds(),
        "hash" => binds() || values().any(|v| v.starts_with('-') && !v.starts_with("--") && v.contains('p')),
        _ => false,
    }
}

/// Whether `word` may become other than one argument: a brace list, a glob (zsh's extended
/// operators included), or anything unquoted that expands, which splits in bash and vanishes when
/// empty in zsh. `"$@"` and `"${a[@]}"` give a word per element even when quoted. A variable
/// whose value is known, not empty, and holds nothing the default `IFS` or a glob acts on stays
/// one word.
fn may_split(word: &super::Word) -> bool {
    use super::WordPart;
    use crate::pathctx::item_shape::{Binding, binding};
    let substitutes =
        |part: &WordPart| matches!(part, WordPart::CmdSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) | WordPart::ProcSub(_));
    let one_known_word = || {
        let value = super::check::certain_value(word);
        !word.0.iter().any(substitutes)
            && value != super::scope_budget::UNCERTAIN_VALUE
            && !value.is_empty()
            && !value.contains([' ', '\t', '\n', '*', '?', '[', '^', '#', '<', '~', '@'])
            && matches!(binding("IFS"), Binding::Unbound)
    };
    word.expand().len() != 1
        || (!one_known_word()
            && word.0.iter().any(|part| match part {
                WordPart::Lit(s) => s.contains(['$', '*', '?', '[', '^', '#', '<']),
                WordPart::DQuote(inner) => inner.eval().contains('@'),
                part if substitutes(part) => true,
                _ => false,
            }))
}

/// Whether any definition in this evaluation bound `name`, in scope now or not.
pub(crate) fn ever_defined(name: &str) -> bool {
    DEFINED.with(|d| d.borrow().iter().any(|n| n == name)) || names_a_function(name)
}