safe-chains 0.243.6

Auto-allow safe bash commands in agentic coding tools
Documentation
macro_rules! handler_module {
    ($($sub:ident),+ $(,)?) => {
        $(mod $sub;)+

        pub(crate) fn dispatch(cmd: &str, tokens: &[crate::parse::Token]) -> Option<crate::verdict::Verdict> {
            None$(.or_else(|| $sub::dispatch(cmd, tokens)))+
        }

        pub fn command_docs() -> Vec<crate::docs::CommandDoc> {
            let mut docs = Vec::new();
            $(docs.extend($sub::command_docs());)+
            docs
        }

        #[cfg(test)]
        pub(super) fn full_registry() -> Vec<&'static super::CommandEntry> {
            let mut v = Vec::new();
            $(v.extend($sub::REGISTRY);)+
            v
        }
    };
}

pub mod android;
mod cargo_runs_this;
pub mod coreutils;
pub mod df;
pub(crate) mod direct_script;
mod env_print;
pub mod fd;
mod followed_read;
pub mod forges;
pub mod fuzzy;
pub mod hadolint;
pub mod interpreter;
pub mod jvm;
pub mod magick;
mod make_dirs;
mod make_text;
mod mise_global;
pub mod network;
pub mod node;
pub mod pandoc;
pub(crate) mod pattern_flags;
pub mod perl;
mod perl_load;
mod perl_regex;
pub mod php;
pub mod printf;
pub mod ruby;
pub mod safe_chains;
pub mod shell;
pub(crate) mod shell_text;
pub mod shellcheck;
#[cfg(test)]
mod signal_tests;
pub mod system;
pub mod tilt;
pub mod vcs;
pub mod wrappers;

use std::collections::HashMap;

use crate::parse::Token;
use crate::verdict::Verdict;

type HandlerFn = fn(&[Token]) -> Verdict;

pub fn custom_cmd_handlers() -> HashMap<&'static str, HandlerFn> {
    HashMap::from([
        ("gh", forges::gh::is_safe_gh as HandlerFn),
        ("bash", shell::is_safe_shell as HandlerFn),
        ("glab", forges::glab::is_safe_glab as HandlerFn),
        ("interpreter", interpreter::check_interpreter as HandlerFn),
        ("magick", magick::is_safe_magick as HandlerFn),
        ("pandoc", pandoc::check_pandoc as HandlerFn),
        ("shellcheck", shellcheck::check_shellcheck as HandlerFn),
        ("hadolint", hadolint::check_hadolint as HandlerFn),
        ("awk", coreutils::awk::check_awk as HandlerFn),
        ("curl", network::is_safe_curl as HandlerFn),
        ("df", df::check_df as HandlerFn),
        ("fd", fd::check_fd as HandlerFn),
        ("php", php::is_safe_php as HandlerFn),
        ("open", system::open::check_open as HandlerFn),
        ("screen", system::screen::check_screen as HandlerFn),
        ("printf", printf::check_printf as HandlerFn),
        ("ssh", system::ssh::check_ssh as HandlerFn),
        ("sysctl", system::sysctl::is_safe_sysctl as HandlerFn),
        ("safe_chains", safe_chains::check_safe_chains as HandlerFn),
        ("tilt", tilt::check_tilt as HandlerFn),
    ])
}

pub fn custom_sub_handlers() -> HashMap<&'static str, HandlerFn> {
    HashMap::from([
        ("bun_x", node::bun::check_bun_x as HandlerFn),
        ("bundle_config", ruby::bundle::check_bundle_config as HandlerFn),
        ("bundle_exec", ruby::bundle::check_bundle_exec as HandlerFn),
        ("gh_api", forges::gh::is_safe_gh_api as HandlerFn),
        ("laravel_cache_clear", php::check_laravel_cache_clear as HandlerFn),
        ("plutil_convert", system::plutil::check_plutil_convert as HandlerFn),
        ("plutil_extract", system::plutil::check_plutil_extract as HandlerFn),
    ])
}

pub(crate) fn judges_its_own_path(tokens: &[Token]) -> bool {
    tokens.first().is_some_and(|first| first.command_name() == "heavy-slot.sh")
}

pub(crate) fn names_a_command(tokens: &[Token]) -> bool {
    tokens.first().is_some_and(|first| named_verdict(first.command_name(), tokens).is_some())
}

