fix(fermata): vendor/ covers what lies below it; relative paths and links meet the rules; the payload's cwd decides

.botignore matches a path or any parent, with the path tried first, so
!vendor/keep beats vendor/. Policy::check takes a relative path against the
root and also checks the path as the file system resolves it, spelled from the
root as given, so a link or a root behind a link hides nothing. session_dir: the
payload's cwd if absolute, else the process directory, for both hooks; fermata
check and the hook make paths absolute.
This commit is contained in:
2026-11-07 00:59:04 +01:00
parent 16a8b13fb9
commit 11328da30f
10 changed files with 386 additions and 28 deletions
+25
View File
@@ -69,3 +69,28 @@ fn check_exits_2_and_names_the_line_of_a_broken_config() {
.stderr(predicate::str::contains(".botsecrets").and(predicate::str::contains(format!("line {line}"))));
}
}
/// A relative path is taken against the working directory, as a shell does.
#[test]
fn check_takes_a_relative_path_against_the_working_directory() {
let tmp = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
fs::write(tmp.path().join(".botignore"), ".env\nvendor/\n").unwrap();
fs::write(tmp.path().join(".env"), "").unwrap();
fs::write(tmp.path().join("a.txt"), "").unwrap();
fs::create_dir(tmp.path().join("sub")).unwrap();
let check = |dir: &std::path::Path, op: &str, path: &str| {
Command::cargo_bin("fermata")
.unwrap()
.args(["check", "--op", op, path])
.current_dir(dir)
.env("HOME", home.path())
.assert()
};
check(tmp.path(), "read", ".env").code(1).stdout(predicate::str::contains(".env"));
check(tmp.path(), "read", "./.env").code(1);
check(tmp.path(), "write", "vendor/new").code(1);
check(&tmp.path().join("sub"), "read", "../.env").code(1);
check(tmp.path(), "read", "a.txt").code(0);
}
+136
View File
@@ -0,0 +1,136 @@
//! The session's directory (the payload's `cwd`) decides which project a call is in,
//! not the directory the hook was started in: Claude Code can spawn a hook elsewhere
//! (`--project-config-root`, remote mode, a deleted directory). All values are fake.
use assert_cmd::Command;
use serde_json::{json, Value};
use std::fs;
use std::path::Path;
use tempfile::TempDir;
const SESSION_VALUE: &str = "fake-value-of-the-session";
const PROCESS_VALUE: &str = "fake-value-of-the-process";
/// A project with a `.env` value of its own and a command rule
/// that denies a word of its own.
fn project(word: &str, value: &str, botignore: &str) -> TempDir {
let dir = tempfile::tempdir().unwrap();
fs::create_dir(dir.path().join(".git")).unwrap();
fs::write(dir.path().join(".botignore"), botignore).unwrap();
fs::write(dir.path().join(".botsecrets"), format!("[policy.bash]\ndeny = [\"{word}\"]\n")).unwrap();
fs::write(dir.path().join(".env"), format!("API_TOKEN={value}\n")).unwrap();
dir
}
struct Setup {
process: TempDir,
session: TempDir,
home: TempDir,
}
/// The hook runs in `process`. Only `session` blocks `.env` and `vendor/`, and each
/// denies its own word.
fn setup() -> Setup {
Setup {
process: project("process-word", PROCESS_VALUE, ""),
session: project("session-word", SESSION_VALUE, ".env\nvendor/\n"),
home: tempfile::tempdir().unwrap(),
}
}
impl Setup {
fn hook(&self, event: &str, mut payload: Value, cwd: Option<&Path>) -> Value {
if let Some(cwd) = cwd {
payload["cwd"] = json!(cwd);
}
let output = Command::cargo_bin("fermata")
.unwrap()
.args(["hook", "--event", event, "--harness", "claude"])
.current_dir(self.process.path())
.env("HOME", self.home.path())
.write_stdin(payload.to_string())
.assert()
.success()
.get_output()
.clone();
serde_json::from_slice(&output.stdout).unwrap()
}
fn bash(&self, command: &str, cwd: Option<&Path>) -> Value {
self.hook("pre-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": command}}), cwd)
}
fn pre_path(&self, tool: &str, file: &str, cwd: Option<&Path>) -> Value {
self.hook("pre-tool-use", json!({"tool_name": tool, "tool_input": {"file_path": file}}), cwd)
}
/// What the model gets of an output holding both projects' values.
fn post(&self, cwd: Option<&Path>) -> String {
let text = format!("{SESSION_VALUE} {PROCESS_VALUE}");
let out = self.hook("post-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "x"}, "tool_response": text}), cwd);
out["hookSpecificOutput"]["updatedToolOutput"].as_str().unwrap_or(&text).to_string()
}
}
fn is_denied(out: &Value) -> bool {
out["hookSpecificOutput"]["permissionDecision"] == "deny"
}
#[test]
fn the_payloads_directory_decides_a_command() {
let s = setup();
let session = Some(s.session.path());
assert!(is_denied(&s.bash("run session-word", session)));
assert_eq!(s.bash("run process-word", session), json!({}));
}
#[test]
fn the_payloads_directory_decides_what_post_tool_use_masks() {
let s = setup();
assert_eq!(s.post(Some(s.session.path())), format!("***** {PROCESS_VALUE}"));
}
#[test]
fn a_relative_file_path_is_taken_against_the_payloads_directory() {
let s = setup();
let session = Some(s.session.path());
assert!(is_denied(&s.pre_path("Read", ".env", session)));
assert!(is_denied(&s.pre_path("Read", "./.env", session)));
assert!(is_denied(&s.pre_path("Write", "vendor/a", session)));
assert!(is_denied(&s.pre_path("Edit", "vendor/b/c", session)));
assert_eq!(s.pre_path("Read", "src/a.rs", session), json!({}));
}
/// A subdirectory and a deleted directory are still in their project.
#[test]
fn a_payloads_directory_that_is_gone_is_still_in_its_project() {
let s = setup();
let gone = s.session.path().join("gone/sub");
assert!(is_denied(&s.bash("run session-word", Some(&gone))));
assert_eq!(s.post(Some(&gone)), format!("***** {PROCESS_VALUE}"));
assert!(is_denied(&s.pre_path("Read", "../../.env", Some(&gone))));
}
/// No `cwd` and a `cwd` that is not absolute both leave the process directory, as
/// every existing test and an older Claude Code do.
#[test]
fn without_a_usable_directory_the_process_directory_decides() {
let s = setup();
for cwd in [None, Some(Path::new("relative/dir"))] {
assert!(is_denied(&s.bash("run process-word", cwd)), "{cwd:?}");
assert_eq!(s.bash("run session-word", cwd), json!({}), "{cwd:?}");
assert_eq!(s.post(cwd), format!("{SESSION_VALUE} *****"), "{cwd:?}");
assert_eq!(s.pre_path("Read", ".env", cwd), json!({}), "{cwd:?}: the process project has no such rule");
}
fs::write(s.process.path().join(".botignore"), ".env\n").unwrap();
assert!(is_denied(&s.pre_path("Read", ".env", None)));
}
/// An absolute path decides its own project, wherever the session is.
#[test]
fn an_absolute_file_path_stays_in_its_own_project() {
let s = setup();
let env = s.session.path().join(".env");
assert!(is_denied(&s.pre_path("Read", env.to_str().unwrap(), None)));
assert!(is_denied(&s.pre_path("Read", s.session.path().join("x/../.env").to_str().unwrap(), Some(s.process.path()))));
}
+45
View File
@@ -133,3 +133,48 @@ fn nested_botignore_overrides_root() {
"logs/.botignore should un-ignore keep.log",
);
}
/// As in git, a directory pattern covers what lies below it, also a file not written yet.
#[test]
fn a_directory_pattern_covers_the_files_below_it() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
fs::write(root.join(".botignore"), "vendor/\n").unwrap();
fs::create_dir_all(root.join("vendor/b")).unwrap();
fs::write(root.join("vendor/a"), "").unwrap();
fs::write(root.join("vendor/b/c"), "").unwrap();
fs::write(root.join("vendors"), "").unwrap();
let set = BotignoreSet::load(root).unwrap();
for below in ["vendor", "vendor/a", "vendor/b/c", "vendor/new", "vendor/b/new"] {
let rule = set.matched(&root.join(below)).unwrap();
assert_eq!(rule.map(|r| r.pattern).as_deref(), Some("vendor/"), "{below}");
}
assert!(set.matched(&root.join("vendors")).unwrap().is_none());
assert!(set.matched(&root.join("src/vendor")).unwrap().is_none(), "no such directory, and the file is no directory");
assert!(set.matched(root).unwrap().is_none());
}
/// The path is tried before its parents, so a negation under the directory wins.
#[test]
fn a_negation_below_a_directory_pattern_keeps_that_file() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
fs::write(root.join(".botignore"), "vendor/\n!vendor/keep\n").unwrap();
fs::create_dir_all(root.join("vendor")).unwrap();
fs::write(root.join("vendor/keep"), "").unwrap();
fs::write(root.join("vendor/a"), "").unwrap();
let set = BotignoreSet::load(root).unwrap();
assert!(set.matched(&root.join("vendor/keep")).unwrap().is_none());
assert!(set.matched(&root.join("vendor/a")).unwrap().is_some());
}
/// A path outside a matcher's directory never reaches it: the parents call asserts on one.
#[test]
fn a_path_outside_the_root_matches_nothing() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join(".botignore"), "*\n").unwrap();
let set = BotignoreSet::load(tmp.path()).unwrap();
assert!(set.matched(std::path::Path::new("/elsewhere/a")).unwrap().is_none());
}
+99
View File
@@ -64,3 +64,102 @@ fn policy_write_block_applies_only_to_write() {
assert_eq!(policy.check(Op::Read, &target).unwrap(), Decision::Allow);
assert!(matches!(policy.check(Op::Write, &target).unwrap(), Decision::Deny(_)));
}
fn denied(policy: &Policy, op: Op, path: impl AsRef<std::path::Path>) -> bool {
policy.check(op, path.as_ref()).unwrap().is_blocking()
}
/// A relative path is the project's, for `.botignore` and for `[policy]`.
#[test]
fn a_relative_path_is_taken_against_the_root() {
let tmp = make_project(".env\nvendor/\n", "[policy.read]\npatterns = [\"conf/*.yaml\"]\n");
let policy = Policy::load(tmp.path()).unwrap();
assert!(denied(&policy, Op::Read, ".env"));
assert!(denied(&policy, Op::Read, "./.env"));
assert!(denied(&policy, Op::Read, "src/../.env"));
assert!(denied(&policy, Op::Write, "vendor/a"));
assert!(denied(&policy, Op::Read, "conf/a.yaml"));
assert!(!denied(&policy, Op::Read, "src/a.rs"));
assert!(!denied(&policy, Op::Write, "conf/a.yaml"));
}
#[test]
fn an_absolute_path_with_dots_is_resolved_first() {
let tmp = make_project(".env\n", "");
let policy = Policy::load(tmp.path()).unwrap();
assert!(denied(&policy, Op::Read, tmp.path().join("src/../.env")));
}
#[cfg(unix)]
mod links {
use super::*;
use std::os::unix::fs::symlink;
#[test]
fn a_link_to_a_blocked_file_is_stopped() {
let tmp = make_project(".env\n", "[policy.read]\npatterns = [\"conf/**\"]\n");
fs::write(tmp.path().join(".env"), "").unwrap();
fs::create_dir(tmp.path().join("conf")).unwrap();
fs::write(tmp.path().join("conf/a.yaml"), "").unwrap();
fs::write(tmp.path().join("plain.txt"), "").unwrap();
symlink(".env", tmp.path().join("notes")).unwrap();
symlink("conf/a.yaml", tmp.path().join("settings")).unwrap();
symlink("plain.txt", tmp.path().join("other")).unwrap();
let policy = Policy::load(tmp.path()).unwrap();
assert!(denied(&policy, Op::Read, tmp.path().join("notes")));
assert!(denied(&policy, Op::Read, "notes"), "relative");
assert!(denied(&policy, Op::Read, tmp.path().join("settings")), "[policy.read]");
assert!(!denied(&policy, Op::Read, tmp.path().join("other")));
}
/// A new file does not exist to resolve, and the link above it does.
#[test]
fn a_new_file_below_a_link_is_where_the_link_points() {
let tmp = make_project("vendor/\n", "");
fs::create_dir(tmp.path().join("vendor")).unwrap();
symlink("vendor", tmp.path().join("v")).unwrap();
let policy = Policy::load(tmp.path()).unwrap();
assert!(denied(&policy, Op::Write, tmp.path().join("v/new")));
}
/// The matchers hold the root as it was given. A root reached through a link must
/// still meet a path spelled the real way, and the other way round.
#[test]
fn a_root_behind_a_link_meets_both_spellings() {
let tmp = tempfile::tempdir().unwrap();
let real = tmp.path().join("real");
fs::create_dir(&real).unwrap();
fs::write(real.join(".botignore"), ".env\n").unwrap();
fs::write(real.join(".env"), "").unwrap();
fs::write(real.join("a.txt"), "").unwrap();
symlink(".env", real.join("notes")).unwrap();
let link = tmp.path().join("link");
symlink(&real, &link).unwrap();
let through_link = Policy::load(&link).unwrap();
for path in [real.join(".env"), real.join("notes"), link.join(".env"), link.join("notes")] {
assert!(denied(&through_link, Op::Read, &path), "{}", path.display());
}
assert!(!denied(&through_link, Op::Read, real.join("a.txt")));
let direct = Policy::load(&real).unwrap();
assert!(denied(&direct, Op::Read, link.join(".env")));
assert!(!denied(&direct, Op::Read, link.join("a.txt")));
}
/// A link out of the project is no way around a `[policy]` glob, and `.botignore`
/// rules stay with their own directory.
#[test]
fn a_link_out_of_the_root_keeps_the_rules_scoped() {
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join("server.key"), "").unwrap();
fs::write(outside.path().join("a.txt"), "").unwrap();
let tmp = make_project("a.txt\n", "[policy.read]\npatterns = [\"**/*.key\"]\n");
symlink(outside.path().join("server.key"), tmp.path().join("k")).unwrap();
symlink(outside.path().join("a.txt"), tmp.path().join("b.txt")).unwrap();
let policy = Policy::load(tmp.path()).unwrap();
assert!(denied(&policy, Op::Read, tmp.path().join("k")));
assert!(!denied(&policy, Op::Read, tmp.path().join("b.txt")));
}
}
+10
View File
@@ -155,3 +155,13 @@ fn powershell_and_monitor_commands_are_commands() {
assert_eq!(call.op, ToolOp::Command { text: "tail -f x.log".into() }, "{tool}");
}
}
#[test]
fn a_payloads_working_directory_is_kept_for_both_events() {
let with = br#"{"tool_name":"Bash","cwd":"/proj/sub","tool_input":{"command":"ls"},"tool_response":"x"}"#;
let without = br#"{"tool_name":"Bash","tool_input":{"command":"ls"},"tool_response":"x"}"#;
assert_eq!(ClaudeAdapter.parse_request(with).unwrap().cwd.as_deref(), Some(std::path::Path::new("/proj/sub")));
assert_eq!(ClaudeAdapter.parse_post_tool_use(with).unwrap().cwd.as_deref(), Some(std::path::Path::new("/proj/sub")));
assert_eq!(ClaudeAdapter.parse_request(without).unwrap().cwd, None);
assert_eq!(ClaudeAdapter.parse_post_tool_use(without).unwrap().cwd, None);
}