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:
+21
-12
@@ -1,6 +1,6 @@
|
|||||||
use clap::{Parser, Subcommand, ValueEnum};
|
use clap::{Parser, Subcommand, ValueEnum};
|
||||||
use dirigent_fermata::core::secrets::{config::ParseErrorAction, SecretsConfig};
|
use dirigent_fermata::core::secrets::{config::ParseErrorAction, SecretsConfig};
|
||||||
use dirigent_fermata::core::{project::find_project_root, Decision, Op, Policy, Reason};
|
use dirigent_fermata::core::{paths::absolute, project::find_project_root, Decision, Op, Policy, Reason};
|
||||||
use dirigent_fermata::harness::HookEvent;
|
use dirigent_fermata::harness::HookEvent;
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
@@ -61,7 +61,9 @@ fn main() -> ExitCode {
|
|||||||
|
|
||||||
fn run_check(op: Op, json: bool, paths: &[PathBuf]) -> ExitCode {
|
fn run_check(op: Op, json: bool, paths: &[PathBuf]) -> ExitCode {
|
||||||
let mut worst: Option<Decision> = None;
|
let mut worst: Option<Decision> = None;
|
||||||
|
let cwd = std::env::current_dir().unwrap_or_default();
|
||||||
for p in paths {
|
for p in paths {
|
||||||
|
let p = &absolute(p, &cwd);
|
||||||
let root = match find_project_root(p) {
|
let root = match find_project_root(p) {
|
||||||
Some(r) => r,
|
Some(r) => r,
|
||||||
None => continue,
|
None => continue,
|
||||||
@@ -134,6 +136,15 @@ fn run_hook(event_str: &str, harness: &str) -> ExitCode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The directory a call runs in: the payload's `cwd` if absolute, else this process's.
|
||||||
|
/// `None` only if neither is known.
|
||||||
|
fn session_dir(cwd: Option<&Path>) -> Option<PathBuf> {
|
||||||
|
match cwd.filter(|cwd| cwd.is_absolute()) {
|
||||||
|
Some(cwd) => Some(cwd.to_path_buf()),
|
||||||
|
None => std::env::current_dir().map_err(|e| eprintln!("fermata: cwd error: {e}")).ok(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The refusal text of the failure paths. It names files, never their contents.
|
/// The refusal text of the failure paths. It names files, never their contents.
|
||||||
const FIX_OR_CHANGE: &str = "and on_parse_error = \"deny\" is set. Fix the file or change the setting.";
|
const FIX_OR_CHANGE: &str = "and on_parse_error = \"deny\" is set. Fix the file or change the setting.";
|
||||||
|
|
||||||
@@ -201,8 +212,11 @@ fn run_pre_tool_use(
|
|||||||
gate_failure(root, "the .botignore or [policy] rules cannot be applied,")
|
gate_failure(root, "the .botignore or [policy] rules cannot be applied,")
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let session = session_dir(call.cwd.as_deref());
|
||||||
let decision = match &call.op {
|
let decision = match &call.op {
|
||||||
ToolOp::Path { path, kind } => match find_project_root(path) {
|
ToolOp::Path { path, kind } => {
|
||||||
|
let path = session.as_deref().map_or_else(|| path.clone(), |dir| absolute(path, dir));
|
||||||
|
match find_project_root(&path) {
|
||||||
None => Decision::Allow,
|
None => Decision::Allow,
|
||||||
Some(root) => match gate_policy(&root) {
|
Some(root) => match gate_policy(&root) {
|
||||||
Err(decision) => decision,
|
Err(decision) => decision,
|
||||||
@@ -211,23 +225,18 @@ fn run_pre_tool_use(
|
|||||||
PathKind::Read => Op::Read,
|
PathKind::Read => Op::Read,
|
||||||
PathKind::Write => Op::Write,
|
PathKind::Write => Op::Write,
|
||||||
};
|
};
|
||||||
policy.check(op, path).unwrap_or_else(|e| check_failed(&root, &e))
|
policy.check(op, &path).unwrap_or_else(|e| check_failed(&root, &e))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
|
||||||
ToolOp::Command { text } => match std::env::current_dir() {
|
|
||||||
Err(e) => {
|
|
||||||
eprintln!("fermata: cwd error: {e}");
|
|
||||||
Decision::Allow
|
|
||||||
}
|
}
|
||||||
Ok(cwd) => match find_project_root(&cwd) {
|
}
|
||||||
|
ToolOp::Command { text } => match session.as_deref().and_then(find_project_root) {
|
||||||
None => Decision::Allow,
|
None => Decision::Allow,
|
||||||
Some(root) => match gate_policy(&root) {
|
Some(root) => match gate_policy(&root) {
|
||||||
Err(decision) => decision,
|
Err(decision) => decision,
|
||||||
Ok(policy) => policy.check_command(text).unwrap_or_else(|e| check_failed(&root, &e)),
|
Ok(policy) => policy.check_command(text).unwrap_or_else(|e| check_failed(&root, &e)),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
|
||||||
};
|
};
|
||||||
let out = adapter
|
let out = adapter
|
||||||
.render_decision(&call, &decision)
|
.render_decision(&call, &decision)
|
||||||
@@ -267,8 +276,8 @@ fn run_post_tool_use(
|
|||||||
return pass_through();
|
return pass_through();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find project root from cwd (PostToolUse has no reliable path).
|
// Find project root from the session's directory (PostToolUse has no reliable path).
|
||||||
let root = match std::env::current_dir().ok().and_then(|d| find_project_root(&d)) {
|
let root = match session_dir(payload.cwd.as_deref()).and_then(|d| find_project_root(&d)) {
|
||||||
Some(r) => r,
|
Some(r) => r,
|
||||||
// No project root → nothing to redact, pass through.
|
// No project root → nothing to redact, pass through.
|
||||||
None => return pass_through(),
|
None => return pass_through(),
|
||||||
|
|||||||
@@ -60,9 +60,10 @@ impl BotignoreSet {
|
|||||||
Ok(Self { matchers })
|
Ok(Self { matchers })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns `Some(Rule)` if `path` is matched (and not negated by a
|
/// Returns `Some(Rule)` if `path` or a directory above it is matched (and
|
||||||
/// deeper-scoped whitelist), else `None`. The deepest matcher whose
|
/// not negated by a deeper-scoped whitelist), else `None`. The deepest
|
||||||
/// directory contains `path` wins.
|
/// matcher whose directory contains `path` wins, and each tries the path
|
||||||
|
/// before its parents, so `!vendor/keep` beats `vendor/`.
|
||||||
pub fn matched(&self, path: &Path) -> Result<Option<Rule>, BotignoreError> {
|
pub fn matched(&self, path: &Path) -> Result<Option<Rule>, BotignoreError> {
|
||||||
let is_dir = path.is_dir();
|
let is_dir = path.is_dir();
|
||||||
let mut current: Option<&ScopedMatcher> = None;
|
let mut current: Option<&ScopedMatcher> = None;
|
||||||
@@ -72,7 +73,8 @@ impl BotignoreSet {
|
|||||||
if !path.starts_with(&sm.dir) {
|
if !path.starts_with(&sm.dir) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let m = sm.matcher.matched(path, is_dir);
|
// This call panics on a path outside `sm.dir`: the check above keeps it out.
|
||||||
|
let m = sm.matcher.matched_path_or_any_parents(path, is_dir);
|
||||||
if m.is_ignore() {
|
if m.is_ignore() {
|
||||||
current = Some(sm);
|
current = Some(sm);
|
||||||
current_pattern = m.inner().map(|g| g.original().to_string());
|
current_pattern = m.inner().map(|g| g.original().to_string());
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use crate::core::botignore::{BotignoreError, BotignoreSet};
|
use crate::core::botignore::{BotignoreError, BotignoreSet};
|
||||||
use crate::core::decision::{Decision, Reason, Rule};
|
use crate::core::decision::{Decision, Reason, Rule};
|
||||||
use crate::core::op::Op;
|
use crate::core::op::Op;
|
||||||
|
use crate::core::paths::absolute;
|
||||||
use crate::core::secrets::config::{PolicyConfig, SecretsConfig};
|
use crate::core::secrets::config::{PolicyConfig, SecretsConfig};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
@@ -84,7 +85,27 @@ impl Policy {
|
|||||||
Ok(Decision::Allow)
|
Ok(Decision::Allow)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A relative `path` is the project's. The path is checked as written and as the
|
||||||
|
/// file system resolves it, so a link does not hide what it points at.
|
||||||
pub fn check(&self, op: Op, path: &Path) -> Result<Decision, PolicyError> {
|
pub fn check(&self, op: Op, path: &Path) -> Result<Decision, PolicyError> {
|
||||||
|
let path = absolute(path, &self.root);
|
||||||
|
let decision = self.check_rules(op, &path)?;
|
||||||
|
match self.resolved(&path) {
|
||||||
|
Some(resolved) if !decision.is_blocking() => self.check_rules(op, &resolved),
|
||||||
|
_ => Ok(decision),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `path` with its links resolved, or `None` if that changes nothing. A file not
|
||||||
|
/// written yet goes where the nearest existing directory above it leads. Under the
|
||||||
|
/// root it is spelled from the root as given, because the rules hold that spelling.
|
||||||
|
fn resolved(&self, path: &Path) -> Option<PathBuf> {
|
||||||
|
let real = path.ancestors().find_map(|dir| Some(absolute(path.strip_prefix(dir).ok()?, &dir.canonicalize().ok()?)))?;
|
||||||
|
let inside = self.root.canonicalize().ok().and_then(|root| Some(self.root.join(real.strip_prefix(root).ok()?)));
|
||||||
|
Some(inside.unwrap_or(real)).filter(|resolved| resolved != path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_rules(&self, op: Op, path: &Path) -> Result<Decision, PolicyError> {
|
||||||
// 1. .botignore is path-only and applies to read+write equally.
|
// 1. .botignore is path-only and applies to read+write equally.
|
||||||
if matches!(op, Op::Read | Op::Write) {
|
if matches!(op, Op::Read | Op::Write) {
|
||||||
if let Some(rule) = self.botignore.matched(path)? {
|
if let Some(rule) = self.botignore.matched(path)? {
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ impl HarnessAdapter for ClaudeAdapter {
|
|||||||
Ok(ToolCall {
|
Ok(ToolCall {
|
||||||
tool_name,
|
tool_name,
|
||||||
op,
|
op,
|
||||||
|
cwd: payload_cwd(&v),
|
||||||
raw: v,
|
raw: v,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -79,7 +80,7 @@ impl HarnessAdapter for ClaudeAdapter {
|
|||||||
.to_string();
|
.to_string();
|
||||||
let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null);
|
let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null);
|
||||||
let tool_response = v.get("tool_response").cloned().unwrap_or(Value::Null);
|
let tool_response = v.get("tool_response").cloned().unwrap_or(Value::Null);
|
||||||
Ok(PostToolUsePayload { tool_name, tool_input, tool_response })
|
Ok(PostToolUsePayload { tool_name, tool_input, tool_response, cwd: payload_cwd(&v) })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn redact_output(&self, payload: &PostToolUsePayload, redactor: &Redactor) -> OutputEdit {
|
fn redact_output(&self, payload: &PostToolUsePayload, redactor: &Redactor) -> OutputEdit {
|
||||||
@@ -148,6 +149,12 @@ impl HarnessAdapter for ClaudeAdapter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The session's current directory. The hook's own may differ: Claude Code spawns hooks
|
||||||
|
/// in the project config root or the launch directory in some modes.
|
||||||
|
fn payload_cwd(v: &Value) -> Option<PathBuf> {
|
||||||
|
v.get("cwd").and_then(Value::as_str).map(PathBuf::from)
|
||||||
|
}
|
||||||
|
|
||||||
fn is_mcp(payload: &PostToolUsePayload) -> bool {
|
fn is_mcp(payload: &PostToolUsePayload) -> bool {
|
||||||
payload.tool_name.starts_with("mcp__")
|
payload.tool_name.starts_with("mcp__")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ pub struct ToolCall {
|
|||||||
pub op: ToolOp,
|
pub op: ToolOp,
|
||||||
/// Original raw payload for the adapter to consult when rendering.
|
/// Original raw payload for the adapter to consult when rendering.
|
||||||
pub raw: serde_json::Value,
|
pub raw: serde_json::Value,
|
||||||
|
/// The session's current directory, if the harness sent one.
|
||||||
|
pub cwd: Option<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -54,6 +56,8 @@ pub struct PostToolUsePayload {
|
|||||||
/// The tool's output as the harness sent it, in any shape. It may contain
|
/// The tool's output as the harness sent it, in any shape. It may contain
|
||||||
/// secrets. `Null` when the harness sent none.
|
/// secrets. `Null` when the harness sent none.
|
||||||
pub tool_response: serde_json::Value,
|
pub tool_response: serde_json::Value,
|
||||||
|
/// The session's current directory, if the harness sent one.
|
||||||
|
pub cwd: Option<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PostToolUsePayload {
|
impl PostToolUsePayload {
|
||||||
|
|||||||
@@ -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}"))));
|
.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);
|
||||||
|
}
|
||||||
|
|||||||
@@ -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()))));
|
||||||
|
}
|
||||||
@@ -133,3 +133,48 @@ fn nested_botignore_overrides_root() {
|
|||||||
"logs/.botignore should un-ignore keep.log",
|
"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());
|
||||||
|
}
|
||||||
|
|||||||
@@ -64,3 +64,102 @@ fn policy_write_block_applies_only_to_write() {
|
|||||||
assert_eq!(policy.check(Op::Read, &target).unwrap(), Decision::Allow);
|
assert_eq!(policy.check(Op::Read, &target).unwrap(), Decision::Allow);
|
||||||
assert!(matches!(policy.check(Op::Write, &target).unwrap(), Decision::Deny(_)));
|
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")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -155,3 +155,13 @@ fn powershell_and_monitor_commands_are_commands() {
|
|||||||
assert_eq!(call.op, ToolOp::Command { text: "tail -f x.log".into() }, "{tool}");
|
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);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user