Files
fermata/tests/cli_command_paths.rs
T
g4borg 34298c5f9a fix(fermata): a shell behind a wrapper and a verb given by path are read; the forms that stay text are named
The bash/sh/zsh/eval unwrap reads the word after the prefix walk, so sudo, env,
timeout, nohup, exec, xargs, busybox and X=1 in front of a shell no longer hide
its command line. A prefix counts by its file name, as a verb already did, so
/bin/bash -c, /usr/bin/env cat and /usr/bin/timeout 5 cat are read.

Named as limits, each with a test in known_limits.rs: dash -c, ksh -c,
bash -c -- x, eval past its first argument, sudo -u root bash -c, and on the read
gate eval cat id_rsa and cat <&3 id_rsa. (re-check I-3, I-4 leftover, I-5's stale line)
2026-11-07 02:11:10 +01:00

325 lines
14 KiB
Rust

//! A command meets the path rules by its verb class, and a path call meets the rules of
//! the path's project and of the session's. All values are fake.
use assert_cmd::Command;
use serde_json::{json, Value};
use std::fs;
use std::path::Path;
use tempfile::TempDir;
const VALUE: &str = "fake-value-in-the-file";
const ENV: &str = "API_TOKEN=fake-value-in-the-file\n";
const PEM: &str = "-----BEGIN PRIVATE KEY-----\nFAKEFAKEfakeFAKEfake\n-----END PRIVATE KEY-----\n";
/// The same rule, in each of the two places a project can write it.
const RULES: [(&str, &str); 2] = [(".botignore", ".env\n"), (".botsecrets", "[policy.read]\npatterns = [\".env\"]\n")];
fn write(dir: &Path, files: &[(&str, &str)]) {
for (name, content) in files {
let path = dir.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, content).unwrap();
}
}
fn project(files: &[(&str, &str)]) -> TempDir {
let dir = tempfile::tempdir().unwrap();
fs::create_dir(dir.path().join(".git")).unwrap();
write(dir.path(), files);
dir
}
fn hook_in(dir: &Path, home: &Path, payload: Value) -> Value {
let output = Command::cargo_bin("fermata")
.unwrap()
.args(["hook", "--event", "pre-tool-use", "--harness", "claude"])
.current_dir(dir)
.env("HOME", home)
.write_stdin(payload.to_string())
.assert()
.success()
.get_output()
.clone();
assert!(!String::from_utf8_lossy(&output.stderr).contains(VALUE));
serde_json::from_slice(&output.stdout).unwrap()
}
fn tool(dir: &Path, name: &str, command: &str) -> Value {
let home = tempfile::tempdir().unwrap();
hook_in(dir, home.path(), json!({"tool_name": name, "tool_input": {"command": command}}))
}
fn bash(dir: &Path, command: &str) -> Value {
tool(dir, "Bash", command)
}
fn verdict(out: &Value) -> &str {
out["hookSpecificOutput"]["permissionDecision"].as_str().unwrap_or("none")
}
fn reason(out: &Value) -> &str {
out["hookSpecificOutput"]["permissionDecisionReason"].as_str().unwrap_or_default()
}
#[test]
fn a_rule_on_a_path_stops_what_prints_it_or_runs_on_it_and_not_what_only_names_it() {
for rule in RULES {
let p = project(&[rule, (".env", ENV)]);
for command in ["cat .env", "cat ./.env; false", "gc .env", "source .env", "ls; cat .env", "cp .env x", "git add .env"] {
assert_eq!(verdict(&bash(p.path(), command)), "deny", "{rule:?}: {command}");
}
for command in ["ls .env", "test -f .env", "echo .env", "git commit -m .env", "grep .env .gitignore", "npm test"] {
assert_eq!(bash(p.path(), command), json!({}), "{rule:?}: {command}");
}
}
}
/// `allow_prefixes` skips `ask` and nothing else.
#[test]
fn an_allow_prefix_does_not_lift_a_path_rule() {
let allow = "[policy.bash]\nallow_prefixes = [\"cat\"]\nask = [\"cat\"]\n";
let p = project(&[(".botignore", ".env\n"), (".botsecrets", allow), (".env", ENV), ("notes.txt", "x")]);
assert_eq!(verdict(&bash(p.path(), "cat .env")), "deny");
assert_eq!(bash(p.path(), "cat notes.txt"), json!({}));
let both = format!("{allow}[policy.read]\npatterns = [\".env\"]\n");
let p = project(&[(".botsecrets", &both), (".env", ENV)]);
assert_eq!(verdict(&bash(p.path(), "cat .env")), "deny");
}
/// The worst of the two checks stands, whichever one stops the command.
#[test]
fn a_command_rule_and_a_path_rule_each_decide() {
let p = project(&[(".botignore", ".env\n"), (".botsecrets", "[policy.bash]\nask = [\"cat\"]\ndeny = [\"curl\"]\n"), (".env", ENV), ("a.txt", "x")]);
assert_eq!(verdict(&bash(p.path(), "cat a.txt")), "ask");
assert_eq!(verdict(&bash(p.path(), "cat .env")), "deny");
assert_eq!(verdict(&bash(p.path(), "curl x")), "deny");
}
/// A broken `[policy.bash]` costs its own rules, not the path rules.
#[test]
fn a_bad_command_rule_keeps_the_path_rule() {
let p = project(&[(".botignore", ".env\n"), (".botsecrets", "[policy.bash]\ndeny = [\"a[\"]\n"), (".env", ENV)]);
assert_eq!(verdict(&bash(p.path(), "cat .env")), "deny");
assert_eq!(bash(p.path(), "ls"), json!({}));
}
/// `[policy.write]` does not reach commands.
#[test]
fn a_write_rule_is_not_applied_to_a_command() {
let p = project(&[(".botsecrets", "[policy.write]\npatterns = [\"a.txt\"]\n"), ("a.txt", "x")]);
assert_eq!(bash(p.path(), "cat a.txt"), json!({}));
assert_eq!(bash(p.path(), "cp a.txt b.txt"), json!({}));
}
#[test]
fn powershell_and_monitor_meet_the_same_rules() {
let p = project(&[(".botignore", ".env\n"), (".env", ENV)]);
assert_eq!(verdict(&tool(p.path(), "PowerShell", "gc .\\.env")), "deny");
assert_eq!(verdict(&tool(p.path(), "PowerShell", "Get-Content .env")), "deny");
assert_eq!(verdict(&tool(p.path(), "Monitor", "tail -f .env")), "deny");
assert_eq!(tool(p.path(), "PowerShell", "ls .env"), json!({}));
// Backslash is an escape in a POSIX shell, so this names `..env`, which is not there.
assert_eq!(bash(p.path(), "gc .\\.env"), json!({}));
}
/// The read gate needs no rule, and only a printing command meets it.
#[test]
fn on_default_config_only_a_printing_command_meets_the_read_gate() {
let p = project(&[("id_rsa", PEM), ("a.key", PEM)]);
for command in ["cat id_rsa", "head -n 1 id_rsa", "base64 a.key", "sudo cat ./id_rsa", "cat < id_rsa"] {
let out = bash(p.path(), command);
assert_eq!(verdict(&out), "deny", "{command}");
assert!(reason(&out).contains("ask the user") && !reason(&out).contains("FAKE"), "{out}");
}
for command in ["ssh -i id_rsa x", "chmod 600 id_rsa", "ls *.key", "ls -la id_rsa", "openssl rsa -in a.key", "curl --cert a.key x"] {
assert_eq!(bash(p.path(), command), json!({}), "{command}");
}
}
#[test]
fn on_unparsed_read_allow_lifts_the_gate_on_commands_too() {
let p = project(&[(".botsecrets", "[enforcement]\non_unparsed_read = \"allow\"\n"), ("id_rsa", PEM)]);
assert_eq!(bash(p.path(), "cat id_rsa"), json!({}));
}
/// A leading `~/` is the home the hook runs under.
#[test]
fn a_command_naming_a_file_in_home_meets_the_read_gate() {
let p = project(&[]);
let home = tempfile::tempdir().unwrap();
write(home.path(), &[(".ssh/id_rsa", PEM)]);
let call = |command: &str| hook_in(p.path(), home.path(), json!({"tool_name": "Bash", "tool_input": {"command": command}}));
assert_eq!(verdict(&call("cat ~/.ssh/id_rsa")), "deny");
assert_eq!(call("ls ~/.ssh/id_rsa"), json!({}));
}
/// The session's directory resolves the words, not this process's.
#[test]
fn the_payloads_cwd_resolves_a_commands_words() {
let p = project(&[(".botignore", ".env\n"), (".env", ENV), ("sub/x", "")]);
let elsewhere = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let call = |cwd: &Path, command: &str| {
hook_in(elsewhere.path(), home.path(), json!({"tool_name": "Bash", "cwd": cwd, "tool_input": {"command": command}}))
};
assert_eq!(verdict(&call(p.path(), "cat .env")), "deny");
assert_eq!(call(&p.path().join("sub"), "cat .env"), json!({}));
assert_eq!(verdict(&call(&p.path().join("sub"), "cat ../.env")), "deny");
}
// ---------------------------------------------------------------------------
// Two roots
// ---------------------------------------------------------------------------
fn read_from(session: &Path, home: &Path, file: &Path) -> Value {
hook_in(session, home, json!({"tool_name": "Read", "tool_input": {"file_path": file}}))
}
/// `home` has no project of its own, so only the session's rules can stop this.
#[test]
fn the_sessions_project_decides_a_read_outside_any_project() {
let a = project(&[]);
let home = tempfile::tempdir().unwrap();
write(home.path(), &[(".ssh/id_rsa", PEM), (".ssh/config", "Host x\n")]);
let out = read_from(a.path(), home.path(), &home.path().join(".ssh/id_rsa"));
assert_eq!(verdict(&out), "deny", "{out}");
assert_eq!(read_from(a.path(), home.path(), &home.path().join(".ssh/config")), json!({}));
// With the setting off in the session's project there is no one left to stop it.
let a = project(&[(".botsecrets", "[enforcement]\non_unparsed_read = \"allow\"\n")]);
assert_eq!(read_from(a.path(), home.path(), &home.path().join(".ssh/id_rsa")), json!({}));
}
/// Rules of the path's project hold from any session, by relative path too.
#[test]
fn the_paths_project_decides_a_read_from_another_session() {
let parent = tempfile::tempdir().unwrap();
let (a, b) = (parent.path().join("a"), parent.path().join("b"));
write(&a, &[(".git/x", "")]);
write(&b, &[(".git/x", ""), (".botignore", "x\n"), ("x", "fake"), ("y", "fake")]);
let home = tempfile::tempdir().unwrap();
let relative = |file: &str| hook_in(&a, home.path(), json!({"tool_name": "Read", "tool_input": {"file_path": format!("../b/{file}")}}));
assert_eq!(verdict(&relative("x")), "deny");
assert_eq!(relative("y"), json!({}));
assert_eq!(verdict(&read_from(&a, home.path(), &b.join("x"))), "deny");
}
/// Each root decides, and the worst stands: the session's rule holds in another project,
/// and a Write counts as a Write in both.
#[test]
fn the_worst_of_two_roots_stands() {
let parent = tempfile::tempdir().unwrap();
let (a, b) = (parent.path().join("a"), parent.path().join("b"));
write(&a, &[(".git/x", ""), (".botsecrets", "[policy.read]\npatterns = [\"**/x\"]\n[policy.write]\npatterns = [\"**/w\"]\n")]);
write(&b, &[(".git/x", ""), ("x", "fake"), ("w", "fake")]);
let home = tempfile::tempdir().unwrap();
assert_eq!(verdict(&read_from(&a, home.path(), &b.join("x"))), "deny");
assert_eq!(read_from(&a, home.path(), &b.join("w")), json!({}));
let write_call = hook_in(&a, home.path(), json!({"tool_name": "Write", "tool_input": {"file_path": b.join("w"), "content": ""}}));
assert_eq!(verdict(&write_call), "deny");
let write_call = hook_in(&a, home.path(), json!({"tool_name": "Write", "tool_input": {"file_path": b.join("x"), "content": ""}}));
assert_eq!(write_call, json!({}));
}
/// When the session and the path share a project, its rules decide as they did with one root.
#[test]
fn a_path_in_the_sessions_own_project_stays_as_it_was() {
let p = project(&[(".botignore", ".env\n"), (".env", ENV), ("a.txt", "x")]);
let home = tempfile::tempdir().unwrap();
assert_eq!(verdict(&read_from(p.path(), home.path(), &p.path().join(".env"))), "deny");
assert_eq!(read_from(p.path(), home.path(), &p.path().join("a.txt")), json!({}));
}
/// A word with a separator names a path only if the path is there. A package, a branch, an
/// image or a host's path is no file under a directory rule.
#[test]
fn a_word_with_a_separator_that_is_no_existing_path_is_not_denied() {
let p = project(&[(".botignore", "vendor/\nbuild/\n"), ("vendor/a", "x"), ("build/x", "x")]);
for command in ["composer require vendor/package", "git checkout build/fix", "git log build/fix", "docker build -t build/img .", "curl example.com/vendor/a"] {
assert_eq!(bash(p.path(), command), json!({}), "{command}");
}
// What is there, what a variable or glob may reach, and a redirect's target still count.
for command in ["cat vendor/a", "cat ./vendor/a", "cp vendor/a b", "cat < vendor/a", "tool > vendor/new", "tool $X/vendor/a", "tool */vendor/a", "cat vendor/?", "rm -rf vendor/"] {
assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}");
}
}
/// A listed printing verb behind a wrapper or an early redirect is still that verb.
#[test]
fn a_wrapper_or_an_early_redirect_does_not_hide_a_printing_verb() {
let p = project(&[("id_rsa", PEM)]);
for command in [
"timeout 5 cat id_rsa",
"timeout 5s cat id_rsa",
"timeout -k 1 5 cat id_rsa",
"nice cat id_rsa",
"nice -n 10 cat id_rsa",
"ionice -c 2 cat id_rsa",
"stdbuf -o0 cat id_rsa",
"xargs cat id_rsa",
"xargs -n 1 cat id_rsa",
"busybox cat id_rsa",
"cat 2>&1 id_rsa",
"cat 1>&2 id_rsa",
"cat >&2 id_rsa",
] {
assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}");
}
// The wrapper's own program is no printing verb, and a background job still splits.
for command in ["timeout 5 ssh -i id_rsa x", "nice chmod 600 id_rsa", "sleep 1 & ls id_rsa"] {
assert_eq!(bash(p.path(), command), json!({}), "{command}");
}
}
/// A shell's `-c` argument and `eval`'s are command lines, and are read as such.
#[test]
fn a_command_line_given_to_a_shell_or_eval_is_read() {
let p = project(&[(".botignore", "vendor/\n.env\n"), (".env", ENV), ("vendor/a/b", "x"), ("id_rsa", PEM)]);
for command in ["bash -c 'cat .env'", "sh -c 'cat vendor/a/b'", "zsh -c 'cat .env'", "bash -lc 'cat .env'", "eval 'cat .env'", "bash -c 'ls; cat id_rsa'", "bash -c \"bash -c 'cat .env'\""] {
assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}");
}
for command in ["bash -c 'echo hello'", "sh run.sh", "bash -c 'ls .env'", "eval 'true'", "bash"] {
assert_eq!(bash(p.path(), command), json!({}), "{command}");
}
}
/// The same behind a wrapper or an assignment, and a shell, a wrapper or a verb given by
/// its path: what counts is the word the prefix walk stops at, by its file name.
#[test]
fn a_shell_behind_a_wrapper_and_a_verb_given_by_path_are_read() {
let p = project(&[(".botignore", ".env\n"), (".env", ENV), ("id_rsa", PEM)]);
for command in [
"sudo bash -c 'cat .env'",
"env bash -c 'cat .env'",
"/usr/bin/env bash -c 'cat .env'",
"/bin/bash -c 'cat .env'",
"timeout 5 bash -c 'cat .env'",
"nohup sh -c 'cat .env'",
"exec sh -c 'cat .env'",
"xargs sh -c 'cat .env'",
"busybox sh -c 'cat .env'",
"X=1 bash -c 'cat .env'",
"env X=1 bash -c 'cat .env'",
"command eval 'cat .env'",
// The read gate, with no rule on the name.
"sudo bash -c 'cat id_rsa'",
"/bin/bash -c 'cat id_rsa'",
"X=1 bash -c 'cat id_rsa'",
"/bin/cat id_rsa",
"/usr/bin/env cat id_rsa",
"/usr/bin/sudo cat id_rsa",
"/usr/bin/timeout 5 cat id_rsa",
] {
assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}");
}
for command in [
"sudo bash -c 'ls .env'",
"/bin/bash -c 'echo .env'",
"X=1 bash -c 'echo hello'",
"/usr/bin/env ls id_rsa",
"/usr/bin/timeout 5 ls id_rsa",
] {
assert_eq!(bash(p.path(), command), json!({}), "{command}");
}
}