safe-chains 0.243.1

Auto-allow safe bash commands in agentic coding tools
Documentation
//! A recursive operation reaches everything below its operand, not only the operand.
//!
//! `chmod -R 755 .` names the project root, a worktree path, yet walks into `.git/hooks` and makes
//! whatever is there executable; `cp -r other/. .` writes `other/.git` over the project's own. The
//! write-frozen metadata names (`.git`, `.jj`, `.hg`, `.sl`, `.envrc`) are frozen at any depth, so a
//! recursive write is judged as a write to the first one that exists below its operand. The folder
//! is listed at decision time, which races the shell as the glob listing does (HP-5). A tree too
//! large to list within the budget is judged as holding one. With no project root known, nothing is
//! listed and the operand is judged as before. A command that follows links while it walks is also
//! judged where each link out of the tree leads (`frozen_walk`).

use super::frozen_walk::{Skip, Walk, reach_below};
use super::regions::metadata::component_may_name;
use crate::verdict::Verdict;

/// What a walk below an operand turned up.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Reach {
    /// A frozen name that exists, or a link out of the tree, spelled as the operand joined with its
    /// path below it.
    Found(String),
    /// A tree that could not be listed in full, stood for by a frozen name directly below it.
    Unlisted(String),
}

/// What a walk cut short reaches. A walk that follows links may have missed one leading anywhere,
/// so no path stands for it; one that does not stands for a frozen name below its operand.
pub(crate) fn cut_short(base: &str, walk: Walk) -> Vec<Reach> {
    if walk.links == super::frozen_walk::WalkLinks::Follow {
        vec![Reach::Unlisted(super::locus::UNKNOWABLE_ITEM.to_string())]
    } else {
        vec![super::frozen_walk::unlisted(base)]
    }
}

/// Whether reading the folder a followed link leads to out of the tree reads a secret: the walk
/// reports such a link as a frozen name below it, which says nothing about what lies in its target.
pub(crate) fn reads_a_secret(target: &std::path::Path) -> bool {
    target.to_str().is_none_or(|path| super::read_tree_verdict(path) == Verdict::Denied)
}

impl Reach {
    pub(crate) fn path(&self) -> &str {
        match self {
            Reach::Found(p) | Reach::Unlisted(p) => p,
        }
    }
}

/// What a walk has seen. [`Sight::Found`] dominates [`Sight::Unlisted`], so one unreadable
/// directory cannot erase a frozen name listed beside it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Sight {
    Empty,
    Unlisted,
    Found,
}

/// `seen` combined with `next`. Order does not matter: a frozen name stays found.
pub(crate) fn fold_sight(seen: Sight, next: Sight) -> Sight {
    match (seen, next) {
        (Sight::Found, _) | (_, Sight::Found) => Sight::Found,
        (Sight::Unlisted, _) | (_, Sight::Unlisted) => Sight::Unlisted,
        (Sight::Empty, Sight::Empty) => Sight::Empty,
    }
}

pub(crate) fn sight_of(reached: &[Reach]) -> Sight {
    reached
        .iter()
        .fold(Sight::Empty, |seen, reach| fold_sight(seen, if matches!(reach, Reach::Found(_)) { Sight::Found } else { Sight::Unlisted }))
}

/// A walk that stops at the first frozen name may stop before other glob matches only once one
/// is found. An unlisted literal is not that: the shell can still expand onto a match.
pub(crate) fn stops_before_matches(ignore_links: bool, seen: Sight) -> bool {
    ignore_links && seen == Sight::Found
}

/// The operands of a write-role command, followed by the frozen places a recursive one reaches
/// below them. `rm -r .` removes `.git` as `rm -r .git` does, so a frozen name found below a removal
/// counts too. A removal of a plain name plants nothing to run, so an unlisted tree is let through.
/// A glob is not a plain name: when the walk cannot list what it reaches, the removal is refused.
pub(super) fn with_reached(spec: &crate::registry::types::BehaviorSpec, operands: &[&str], tokens: &[crate::parse::Token]) -> Vec<String> {
    let mut all: Vec<String> = operands.iter().map(|p| (*p).to_string()).collect();
    if spec.unbounded_flags.iter().any(|f| super::flags::behavior_flag_present(tokens, f)) {
        let removes = spec.operation == crate::engine::facet::Operation::Destroy;
        all.extend(
            operands
                .iter()
                .filter_map(|p| frozen_below(p, true).filter(|r| !removes || removal_keeps(p, r)).map(|r| r.path().to_string())),
        );
    }
    all
}