fn named_verdict(cmd: &str, tokens: &[Token]) -> Option<Verdict> {
    None.or_else(|| crate::registry::custom_dispatch(tokens))
        .or_else(|| shell::dispatch(cmd, tokens))
        .or_else(|| wrappers::dispatch(cmd, tokens))
        .or_else(|| node::dispatch(cmd, tokens))
        .or_else(|| jvm::dispatch(cmd, tokens))
        .or_else(|| android::dispatch(cmd, tokens))
        .or_else(|| system::dispatch(cmd, tokens))
        .or_else(|| perl::dispatch(cmd, tokens))
        .or_else(|| coreutils::dispatch(cmd, tokens))
        .or_else(|| fuzzy::dispatch(cmd, tokens))
        .or_else(|| vcs::dispatch(cmd, tokens))
        .or_else(|| crate::registry::toml_dispatch(tokens))
}

pub fn dispatch(tokens: &[Token]) -> Verdict {
    let cmd = crate::engine::resolve::dispatch_name(&tokens[0]);
    let verdict = named_verdict(cmd, tokens).unwrap_or(Verdict::Denied);
    // Cross-cutting path-operand gate (audit fix): a legacy content-reader/writer must not
    // read/write a sensitive path just because its own handler ignored the operand's locus.
    // Canonicalize through the alias map (`gtee` → `tee`) so a Homebrew g-alias hits the same
    // role table its base name does — otherwise the alias sails past this gate (`gtee /etc/x`).
    if verdict.is_allowed() && crate::pathgate::should_deny(crate::registry::canonical_name(cmd), tokens) {
        return Verdict::Denied;
    }
    if verdict.is_allowed() && refuses_its_arguments(tokens) {
        return Verdict::Denied;
    }
    verdict
}

pub(crate) fn refuses_its_arguments(tokens: &[Token]) -> bool {
    let Some(first) = tokens.first() else {
        return false;
    };
    let specific = match crate::registry::canonical_name(first.command_name()) {
        "cargo" => safe_chains::cargo_run_reaches_a_rule_change(tokens),
        "chmod" => coreutils::chmod_mode::sets_an_id_bit(tokens),
        "mkdir" => coreutils::chmod_mode::mkdir_mode_sets_an_id_bit(tokens),
        "rsync" => {
            coreutils::chmod_mode::rsync_chmod_sets_an_id_bit(tokens)
                || coreutils::rsync_remote::refuses_its_remote_options(tokens)
                || coreutils::rsync_shell::names_a_program_to_run(tokens)
        }
        "git" => vcs::git::runs_in_a_repository_outside_the_project(tokens),
        name @ ("branchdiff" | "tig" | "hg" | "git-lfs" | "gitleaks" | "jj" | "jjpr") => {
            vcs::git::opens_a_repository_outside_the_project(name, tokens)
        }
        "bundle" => ruby::gemfile::loads_a_gemfile_out_of_sight(tokens),
        "make" => {
            make_text::evaluates_text_from_the_line(tokens)
                || make_dirs::moves_its_folder_out_of_sight(tokens)
                || make_dirs::moves_into_an_unreviewed_folder(tokens)
        }
        "mise" => env_print::prints_the_environment(tokens) || mise_global::sets_an_audited_variable_globally(tokens),
        "export" | "declare" | "ps" => env_print::prints_the_environment(tokens),
        "pax" => coreutils::archive_extract::extracts(tokens) || coreutils::stdin_names::reads_names_it_cannot_check(tokens),
        "cpio" => {
            coreutils::archive_extract::extracts(tokens)
                || coreutils::stdin_names::reads_names_it_cannot_check(tokens)
                || coreutils::archive_extract::opens_a_remote_archive(tokens)
        }
        "zip" => coreutils::stdin_names::reads_names_it_cannot_check(tokens),
        "ditto" | "xar" | "xip" | "ptar" | "ptargrep" | "7z" => coreutils::archive_extract::extracts(tokens),
        "man" | "apropos" | "manpath" => shell_text::man_evaluates_a_word(tokens),
        "zless" | "zmore" => shell_text::splits_a_flag(tokens) || shell_text::hands_flags_to_another_pager(tokens),
        "zcmp" | "bzcmp" => shell_text::splits_a_flag(tokens),
        "bash" | "sh" | "zsh" | "dash" | "ksh" => direct_script::runs_packaged_or_frozen(tokens),
        _ => false,
    };
    specific || followed_read::follows_a_secret(tokens)
}

pub fn handler_docs() -> Vec<crate::docs::CommandDoc> {
    let mut docs = Vec::new();
    docs.extend(node::command_docs());
    docs.extend(jvm::command_docs());
    docs.extend(android::command_docs());
    docs.extend(system::command_docs());
    docs.extend(coreutils::command_docs());
    docs.extend(fuzzy::command_docs());
    docs.extend(shell::command_docs());
    docs.extend(wrappers::command_docs());
    docs.extend(vcs::command_docs());
    docs.extend(crate::registry::toml_command_docs());
    docs
}

