From 6bf602aa6a9499d5a158360834d479f13cc90304 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabor=20K=C3=B6rber?= Date: Sat, 7 Nov 2026 02:00:45 +0100 Subject: [PATCH] fix(fermata): a bad glob costs only itself; commands read what is there, behind a wrapper or a shell - A glob in [files] or [policy] that does not compile costs only that pattern while open, with a note by name beside text output. A [files] list with none left leaves the built-in list. Under deny the refusal stays, and the channel filter stays strict. - A file named `credentials` is on the default list, at any depth. - A word with a separator counts only if the path is there, the shell may expand it, or a redirect names it: packages, branches and hosts' paths are not denied. - timeout, nice, ionice, stdbuf, xargs and busybox are prefixes; `2>&1` stays in its segment. - `bash|sh|zsh -c` and `eval` arguments are read as command lines. - A `<<` with no closing line is no heredoc. A commented line's own comment is dropped. Text holding NUL fails to parse. The unknown-field message says so. Durations are bound to under 6 characters. More source extensions pass the gate. - Removed: HarnessAdapter::post_tool_op (dead since 3C was dropped), tool_op back inline. --- src/bin/fermata.rs | 27 ++-- src/core/paths.rs | 51 +++++--- src/core/policy.rs | 31 ++--- src/core/secrets/config.rs | 20 ++- src/core/secrets/manifest.rs | 11 +- src/core/secrets/parser.rs | 13 +- src/core/secrets/value_class.rs | 13 +- src/harness/claude.rs | 33 ++--- src/harness/mod.rs | 4 - tests/cli_bad_patterns.rs | 213 +++++++++++++++++++++++++++++++ tests/cli_command_paths.rs | 53 ++++++++ tests/cli_hook_r2_values.rs | 6 + tests/cli_hook_read_gate.rs | 16 ++- tests/cli_hook_secret_formats.rs | 18 +++ tests/core_manifest_outbound.rs | 15 +++ tests/core_paths.rs | 46 ++++++- tests/core_secrets_config.rs | 6 +- tests/core_value_class.rs | 6 +- tests/harness_claude.rs | 23 +--- tests/known_limits.rs | 114 +++++++++++++++-- 20 files changed, 579 insertions(+), 140 deletions(-) create mode 100644 tests/cli_bad_patterns.rs diff --git a/src/bin/fermata.rs b/src/bin/fermata.rs index ca216e1..95b07cc 100644 --- a/src/bin/fermata.rs +++ b/src/bin/fermata.rs @@ -69,7 +69,7 @@ fn run_check(op: Op, json: bool, paths: &[PathBuf]) -> ExitCode { None => continue, }; // `Policy::load` goes on without a broken layer; a check says so instead. - let (_, errors) = SecretsConfig::load_or_default(&root); + let (config, errors) = SecretsConfig::load_or_default(&root); if !errors.is_empty() { for e in &errors { eprintln!("fermata: secrets config: {e}"); @@ -83,8 +83,8 @@ fn run_check(op: Op, json: bool, paths: &[PathBuf]) -> ExitCode { return ExitCode::from(2); } }; - if let Some(e) = policy.files_error() { - eprintln!("fermata: secrets config: {e}"); + if !config.bad_patterns().is_empty() { + eprintln!("fermata: secrets config: bad patterns: {}", config.bad_patterns().join(", ")); return ExitCode::from(2); } let d = match policy.check(op, p) { @@ -183,19 +183,19 @@ fn gate_policy(root: &Path) -> Result { return Err(refused); } } - let policy = Policy::load(root).map_err(|e| { - // A pattern can appear here. Patterns are not values: a deny reason names them too. - eprintln!("fermata: load error: {e}"); - gate_failure(root, "the .botignore or [policy] rules cannot be loaded,") - })?; - if let Some(e) = policy.files_error() { - eprintln!("fermata: secrets config: {e}"); - let refused = gate_failure(root, "the [files] patterns in .botsecrets cannot be used,"); + let bad = SecretsConfig::load_or_default(root).0.bad_patterns().join(", "); + if !bad.is_empty() { + eprintln!("fermata: secrets config: bad patterns: {bad}"); + let refused = gate_failure(root, &format!("the patterns {bad} in the [files] or [policy] rules cannot be used,")); if refused.is_blocking() { return Err(refused); } } - Ok(policy) + Policy::load(root).map_err(|e| { + // A pattern can appear here. Patterns are not values: a deny reason names them too. + eprintln!("fermata: load error: {e}"); + gate_failure(root, "the .botignore or [policy] rules cannot be loaded,") + }) } /// The write guard, under `root`'s settings: a call that would add a mask to `path` is @@ -395,6 +395,9 @@ fn run_post_tool_use( return answer(None, ¬es); } }; + if shows_text { + notes.extend(config.bad_patterns().iter().map(|p| format!("[fermata] The pattern {p} in [files] or [policy] does not compile, so that pattern is off."))); + } if shows_text && !manifest.skipped().is_empty() { let files: Vec = manifest.skipped().iter().map(|path| shown_path(path, &root)).collect(); notes.push(format!("[fermata] {} cannot be parsed, so its values are not masked here.", files.join(", "))); diff --git a/src/core/paths.rs b/src/core/paths.rs index fca630a..6beb207 100644 --- a/src/core/paths.rs +++ b/src/core/paths.rs @@ -30,8 +30,9 @@ const METADATA: &[&str] = &["ls", "stat", "file", "test", "[", "[[", "du", "whic const GIT_METADATA: &[&str] = &["status", "check-ignore", "ls-files", "commit"]; /// Words that run what follows them. The shell's keywords are here because in /// `if [ -f .env ]; then` the verb is `[`. -const PREFIXES: &[&str] = - &["sudo", "env", "time", "nohup", "command", "exec", "if", "elif", "then", "else", "while", "until", "do", "!", "{"]; +const PREFIXES: &[&str] = &[ + "sudo", "env", "time", "nohup", "command", "exec", "timeout", "nice", "ionice", "stdbuf", "xargs", "busybox", "if", "elif", "then", "else", "while", "until", "do", "!", "{", +]; /// Verbs whose first word is a pattern, unless `-e` or `-f` gives it. const PATTERN_FIRST: &[&str] = &["grep", "egrep", "fgrep", "rg", "awk", "sed"]; const FIND_PATTERNS: &[&str] = &["-name", "-iname", "-path", "-ipath", "-wholename", "-regex"]; @@ -111,17 +112,16 @@ pub fn segments(command: &str, dialect: Dialect) -> Vec> { (None, '#') if s.word.is_none() => i += chars[i..].iter().take_while(|next| **next != '\n').count(), (None, '\n') => { s.end_segment(); - // The body runs to its closing line, or to the end if it has none. + // The body runs to its closing line. With none it is no heredoc: `$((1<<2))`. if let Some(delimiter) = s.heredoc.take() { - while i < chars.len() { - let line: String = chars[i..].iter().take_while(|next| **next != '\n').collect(); - i += line.chars().count() + 1; - if line.trim() == delimiter { - break; - } - } + let rest: String = chars[i..].iter().collect(); + let body = rest.split_inclusive('\n').position(|line| line.trim() == delimiter); + let lines = rest.split_inclusive('\n').take(body.map_or(0, |at| at + 1)); + i += lines.map(|line| line.chars().count()).sum::(); } } + // `2>&1` stays in its segment: the `&` after `>` starts no job. + (None, '&') if s.word.is_none() && s.words.last().is_some_and(|w| w == ">") => {} (None, ';' | '|' | '&' | '(' | ')' | '`') => s.end_segment(), (None, '<' | '>') => { s.end_word(); @@ -142,6 +142,13 @@ pub fn segments(command: &str, dialect: Dialect) -> Vec> { pub fn command_paths(command: &str, dialect: Dialect, cwd: &Path, home: Option<&Path>) -> Vec { let mut found = Vec::new(); for words in segments(command, dialect) { + // A shell's `-c` argument and `eval`'s are command lines of their own. + let inner = match words[0].as_str() { + "eval" => words.get(1), + "bash" | "sh" | "zsh" => words.iter().position(|w| w.starts_with('-') && w.ends_with('c')).and_then(|at| words.get(at + 1)), + _ => None, + }; + found.extend(inner.iter().flat_map(|inner| command_paths(inner, dialect, cwd, home))); let (mut args, mut inputs, mut outputs) = (Vec::new(), Vec::new(), Vec::new()); let mut rest = words.iter().map(String::as_str).peekable(); while let Some(word) = rest.next() { @@ -160,9 +167,10 @@ pub fn command_paths(command: &str, dialect: Dialect, cwd: &Path, home: Option<& } } let (verb, named) = named_words(&args); - let classed = inputs.iter().map(|word| (*word, Verb::Prints)); - for (word, verb) in classed.chain(named.iter().chain(&outputs).map(|word| (*word, verb))) { - found.extend(word_paths(word, cwd, home).into_iter().map(|path| CommandPath { path, verb })); + let read = inputs.iter().map(|word| (*word, Verb::Prints, true)); + let written = outputs.iter().map(|word| (*word, verb, true)); + for (word, verb, redirect) in read.chain(named.iter().map(|word| (*word, verb, false))).chain(written) { + found.extend(word_paths(word, redirect, cwd, home).into_iter().map(|path| CommandPath { path, verb })); } } found @@ -178,7 +186,8 @@ fn named_words<'a>(args: &[&'a str]) -> (Verb, Vec<&'a str>) { match word.split_once('=').filter(|(name, _)| is_name(name)) { Some((_, value)) => named.push(value), None if PREFIXES.contains(word) => prefixed = true, - None if prefixed && word.starts_with('-') => {} + // A prefix's flag or number: `nice -n 10 cat`, `timeout 5s cat`. + None if prefixed && word.starts_with(|c: char| c == '-' || c.is_ascii_digit()) => {} None => break, } at += 1; @@ -212,11 +221,12 @@ fn named_words<'a>(args: &[&'a str]) -> (Verb, Vec<&'a str>) { (verb, named) } -/// The paths one word names. A word counts when it is a file or holds a separator; text -/// with spaces and an address hold one too, so they count only as a real file. A glob -/// reaches the files of its one directory and, as in a shell, a dotfile only when it -/// starts with `.`. -fn word_paths(word: &str, cwd: &Path, home: Option<&Path>) -> Vec { +/// The paths one word names. A word counts when it is a file or a `redirect`'s target, +/// or when it holds a separator and is there or may be once the shell expands it: a +/// package, a branch and a host's path hold one too. Text with spaces and an address +/// count only as a real file. A glob reaches the files of its one directory and, as in +/// a shell, a dotfile only when it starts with `.`. +fn word_paths(word: &str, redirect: bool, cwd: &Path, home: Option<&Path>) -> Vec { let expanded = home .and_then(|home| Some(home.join(["~/", "$HOME/", "${HOME}/"].iter().find_map(|p| word.strip_prefix(p))?))) .map_or_else(|| word.to_string(), |path| path.to_string_lossy().into_owned()); @@ -236,5 +246,6 @@ fn word_paths(word: &str, cwd: &Path, home: Option<&Path>) -> Vec { } let path = absolute(Path::new(&expanded), cwd); let prose = word.contains(char::is_whitespace) || word.contains("://"); - if path.is_file() || (word.contains('/') && !prose) { vec![path] } else { Vec::new() } + let reached = redirect || path.exists() || word.contains(['$', '*', '?']); + if path.is_file() || (word.contains('/') && !prose && reached) { vec![path] } else { Vec::new() } } diff --git a/src/core/policy.rs b/src/core/policy.rs index cbfc2fc..e3884a5 100644 --- a/src/core/policy.rs +++ b/src/core/policy.rs @@ -3,7 +3,7 @@ use crate::core::decision::{Decision, Reason, Rule}; use crate::core::op::Op; 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 crate::core::secrets::{unmaskable_reason, FileFormat, SecretFileSet}; use std::path::{Path, PathBuf}; use thiserror::Error; @@ -23,11 +23,10 @@ pub struct Policy { write_globs: globset::GlobSet, read_patterns: Vec, write_patterns: Vec, - /// The secret list, if `on_unparsed_read` is `deny` and its patterns compile. + /// The secret list, if `on_unparsed_read` is `deny`. read_gate: Option, /// What `[[file]]` overrides declare a file's format to be. declared_formats: Vec<(PathBuf, FileFormat)>, - files_error: Option, } impl Policy { @@ -37,11 +36,9 @@ impl Policy { // Load policy from .botsecrets (or fermata.toml fallback). // A layer that fails costs only its own rules (fail-open). let config = SecretsConfig::load_or_default(root).0; - let (secret_files, files_error) = match SecretFileSet::compile(&config.files.patterns) { - Ok(files) => (Some(files), None), - Err(e) => (None, Some(e)), - }; - let read_gate = secret_files.filter(|_| config.enforcement.on_unparsed_read == GuardAction::Deny); + // A pattern that does not compile costs only itself: `bad_patterns` names it for the hooks. + let usable = |patterns: &[String]| patterns.iter().filter(|p| globset::Glob::new(p).is_ok()).cloned().collect::>(); + let read_gate = SecretFileSet::compile(&config.usable_file_patterns()).ok().filter(|_| config.enforcement.on_unparsed_read == GuardAction::Deny); let declared_formats = config .file_overrides .iter() @@ -50,10 +47,10 @@ impl Policy { let policy = config.policy.unwrap_or_default(); let (read_globs, read_patterns) = compile_globs( - policy.read.as_ref().map(|r| r.patterns.as_slice()).unwrap_or(&[]), + &usable(policy.read.as_ref().map(|r| r.patterns.as_slice()).unwrap_or(&[])), )?; let (write_globs, write_patterns) = compile_globs( - policy.write.as_ref().map(|r| r.patterns.as_slice()).unwrap_or(&[]), + &usable(policy.write.as_ref().map(|r| r.patterns.as_slice()).unwrap_or(&[])), )?; Ok(Self { @@ -66,16 +63,9 @@ impl Policy { write_patterns, read_gate, declared_formats, - files_error, }) } - /// Why the `[files]` patterns cannot be used. The rules still hold, the read gate - /// is off, and the hook decides what to say. - pub fn files_error(&self) -> Option<&ManifestError> { - self.files_error.as_ref() - } - pub fn check_command(&self, command: &str) -> Result { let bash = match self.policy.bash.as_ref() { Some(b) => b, @@ -225,10 +215,9 @@ impl Policy { fn match_command(command: &str, patterns: &[String]) -> Result, PolicyError> { for pat in patterns { if is_glob(pat) { - let g = globset::Glob::new(pat) - .map_err(|e| PolicyError::BadPattern(e.to_string()))? - .compile_matcher(); - if g.is_match(command) { + // A bad pattern costs only itself: see `SecretsConfig::bad_patterns`. + let Ok(glob) = globset::Glob::new(pat) else { continue }; + if glob.compile_matcher().is_match(command) { return Ok(Some(pat.clone())); } } else if command.contains(pat.as_str()) { diff --git a/src/core/secrets/config.rs b/src/core/secrets/config.rs index afd54f8..7527004 100644 --- a/src/core/secrets/config.rs +++ b/src/core/secrets/config.rs @@ -218,6 +218,7 @@ pub(crate) fn default_file_patterns() -> Vec { "config/master.key", "config/credentials/*.key", ".aws/credentials", + "credentials", ".netrc", ".htpasswd", "service-account.json", @@ -602,10 +603,27 @@ impl SecretsConfig { })?; toml::from_str(&text).map_err(|e| SecretsConfigError::Parse { path: path.to_path_buf(), - message: super::parser::toml_message(&e, &text), + message: super::parser::toml_message("config, not TOML or an unknown field,", &e, &text), }) } + /// The globs of `[files]` and `[policy]` that do not compile. While a project stays + /// open each costs only itself; under `deny` the hooks and the channel filter refuse. + pub fn bad_patterns(&self) -> Vec { + let policy = self.policy.as_ref(); + let paths = [Some(&self.files.patterns), policy.and_then(|p| p.read.as_ref()).map(|r| &r.patterns), policy.and_then(|p| p.write.as_ref()).map(|r| &r.patterns)]; + // A command pattern with no glob character is a plain substring. + let commands = policy.and_then(|p| p.bash.as_ref()).into_iter().flat_map(|b| b.deny.iter().chain(&b.ask)).filter(|p| p.contains(['*', '?', '['])); + paths.into_iter().flatten().flatten().chain(commands).filter(|p| Glob::new(p).is_err()).cloned().collect() + } + + /// `[files]` without its bad patterns. With none left the built-in list stands: one + /// typo must not leave a project, or a whole machine, with no list at all. + pub fn usable_file_patterns(&self) -> Vec { + let usable: Vec = self.files.patterns.iter().filter(|p| Glob::new(p).is_ok()).cloned().collect(); + if usable.is_empty() && !self.files.patterns.is_empty() { default_file_patterns() } else { usable } + } + /// Load from a TOML string (useful for testing and embedding). pub fn from_toml(toml_str: &str) -> Result { toml::from_str(toml_str) diff --git a/src/core/secrets/manifest.rs b/src/core/secrets/manifest.rs index f4692ab..7f44796 100644 --- a/src/core/secrets/manifest.rs +++ b/src/core/secrets/manifest.rs @@ -94,7 +94,7 @@ pub enum UnmaskableFile { const SOURCE_EXTENSIONS: &[&str] = &[ "rs", "ts", "tsx", "js", "jsx", "mjs", "cjs", "go", "java", "kt", "rb", "php", "c", "h", "cpp", "hpp", "cs", "swift", "scala", "md", "rst", "html", "css", "vue", "svelte", "tf", "tpl", "j2", "erb", "ex", "exs", "nix", "dart", "lua", "sql", - "xml", "gradle", "groovy", "pl", "zig", "example", "sample", "template", "dist", + "xml", "gradle", "groovy", "pl", "zig", "example", "sample", "template", "dist", "pyi", "mdx", "scss", "less", "ps1", "bat", ]; fn is_source_named_secret(path: &Path) -> bool { @@ -120,8 +120,7 @@ pub fn unmaskable_reason(path: &Path, format: Option) -> Option config.usable_file_patterns(), + ParseErrorAction::Deny => config.files.patterns.clone(), + }; + let discovered = discover_files(&patterns, root)?; // 2. Parse each discovered file. for path in &discovered { diff --git a/src/core/secrets/parser.rs b/src/core/secrets/parser.rs index 4d91dcf..5b84621 100644 --- a/src/core/secrets/parser.rs +++ b/src/core/secrets/parser.rs @@ -50,9 +50,9 @@ fn format_message(format: &str, line: Option) -> String { } /// [`format_message`] for a TOML error over `text`. -pub(crate) fn toml_message(e: &toml::de::Error, text: &str) -> String { +pub(crate) fn toml_message(format: &str, e: &toml::de::Error, text: &str) -> String { let line = e.span().map(|span| text[..span.start.min(text.len())].matches('\n').count() + 1); - format_message("TOML", line) + format_message(format, line) } // --------------------------------------------------------------------------- @@ -189,6 +189,10 @@ pub fn parse_content( source: &Path, ) -> Result, ParseError> { let content = content.strip_prefix('\u{feff}').unwrap_or(content); + // NUL is valid UTF-8: UTF-16 without a BOM would "parse" into keys no filter knows. + if format != FileFormat::OpaqueText && content.contains('\0') { + return Err(ParseError::Format { path: source.to_path_buf(), message: "text holds NUL".into() }); + } match format { FileFormat::Env => parse_env(content, source), FileFormat::Toml => parse_toml(content, source), @@ -270,7 +274,8 @@ fn commented_assignment(line: &str) -> Option<&str> { let (key, value) = assignment.split_once('=')?; let ident = key.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); - let plain = !value.is_empty() && !value.contains(char::is_whitespace); + let unquoted = strip_env_comment(value); + let plain = !unquoted.is_empty() && !unquoted.contains(char::is_whitespace); (ident && (plain || quoted_env_value(value, &[]).is_some())).then_some(assignment) } @@ -591,7 +596,7 @@ fn push_number(entries: &mut Vec, key: &str, text: String, source: fn parse_toml(content: &str, source: &Path) -> Result, ParseError> { let table: toml::Value = content.parse().map_err(|e: toml::de::Error| ParseError::Format { path: source.to_path_buf(), - message: toml_message(&e, content), + message: toml_message("TOML", &e, content), })?; let mut entries = Vec::new(); diff --git a/src/core/secrets/value_class.rs b/src/core/secrets/value_class.rs index 8fb2c47..ff35d27 100644 --- a/src/core/secrets/value_class.rs +++ b/src/core/secrets/value_class.rs @@ -17,20 +17,15 @@ const SETTING_WORDS: &[&str] = &[ "STRATEGY", "BACKEND", "DRIVER", "DOMAIN", "ROLE", "POLICY", "NAME", "USER", "USERNAME", ]; -fn number() -> &'static Regex { +fn number_or_duration() -> &'static Regex { static RE: OnceLock = OnceLock::new(); - RE.get_or_init(|| Regex::new(r"^[+-]?\d+(\.\d+)?$").expect("static pattern")) -} - -fn duration() -> &'static Regex { - static RE: OnceLock = OnceLock::new(); - RE.get_or_init(|| Regex::new(r"^\d+(ms|s|m|h|d|w)$").expect("static pattern")) + RE.get_or_init(|| Regex::new(r"^[+-]?\d+(\.\d+)?$|^\d+(ms|s|m|h|d|w)$").expect("static pattern")) } /// Whether `key = value` is a plain setting, so it makes no manifest entry. /// /// 1. The value is a word of [`PLAIN_WORDS`], quoted or not, also when `explicit`. -/// 2. The value is a number under 6 characters or a duration, also when `explicit`. +/// 2. The value is a number or a duration under 6 characters, also when `explicit`. /// 3. Unless `explicit`, the key's last word (split on `.`, `_`, `-`) is a [`SETTING_WORDS`] entry. /// /// `explicit`: the user's own `keys.include` matched the key, or the value came from a `[[file]]` override. @@ -39,7 +34,7 @@ pub fn is_plain_setting(key: &str, value: &str, explicit: bool) -> bool { if PLAIN_WORDS.iter().any(|word| value.eq_ignore_ascii_case(word)) { return true; } - if (value.len() < 6 && number().is_match(value)) || duration().is_match(value) { + if value.len() < 6 && number_or_duration().is_match(value) { return true; } if explicit { diff --git a/src/harness/claude.rs b/src/harness/claude.rs index 1fd9790..3da9e86 100644 --- a/src/harness/claude.rs +++ b/src/harness/claude.rs @@ -30,7 +30,18 @@ impl HarnessAdapter for ClaudeAdapter { .to_string(); let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null); - let op = tool_op(&tool_name, &tool_input)?; + let op = match tool_name.as_str() { + "Read" => path_op(&tool_input, "file_path", PathKind::Read)?, + // A Grep on a named file is a Read by another name. Without a path it names nothing. + "Grep" if tool_input.get("path").is_some_and(Value::is_string) => path_op(&tool_input, "path", PathKind::Read)?, + "Write" | "Edit" | "MultiEdit" => path_op(&tool_input, "file_path", PathKind::Write)?, + // A WebSocket Monitor (`ws`) has no command: no rule applies, so stay quiet. + "Monitor" if tool_input.get("command").is_none() => return Err(AdapterError::UnsupportedTool("Monitor".into())), + // The three that run a command line. Monitor's lines reach the model with + // no hook between them, so `[policy.bash]` is the only check its command gets. + "Bash" | "PowerShell" | "Monitor" => command_op(&tool_input)?, + other => return Err(AdapterError::UnsupportedTool(other.to_string())), + }; let dialect = if tool_name == "PowerShell" { Dialect::PowerShell } else { Dialect::Posix }; Ok(ToolCall { @@ -89,10 +100,6 @@ impl HarnessAdapter for ClaudeAdapter { Ok(PostToolUsePayload { tool_name, tool_input, tool_response, cwd: payload_cwd(&v) }) } - fn post_tool_op(&self, payload: &PostToolUsePayload) -> Option { - tool_op(&payload.tool_name, &payload.tool_input).ok() - } - fn redact_output(&self, payload: &PostToolUsePayload, redactor: &Redactor) -> OutputEdit { let mut walk = RedactWalk { redactor, tool: &payload.tool_name, mcp: is_mcp(payload), redactions: 0, unmaskable: Vec::new() }; let output = walk.value(&payload.tool_response, None, None, Place::Top); @@ -159,22 +166,6 @@ impl HarnessAdapter for ClaudeAdapter { } } -/// The one mapping from a tool and its input to what it reaches. -fn tool_op(tool: &str, input: &Value) -> Result { - match tool { - "Read" => path_op(input, "file_path", PathKind::Read), - // A Grep on a named file is a Read by another name. Without a path it names nothing. - "Grep" if input.get("path").is_some_and(Value::is_string) => path_op(input, "path", PathKind::Read), - "Write" | "Edit" | "MultiEdit" => path_op(input, "file_path", PathKind::Write), - // A WebSocket Monitor (`ws`) has no command: no rule applies, so stay quiet. - "Monitor" if input.get("command").is_none() => Err(AdapterError::UnsupportedTool("Monitor".into())), - // The three that run a command line. Monitor's lines reach the model with - // no hook between them, so `[policy.bash]` is the only check its command gets. - "Bash" | "PowerShell" | "Monitor" => command_op(input), - other => Err(AdapterError::UnsupportedTool(other.to_string())), - } -} - /// 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 { diff --git a/src/harness/mod.rs b/src/harness/mod.rs index 2443e9d..51fd219 100644 --- a/src/harness/mod.rs +++ b/src/harness/mod.rs @@ -127,10 +127,6 @@ pub trait HarnessAdapter { /// Parse a PostToolUse hook payload (tool name, input, response). fn parse_post_tool_use(&self, input: &[u8]) -> Result; - /// What the finished call reached, as `parse_request` reads it. `None` for a tool the - /// gate has no rules for or an input that names nothing. - fn post_tool_op(&self, payload: &PostToolUsePayload) -> Option; - /// Mask every known secret in the payload's output, in the output's own shape. fn redact_output(&self, payload: &PostToolUsePayload, redactor: &Redactor) -> OutputEdit; diff --git a/tests/cli_bad_patterns.rs b/tests/cli_bad_patterns.rs new file mode 100644 index 0000000..be4964d --- /dev/null +++ b/tests/cli_bad_patterns.rs @@ -0,0 +1,213 @@ +//! A glob that does not compile costs only itself while the project stays open, with a +//! note that names it. Under `on_parse_error = "deny"` it refuses, and the channel filter, +//! which forces `deny`, stays strict. All values are fake. + +use assert_cmd::Command; +use dirigent_fermata::core::secrets::config::ParseErrorAction; +use dirigent_fermata::core::secrets::{Manifest, SecretsConfig}; +use serde_json::{json, Value}; +use std::fs; +use tempfile::TempDir; + +const VALUE: &str = "fake-value-in-the-file"; +const DENY: &str = "[enforcement]\non_parse_error = \"deny\"\n"; + +struct Project { + dir: TempDir, + home: TempDir, +} + +fn project(files: &[(&str, &str)]) -> Project { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join(".git")).unwrap(); + fs::write(dir.path().join(".env"), format!("API_TOKEN={VALUE}\n")).unwrap(); + fs::write(dir.path().join("id_rsa"), "fake key text\n").unwrap(); + fs::write(dir.path().join("safe.txt"), "x").unwrap(); + for (name, content) in files { + fs::write(dir.path().join(name), content).unwrap(); + } + Project { dir, home: tempfile::tempdir().unwrap() } +} + +impl Project { + fn hook(&self, event: &str, payload: Value) -> Value { + let output = Command::cargo_bin("fermata") + .unwrap() + .args(["hook", "--event", event, "--harness", "claude"]) + .current_dir(self.dir.path()) + .env("HOME", self.home.path()) + .write_stdin(payload.to_string()) + .assert() + .success() + .get_output() + .clone(); + assert!(!String::from_utf8_lossy(&output.stderr).contains(VALUE), "stderr quotes the file"); + serde_json::from_slice(&output.stdout).unwrap() + } + + fn pre(&self, tool: &str, input: Value) -> Value { + self.hook("pre-tool-use", json!({"tool_name": tool, "tool_input": input})) + } + + fn read(&self, name: &str) -> Value { + self.pre("Read", json!({"file_path": self.dir.path().join(name)})) + } + + fn bash(&self, command: &str) -> Value { + self.pre("Bash", json!({"command": command})) + } + + fn write(&self, name: &str) -> Value { + self.pre("Write", json!({"file_path": self.dir.path().join(name), "content": "x"})) + } + + fn post_bash(&self, text: &str) -> Value { + let response = json!({"stdout": text, "stderr": "", "interrupted": false, "isImage": false}); + self.hook("post-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "x"}, "tool_response": response})) + } + + fn post_write(&self) -> Value { + self.hook("post-tool-use", json!({"tool_name": "Write", "tool_input": {}, "tool_response": {"type": "create"}})) + } + + /// A value is masked in a command's output, and the note beside it names `pattern`. + fn masks_and_names(&self, pattern: &str) { + let out = self.post_bash(&format!("x {VALUE} y")); + assert!(!out.to_string().contains(VALUE), "{out}"); + assert!(context(&out).contains(pattern), "{out}"); + } +} + +fn context(out: &Value) -> &str { + out["hookSpecificOutput"]["additionalContext"].as_str().unwrap_or_default() +} + +fn denied(out: &Value) -> bool { + out["hookSpecificOutput"]["permissionDecision"] == "deny" +} + +// --------------------------------------------------------------------------- +// [policy.*] +// --------------------------------------------------------------------------- + +/// The other rules, `.botignore` and the read gate all stay on. +#[test] +fn a_bad_policy_read_glob_costs_only_that_pattern() { + let p = project(&[ + (".botsecrets", "[policy.read]\npatterns = [\"a[\", \"blocked.txt\"]\n"), + (".botignore", "ignored.txt\n"), + ("ignored.txt", "x"), + ("blocked.txt", "x"), + ]); + for file in ["id_rsa", "ignored.txt", "blocked.txt"] { + assert!(denied(&p.read(file)), "Read {file}"); + assert!(denied(&p.bash(&format!("cat {file}"))), "cat {file}"); + } + assert_eq!(p.read("safe.txt"), json!({})); + p.masks_and_names("a["); + assert_eq!(p.post_write(), json!({})); +} + +#[test] +fn a_bad_policy_write_glob_costs_only_that_pattern() { + let p = project(&[(".botsecrets", "[policy.write]\npatterns = [\"a[\", \"blocked.txt\"]\n"), (".botignore", "ignored.txt\n")]); + assert!(denied(&p.write("blocked.txt"))); + assert!(denied(&p.write("ignored.txt"))); + assert!(denied(&p.read("id_rsa"))); + assert_eq!(p.write("safe.txt"), json!({})); + p.masks_and_names("a["); +} + +#[test] +fn a_bad_policy_bash_glob_costs_only_that_pattern() { + let p = project(&[(".botsecrets", "[policy.bash]\ndeny = [\"a[\", \"rm -rf\"]\nask = [\"b[\", \"docker\"]\n")]); + assert!(denied(&p.bash("rm -rf x"))); + assert_eq!(p.bash("docker ps")["hookSpecificOutput"]["permissionDecision"], "ask"); + assert_eq!(p.bash("ls"), json!({})); + p.masks_and_names("a["); + p.masks_and_names("b["); +} + +/// A literal command pattern is a substring, whatever a glob would make of it. +#[test] +fn a_literal_command_pattern_is_no_bad_glob() { + let p = project(&[(".botsecrets", &format!("{DENY}[policy.bash]\ndeny = [\"a{{\"]\n"))]); + assert!(denied(&p.bash("run a{ b"))); + assert_eq!(p.bash("ls"), json!({})); +} + +// --------------------------------------------------------------------------- +// [files] +// --------------------------------------------------------------------------- + +#[test] +fn a_bad_files_glob_costs_only_that_pattern() { + let p = project(&[(".botsecrets", "[files]\npatterns = [\"a[\", \".env\", \"id_rsa\"]\n")]); + assert!(denied(&p.read("id_rsa"))); + assert!(denied(&p.bash("cat id_rsa"))); + p.masks_and_names("a["); + assert_eq!(p.post_write(), json!({})); +} + +/// No usable pattern left would mean no list at all, in every project of the machine. +#[test] +fn a_user_global_files_list_with_no_usable_pattern_leaves_the_default_list() { + let p = project(&[]); + let config = p.home.path().join(".config/fermata"); + fs::create_dir_all(&config).unwrap(); + fs::write(config.join(".botsecrets"), "[files]\npatterns = [\"a[\"]\n").unwrap(); + assert!(denied(&p.read("id_rsa"))); + p.masks_and_names("a["); +} + +/// An empty list is what the project asked for. +#[test] +fn an_empty_files_list_stays_empty() { + let p = project(&[(".botsecrets", "[files]\npatterns = []\n")]); + assert_eq!(p.read("id_rsa"), json!({})); + assert_eq!(p.post_bash(&format!("x {VALUE} y")), json!({})); +} + +// --------------------------------------------------------------------------- +// Under `deny` +// --------------------------------------------------------------------------- + +#[test] +fn under_deny_a_bad_glob_refuses_and_names_it() { + for bad in ["[files]\npatterns = [\"a[\", \".env\"]\n", "[policy.read]\npatterns = [\"a[\"]\n", "[policy.write]\npatterns = [\"a[\"]\n", "[policy.bash]\nask = [\"a[\"]\n"] { + let p = project(&[(".botsecrets", &format!("{DENY}{bad}"))]); + for out in [p.read("safe.txt"), p.bash("ls"), p.write("safe.txt")] { + assert!(denied(&out), "{bad}: {out}"); + assert!(out.to_string().contains("a["), "{bad}: {out}"); + } + } + let p = project(&[(".botsecrets", &format!("{DENY}[files]\npatterns = [\"a[\", \".env\"]\n"))]); + let out = p.post_bash("clean"); + assert!(out["hookSpecificOutput"]["updatedToolOutput"].to_string().contains("withheld"), "{out}"); +} + +#[test] +fn fermata_check_exits_2_on_a_bad_glob() { + for bad in ["[files]\npatterns = [\"a[\"]\n", "[policy.read]\npatterns = [\"a[\"]\n", "[policy.bash]\ndeny = [\"a[\"]\n"] { + let p = project(&[(".botsecrets", bad)]); + Command::cargo_bin("fermata") + .unwrap() + .args(["check", "--op", "read", "safe.txt"]) + .current_dir(p.dir.path()) + .env("HOME", p.home.path()) + .assert() + .code(2); + } +} + +/// `Sieve::load` forces `deny`: its manifest refuses a bad pattern, and only an open one skips it. +#[test] +fn a_manifest_skips_a_bad_glob_only_while_open() { + let p = project(&[]); + let mut config = SecretsConfig::from_toml("[files]\npatterns = [\"a[\", \".env\"]\n").unwrap(); + let manifest = Manifest::build(&config, p.dir.path()).unwrap(); + assert!(manifest.entries().iter().any(|e| e.value == VALUE)); + + config.enforcement.on_parse_error = ParseErrorAction::Deny; + assert!(Manifest::build(&config, p.dir.path()).is_err()); +} diff --git a/tests/cli_command_paths.rs b/tests/cli_command_paths.rs index f08ab5a..17d9ba4 100644 --- a/tests/cli_command_paths.rs +++ b/tests/cli_command_paths.rs @@ -229,3 +229,56 @@ fn a_path_in_the_sessions_own_project_stays_as_it_was() { 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}"); + } +} diff --git a/tests/cli_hook_r2_values.rs b/tests/cli_hook_r2_values.rs index ff55efd..91ac27d 100644 --- a/tests/cli_hook_r2_values.rs +++ b/tests/cli_hook_r2_values.rs @@ -97,6 +97,12 @@ fn masked_in_both(files: &[(&str, &str)], read: &str, value: &str) { // Commented `.env` lines // --------------------------------------------------------------------------- +/// A commented line with a comment of its own, as a live line may have. +#[test] +fn a_commented_assignment_with_a_trailing_comment_is_masked() { + masked_in_both(&[(".env", &format!("# API_TOKEN={VALUE} # old\n"))], ".env", VALUE); +} + #[test] fn a_commented_assignment_is_masked() { for line in [ diff --git a/tests/cli_hook_read_gate.rs b/tests/cli_hook_read_gate.rs index 9ca19fe..6e55b81 100644 --- a/tests/cli_hook_read_gate.rs +++ b/tests/cli_hook_read_gate.rs @@ -167,6 +167,13 @@ fn what_can_be_masked_or_is_source_passes() { ("secrets.tpl", "{{ x }}\n".to_string()), ("credentials.example", "API_TOKEN=\n".to_string()), ("secrets.d.ts", "export {};\n".to_string()), + ("secrets.pyi", "def load() -> str: ...\n".to_string()), + ("credentials.pyi", "def load() -> str: ...\n".to_string()), + ("secrets.mdx", "# x\n".to_string()), + ("secrets.scss", "a {}\n".to_string()), + ("secrets.less", "a {}\n".to_string()), + ("secrets.ps1", "Get-Date\n".to_string()), + ("secrets.bat", "echo\n".to_string()), ("notes.txt", "x\n".to_string()), ] { let p = project(setting, &[(name, content.as_bytes())]); @@ -274,20 +281,21 @@ fn the_gate_follows_the_projects_list() { assert!(reason(&p.read("private/notes.txt")).contains("notes.txt")); } -/// A bad `[files]` pattern costs the gate, not the rules beside it, and says so. +/// A `[files]` list with no usable pattern leaves the built-in list, keeps the rules beside +/// it and says so. #[test] -fn a_bad_files_pattern_turns_the_gate_off_and_keeps_the_rules() { +fn a_files_list_with_no_usable_pattern_leaves_the_default_list_and_keeps_the_rules() { let config = "[files]\npatterns = [\"a[\"]\n[policy.read]\npatterns = [\"blocked.txt\"]\n"; let files: &[(&str, &[u8])] = &[(".botignore", b"ignored.txt\n"), ("ignored.txt", b"x"), ("blocked.txt", b"x"), ("id_rsa", b"fake key text")]; let p = project(config, files); - assert_eq!(p.read("id_rsa"), json!({})); + assert!(reason(&p.read("id_rsa")).contains("id_rsa")); assert!(reason(&p.read("ignored.txt")).contains(".botignore")); assert!(reason(&p.read("blocked.txt")).contains("blocked.txt")); assert_eq!(p.check("id_rsa"), 2); let response = json!({"stdout": "x", "stderr": "", "interrupted": false}); let note = p.hook("post-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "x"}, "tool_response": response})); - assert!(note["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("[files]"), "{note}"); + assert!(note["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("a["), "{note}"); assert!(note["hookSpecificOutput"].get("updatedToolOutput").is_none(), "{note}"); // A tool that shows no text pays nothing for it. let quiet = p.hook("post-tool-use", json!({"tool_name": "Write", "tool_input": {}, "tool_response": {"type": "create"}})); diff --git a/tests/cli_hook_secret_formats.rs b/tests/cli_hook_secret_formats.rs index eebeb94..8817623 100644 --- a/tests/cli_hook_secret_formats.rs +++ b/tests/cli_hook_secret_formats.rs @@ -397,3 +397,21 @@ fn a_file_override_can_say_opaque() { let p = project(&format!("{DENY}{config}"), "deploy.bin", BINARY); assert!(!replaced(&p.post_bash(VALUE)), "an opaque file never refuses"); } + +/// A file named `credentials` has a format, so it is on the list at any depth. +#[test] +fn a_file_named_credentials_masks_by_key_at_any_depth() { + for name in ["credentials", "sub/credentials", "sub/.aws/credentials"] { + let p = project("", name, format!("[default]\naws_secret_access_key = {VALUE}\nregion = eu\n").as_bytes()); + assert_eq!(p.pre_read(name), json!({}), "{name}"); + let out = p.post_bash(&format!("x {VALUE} y")); + assert!(!out.to_string().contains(VALUE) && out.to_string().contains(MASK), "{name}: {out}"); + } +} + +/// A binary one cannot be masked, so a Read of it is stopped. +#[test] +fn a_file_named_credentials_that_cannot_be_parsed_is_stopped() { + let p = project("", "credentials", &[0xff, 0xfe, 0x00, 0xc3, 0x28]); + assert_eq!(p.pre_read("credentials")["hookSpecificOutput"]["permissionDecision"], "deny"); +} diff --git a/tests/core_manifest_outbound.rs b/tests/core_manifest_outbound.rs index 2147530..b625da7 100644 --- a/tests/core_manifest_outbound.rs +++ b/tests/core_manifest_outbound.rs @@ -90,6 +90,21 @@ fn mask_entire_file_refuses() { refuses(&[(".botsecrets", b"[[file]]\npath = \"a.txt\"\nmask-entire-file = true\n")]); } +/// UTF-16 with no byte order mark is valid UTF-8 holding NUL: it "parsed" into keys no +/// filter knows. A channel refuses it, as any secret file that cannot be parsed. +#[test] +fn a_utf16_file_with_no_bom_refuses() { + let utf16: Vec = format!("API_TOKEN={VALUE}\n").encode_utf16().flat_map(u16::to_le_bytes).collect(); + refuses(&[(".env", &utf16)]); +} + +/// A file named `credentials` is on the list, so a non-UTF-8 one refuses at any depth. +#[test] +fn a_non_utf8_file_named_credentials_refuses() { + refuses(&[("credentials", BINARY)]); + refuses(&[("sub/credentials", BINARY)]); +} + /// Only `*.tfstate` (JSON) can be broken as text. `*.tfvars`, `.aws/credentials` and /// `secrets.{sh,ini,conf,cfg}` go through the lenient env reader, which accepts any /// UTF-8 text, so for them the new refusal is the non-UTF-8 one. The plan's table says diff --git a/tests/core_paths.rs b/tests/core_paths.rs index 2e8c66e..1506c86 100644 --- a/tests/core_paths.rs +++ b/tests/core_paths.rs @@ -137,12 +137,17 @@ fn a_word_after_an_output_redirect_takes_the_verb_of_its_segment() { // --------------------------------------------------------------------------- #[test] -fn a_word_is_a_path_when_it_is_a_file_or_holds_a_separator() { +fn a_word_is_a_path_when_it_is_a_file_or_holds_a_separator_and_is_there() { check(Posix, &[ ("npm run build", NOTHING), ("cat build", NOTHING), ("cat a-word", NOTHING), - ("cat build/new", &[("build/new", Prints)]), + // What is not there is a package, a branch or a host's path, unless a redirect + // writes it or the shell may expand it. + ("cat build/new", NOTHING), + ("tool > build/new", &[("build/new", Other)]), + ("tool < build/new", &[("build/new", Prints)]), + ("tool $X/new", &[("$X/new", Other)]), ("cat vendor/", &[("vendor", Prints)]), ("cat ~/x", &[("~/x", Prints)]), ("cat $HOME/x", &[("~/x", Prints)]), @@ -150,7 +155,7 @@ fn a_word_is_a_path_when_it_is_a_file_or_holds_a_separator() { ]); // No home known: the text stays as written, under the working directory. let f = fixture(); - let named = command_paths("cat ~/x", Posix, f.cwd.path(), None); + let named = command_paths("cat > ~/x", Posix, f.cwd.path(), None); assert_eq!(named[0].path, f.cwd.path().join("~/x")); } @@ -244,7 +249,7 @@ fn everything_else_is_other() { ("mv .env a-copy", ENV_OTHER), ("rm .env", ENV_OTHER), ("python .env", ENV_OTHER), - ("docker cp .env c:/x", &[(".env", Other), ("c:/x", Other)]), + ("docker cp .env c:/x", ENV_OTHER), ("git add .env", ENV_OTHER), ("git diff .env", ENV_OTHER), ("git", NOTHING), @@ -279,6 +284,33 @@ fn the_verb_comes_after_assignments_and_prefixes() { ]); } +#[test] +fn a_wrapper_is_no_verb_and_its_flag_or_number_neither() { + check(Posix, &[ + ("timeout 5 cat .env", ENV_PRINTS), + ("timeout 5s cat .env", ENV_PRINTS), + ("nice -n 10 cat .env", ENV_PRINTS), + ("ionice -c 2 cat .env", ENV_PRINTS), + ("stdbuf -o0 cat .env", ENV_PRINTS), + ("xargs -n 1 cat .env", ENV_PRINTS), + ("busybox cat .env", ENV_PRINTS), + ("timeout 5 ls .env", ENV_METADATA), + // The named limit: a flag's value that is a word becomes the verb. + ("sudo -u root cat .env", ENV_OTHER), + ]); +} + +#[test] +fn an_early_redirect_stays_in_its_segment() { + check(Posix, &[ + ("cat 2>&1 .env", ENV_PRINTS), + ("cat 1>&2 .env", ENV_PRINTS), + ("cat >&2 .env", ENV_PRINTS), + ("cat .env 2>&1 | ls", ENV_PRINTS), + ("a & cat .env", ENV_PRINTS), + ]); +} + #[test] fn the_verb_word_is_never_a_path() { check(Posix, &[ @@ -365,8 +397,10 @@ fn a_heredoc_body_is_text() { ("cat > a.txt << \"EOF\"\nsee cat .env\nEOF\ncat .env", &[("a.txt", Prints), (".env", Prints)]), ("cat > a.txt <<-EOF\n\tsee cat .env\n\tEOF\ncat .env", &[("a.txt", Prints), (".env", Prints)]), ("git commit -F - <