/// A removal keeps a frozen name it found. It also keeps an unlisted tree when the operand's last
/// component is a glob: the shell can expand onto a match the walk did not open. A bracket in an
/// earlier component is a directory name (`plain[ok]/f`), which a removal still lets through.
fn removal_keeps(operand: &str, reach: &Reach) -> bool {
    if matches!(reach, Reach::Found(_)) {
        return true;
    }
    let last = operand.trim_end_matches('/').rsplit('/').next().unwrap_or(operand);
    last.contains(['*', '?', '['])
}

/// Where a recursive copy of `source` into `dest` writes what it reaches below `source`:
/// `cp -r other/. .` writes `other/.git` as `./.git`. A name that cannot be re-rooted (below a glob
/// source) is returned where it was found, which is frozen itself. A source that is itself a frozen
/// folder, named without a trailing slash, lands under its own name: `rsync -a sub/.git d/` writes
/// `d/.git`.
pub(crate) fn landed(source: &str, dest: &str, follow: bool) -> Vec<String> {
    let dest = dest.trim_end_matches('/');
    let own = source.rsplit('/').next().filter(|name| !source.ends_with('/') && is_frozen(name));
    if let Some(name) = own {
        return vec![format!("{dest}/{name}/f")];
    }
    let walk = if follow { Walk::follow() } else { Walk::plain(true) };
    reach_below(source, walk)
        .iter()
        .map(|reached| match reached.path().strip_prefix(source.trim_end_matches('/')) {
            Some(below) if below.starts_with('/') => format!("{dest}{below}"),
            _ => reached.path().to_string(),
        })
        .collect()
}

/// The places a copy that follows links (`cp -RL`, `rsync -L`) reads through the links below
/// `source` that lead out of it.
pub(crate) fn read_through(source: &str) -> Vec<String> {
    reach_below(source, Walk::follow()).iter().map(|r| r.path().to_string()).collect()
}

/// Whether a tree copy of `source` into the last of `operands` (`rsync -a`, `ditto`) writes a
/// frozen name, or with `follow` reads where a link below it leads.
pub(crate) fn lands_frozen(source: &str, operands: &[&str], follow: bool) -> bool {
    let Some(dest) = operands.last() else { return false };
    let denied = |at: &String| super::write_target_verdict(at) == Verdict::Denied;
    landed(source, dest, follow).iter().any(denied)
        || (follow && read_through(source).iter().any(|at| super::read_tree_verdict(at) == Verdict::Denied))
}

/// Whether a copy's operand `p` reaches a place it may not: as a tree source (`tree`), by landing a
/// frozen name or reading through a followed link; as the destination (`dest`), by writing through
/// a link it keeps there.
pub(crate) fn copy_reaches(p: &str, operands: &[&str], links: super::link_mode::Links, (tree, dest): (bool, bool)) -> bool {
    (tree && lands_frozen(p, operands, links.follow))
        || (dest && links.dest == super::link_mode::DestLinks::WrittenThrough && writes_through(p))
}

/// Whether a copy that keeps the links to folders in its destination (`rsync -K`) writes through one
/// to a place it may not write.
pub(crate) fn writes_through(dest: &str) -> bool {
    reach_below(dest, Walk::follow())
        .iter()
        .any(|r| super::write_target_verdict(r.path()) == Verdict::Denied)
}

/// The verdict of a traversal's inner command (`find -exec`, `fd -x`, `find -delete`) rooted at
/// `base`, `judge` being handed the path each item stands for. When the traversal lists hidden
/// entries and frozen metadata lies below `base`, the command must also pass on a path inside it:
/// `find . -exec chmod +x {} +` reaches `.git/hooks`. A read passes there as anywhere in the
/// project, so only a refusal is taken from that second judgement.
pub(crate) fn judged_over(base: &str, walk: Walk, judge: impl Fn(&str) -> Verdict) -> Verdict {
    let plain = super::locus::traversal_item(base);
    let verdict = judge(&plain);
    if verdict == Verdict::Denied || plain == super::locus::UNKNOWABLE_ITEM {
        return verdict;
    }
    if reach_below(base, walk).iter().any(|reach| judge(reach.path()) == Verdict::Denied) { Verdict::Denied } else { verdict }
}

