From caa13ae654508c1b87f37ab72e260ad2651edf17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabor=20K=C3=B6rber?= Date: Sat, 7 Nov 2026 01:07:44 +0100 Subject: [PATCH] feat(fermata): commands meet the path rules by verb class; a path call meets two projects' rules check_command_paths is wired for Bash, PowerShell and Monitor and merged with check_command, so allow_prefixes never lifts a path rule. Prints verbs get the rules and the read gate, Other verbs the rules, Metadata verbs nothing. A path call is decided by the path's project and the session's, and the worst stands: a Read of ~/.ssh/id_rsa from a project is stopped, and so is ../b/x under b's rules. --- src/bin/fermata.rs | 41 ++++--- src/core/policy.rs | 20 +++- src/harness/claude.rs | 3 + src/harness/mod.rs | 3 + tests/cli_command_paths.rs | 231 +++++++++++++++++++++++++++++++++++++ 5 files changed, 279 insertions(+), 19 deletions(-) create mode 100644 tests/cli_command_paths.rs diff --git a/src/bin/fermata.rs b/src/bin/fermata.rs index 2bc213e..8b9970b 100644 --- a/src/bin/fermata.rs +++ b/src/bin/fermata.rs @@ -228,25 +228,30 @@ fn run_pre_tool_use( let decision = match &call.op { 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, - Some(root) => match gate_policy(&root) { - Err(decision) => decision, - Ok(policy) => { - let op = match kind { - PathKind::Read => Op::Read, - PathKind::Write => Op::Write, - }; - policy.check(op, &path).unwrap_or_else(|e| check_failed(&root, &e)) - } - }, - } - } - ToolOp::Command { text } => match session.as_deref().and_then(find_project_root) { - None => Decision::Allow, - Some(root) => match gate_policy(&root) { + let op = match kind { + PathKind::Read => Op::Read, + PathKind::Write => Op::Write, + }; + // The path's project and the session's each decide, and the worst stands. + let mut roots: Vec = find_project_root(&path).into_iter().collect(); + roots.extend(session.as_deref().and_then(find_project_root)); + roots.dedup(); + let decisions = roots.iter().map(|root| match gate_policy(root) { Err(decision) => decision, - Ok(policy) => policy.check_command(text).unwrap_or_else(|e| check_failed(&root, &e)), + Ok(policy) => policy.check(op, &path).unwrap_or_else(|e| check_failed(root, &e)), + }); + decisions.fold(None, |worst, decision| Some(merge_worst(worst, decision))).unwrap_or(Decision::Allow) + } + ToolOp::Command { text } => match session.as_deref().and_then(|dir| Some((dir, find_project_root(dir)?))) { + None => Decision::Allow, + Some((dir, root)) => match gate_policy(&root) { + Err(decision) => decision, + Ok(policy) => { + // Apart, so that a bad `[policy.bash]` pattern costs only its own rules. + let rules = policy.check_command(text).unwrap_or_else(|e| check_failed(&root, &e)); + let paths = policy.check_command_paths(text, call.dialect, dir).unwrap_or_else(|e| check_failed(&root, &e)); + merge_worst(Some(rules), paths) + } }, }, }; diff --git a/src/core/policy.rs b/src/core/policy.rs index 615f7d8..cbfc2fc 100644 --- a/src/core/policy.rs +++ b/src/core/policy.rs @@ -1,7 +1,7 @@ use crate::core::botignore::{BotignoreError, BotignoreSet}; use crate::core::decision::{Decision, Reason, Rule}; use crate::core::op::Op; -use crate::core::paths::absolute; +use crate::core::paths::{absolute, command_paths, Dialect, Verb}; use crate::core::secrets::config::{GuardAction, PolicyConfig, SecretsConfig}; use crate::core::secrets::{unmaskable_reason, FileFormat, ManifestError, SecretFileSet}; use std::path::{Path, PathBuf}; @@ -111,6 +111,24 @@ impl Policy { Ok(Decision::Allow) } + /// What the paths `command` names meet, by verb class: nothing for a verb that only + /// names them, the read rules for any other, and the read gate for one that prints them. + /// `[policy.write]` does not reach commands. + pub fn check_command_paths(&self, command: &str, dialect: Dialect, cwd: &Path) -> Result { + let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from); + for named in command_paths(command, dialect, cwd, home.as_deref()) { + let decision = match named.verb { + Verb::Prints => self.check(Op::Read, &named.path)?, + Verb::Other => self.check_path_rules(Op::Read, &named.path)?, + Verb::Metadata => Decision::Allow, + }; + if decision.is_blocking() { + return Ok(decision); + } + } + Ok(Decision::Allow) + } + /// The path rules and, for a Read, the read gate. pub fn check(&self, op: Op, path: &Path) -> Result { let decision = self.check_path_rules(op, path)?; diff --git a/src/harness/claude.rs b/src/harness/claude.rs index ed501fc..0e18718 100644 --- a/src/harness/claude.rs +++ b/src/harness/claude.rs @@ -6,6 +6,7 @@ //! carries the verdict / updated output. use super::{AdapterError, HarnessAdapter, OutputEdit, PathKind, PostToolUsePayload, ToolCall, ToolOp}; +use crate::core::paths::Dialect; use crate::core::secrets::Redactor; use crate::core::Decision; use serde_json::{json, Map, Value}; @@ -31,10 +32,12 @@ impl HarnessAdapter for ClaudeAdapter { let op = tool_op(&tool_name, &tool_input)?; + let dialect = if tool_name == "PowerShell" { Dialect::PowerShell } else { Dialect::Posix }; Ok(ToolCall { tool_name, op, cwd: payload_cwd(&v), + dialect, raw: v, }) } diff --git a/src/harness/mod.rs b/src/harness/mod.rs index 2f1dd23..8c36c6a 100644 --- a/src/harness/mod.rs +++ b/src/harness/mod.rs @@ -1,6 +1,7 @@ //! Harness adapter layer. Normalizes harness-specific payloads into //! `core` types and renders `Decision` back to harness wire format. +use crate::core::paths::Dialect; use crate::core::secrets::Redactor; use crate::core::Decision; use std::path::PathBuf; @@ -31,6 +32,8 @@ pub struct ToolCall { pub raw: serde_json::Value, /// The session's current directory, if the harness sent one. pub cwd: Option, + /// Which shell's quoting a command is written in. + pub dialect: Dialect, } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/tests/cli_command_paths.rs b/tests/cli_command_paths.rs new file mode 100644 index 0000000..f08ab5a --- /dev/null +++ b/tests/cli_command_paths.rs @@ -0,0 +1,231 @@ +//! 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!({})); +}