#[cfg(test)]
#[derive(Debug)]
pub(crate) enum CommandEntry {
    Custom { cmd: &'static str, valid_prefix: Option<&'static str> },
    Paths { cmd: &'static str, bare_ok: bool, paths: &'static [&'static str] },
}

#[cfg(test)]
fn full_registry() -> Vec<&'static CommandEntry> {
    let mut entries = Vec::new();
    entries.extend(forges::full_registry());
    entries.extend(jvm::full_registry());
    entries.extend(android::full_registry());
    entries.extend(network::REGISTRY);
    entries.extend(coreutils::full_registry());
    entries.extend(fuzzy::full_registry());
    entries
}

/// Whether safe-chains has a built-in rule for the command `name`: a handler or a TOML entry,
/// leaving out the user's own entries. `suggest` and `safe-chains config add` ask this before
/// drafting an entry, because an entry would replace the built-in rule (custom entries are
/// consulted first). The docs list some handlers under combined names (`bash / sh`), so a name
/// list missed them and `config add 'bash -c x'` drafted an override for bash.
pub(crate) fn is_built_in(name: &str) -> bool {
    let tokens = [Token::from_raw(name.to_string())];
    let cmd = crate::engine::resolve::dispatch_name(&tokens[0]);
    shell::dispatch(cmd, &tokens).is_some()
        || wrappers::dispatch(cmd, &tokens).is_some()
        || node::dispatch(cmd, &tokens).is_some()
        || jvm::dispatch(cmd, &tokens).is_some()
        || android::dispatch(cmd, &tokens).is_some()
        || system::dispatch(cmd, &tokens).is_some()
        || perl::dispatch(cmd, &tokens).is_some()
        || coreutils::dispatch(cmd, &tokens).is_some()
        || fuzzy::dispatch(cmd, &tokens).is_some()
        || vcs::dispatch(cmd, &tokens).is_some()
        || crate::registry::toml_dispatch(&tokens).is_some()
}
#[cfg(test)]
mod tests {
    use super::*;

    const UNKNOWN_FLAG: &str = "--xyzzy-unknown-42";
    const UNKNOWN_SUB: &str = "xyzzy-unknown-42";

    fn check_entry(entry: &CommandEntry, failures: &mut Vec<String>) {
        match entry {
            CommandEntry::Custom { cmd, valid_prefix } => {
                let base = valid_prefix.unwrap_or(cmd);
                let test = format!("{base} {UNKNOWN_FLAG}");
                if crate::is_safe_command(&test) {
                    failures.push(format!("{cmd}: accepted unknown flag: {test}"));
                }
            }
            CommandEntry::Paths { cmd, bare_ok, paths } => {
                if !bare_ok && crate::is_safe_command(cmd) {
                    failures.push(format!("{cmd}: accepted bare invocation"));
                }
                let test = format!("{cmd} {UNKNOWN_SUB}");
                if crate::is_safe_command(&test) {
                    failures.push(format!("{cmd}: accepted unknown subcommand: {test}"));
                }
                for path in *paths {
                    let test = format!("{path} {UNKNOWN_FLAG}");
                    if crate::is_safe_command(&test) {
                        failures.push(format!("{path}: accepted unknown flag: {test}"));
                    }
                }
            }
        }
    }

    #[test]
    fn all_commands_reject_unknown() {
        let registry = full_registry();
        let mut failures = Vec::new();
        for entry in &registry {
            check_entry(entry, &mut failures);
        }
        assert!(failures.is_empty(), "unknown flags/subcommands accepted:\n{}", failures.join("\n"));
    }

    #[test]
    fn process_substitution_safe_inner() {
        let safe =
            ["echo <(cat ./data.txt)", "grep pattern <(ls)", "diff <(sort a.txt) <(sort b.txt)", "comm -23 file.txt <(sort other.txt)"];
        for cmd in &safe {
            assert!(crate::is_safe_command(cmd), "safe process substitution rejected: {cmd}");
        }
    }

    #[test]
    fn process_substitution_unsafe_inner() {
        let unsafe_cmds = ["echo >(rm -rf /)", "diff <(sort a.txt) <(rm -rf /)"];
        for cmd in &unsafe_cmds {
            assert!(!crate::is_safe_command(cmd), "unsafe process substitution approved: {cmd}");
        }
    }
}