/// The path a pipeline stage's producer (`find … | xargs chmod +x`) stands for: inside the first
/// frozen name below `base` when it lists hidden entries (`find`, `fd -H`), else the plain item.
/// When it reaches several places (links out of the tree), no one path stands for them all.
pub(crate) fn stage_item(name: &str, base: &str, args: &[&str]) -> String {
    let plain = super::locus::traversal_item(base);
    if plain == super::locus::UNKNOWABLE_ITEM {
        return plain;
    }
    let find = name == "find";
    let skip = if find { crate::handlers::coreutils::find_skip::skip_of(args) } else { Skip::default() };
    let hidden = find || fd_lists_hidden(args);
    let follow = if find { find_follows(args) } else { fd_follows(args) };
    let walk = Walk { skip: &skip, ..Walk::items(hidden, follow) };
    match reach_below(base, walk).as_slice() {
        [] => plain,
        [one] => one.path().to_string(),
        _ => super::locus::UNKNOWABLE_ITEM.to_string(),
    }
}

/// Whether an `fd` command line lists hidden entries, which fd skips unless told otherwise.
pub(crate) fn fd_lists_hidden(args: &[&str]) -> bool {
    args.iter().any(|a| match a.strip_prefix("--") {
        Some(long) => matches!(long, "hidden" | "unrestricted"),
        None => a.starts_with('-') && a[1..].contains(['H', 'u']),
    })
}

/// Whether an `fd` command line follows links while it walks (`-L`, `--follow`).
pub(crate) fn fd_follows(args: &[&str]) -> bool {
    args.iter().any(|a| match a.strip_prefix("--") {
        Some(long) => long.len() >= 3 && "follow".starts_with(long),
        None => a.starts_with('-') && a[1..].contains('L'),
    })
}

/// Whether a `find` command line follows links: `-L` everywhere, `-H` for its operands, or the
/// `-follow` primary. Looked for in every word, so an inner command's own flag counts too.
pub(crate) fn find_follows(args: &[&str]) -> bool {
    args.iter().any(|a| matches!(*a, "-L" | "-H" | "-follow"))
}

/// The first write-frozen name under the operand `base`, links below it not entered. `None` when
/// nothing frozen lies below, or when `base` cannot be placed on disk.
pub(crate) fn frozen_below(base: &str, hidden: bool) -> Option<Reach> {
    // A found name wins over an unlisted sibling, so a readable match is what a removal sees.
    let reached = reach_below(base, Walk::plain(hidden));
    let found = reached.iter().position(|r| matches!(r, Reach::Found(_))).unwrap_or(0);
    reached.into_iter().nth(found)
}

/// Whether `name` could open a write-frozen folder, spelled in any case or with a character outside
/// ASCII that the file system may fold to one.
pub(crate) fn is_frozen(name: &str) -> bool {
    let fold = cfg!(target_os = "macos");
    super::regions::metadata::frozen_names().iter().any(|n| component_may_name(name, n, fold))
}

/// Whether `name` could open the folder a package manager installs into (`node_modules`), spelled as
/// `is_frozen` reads a frozen name.
pub(crate) fn is_packaged(name: &str) -> bool {
    component_may_name(name, "node_modules", cfg!(target_os = "macos"))
}

/// Whether running the file or folder `path` runs code from installed packages or a frozen folder,
/// once the folder a `cd` moved to is joined on. No commit of the project's own shows that code. A
/// frozen folder named last is the folder itself (`GIT_DIR=.git`), which its tool reads as its own.
pub(crate) fn runs_unreviewed_code(path: &str) -> bool {
    let placed = crate::pathctx::resolve(path);
    let (dirs, last) = placed.rsplit_once('/').unwrap_or(("", &placed));
    is_packaged(last) || dirs.split('/').any(|part| is_frozen(part) || is_packaged(part))
}

/// Whether a tool that runs the code of the folder `path` names would run files from installed
/// packages or a frozen folder: the folder itself counts, since the tool reads the files inside it.
pub(crate) fn is_unreviewed_folder(path: &str) -> bool {
    crate::pathctx::resolve(path).split('/').any(|part| is_frozen(part) || is_packaged(part))
}

#[cfg(test)]
#[path = "frozen_reach_tests.rs"]
mod tests;