feat(fermata): a Read of a secret-list file it cannot mask is stopped; Grep with a path is a Read

SecretFileSet is the one answer to "is this a secret file?", for discovery and
Policy. unmaskable_reason says why a listed file cannot be masked. Policy::check
is now check_path_rules plus check_read_gate, so that commands can take the rules
without the gate (2D). on_unparsed_read = "allow" turns the gate off.

One tool-to-op mapping in claude.rs, read by parse_request and post_tool_op. A
Grep with a path is a Read; with none it stays {}.

A [[file]] override with a format gives the gate a parser. A bad [files] glob
costs the gate, not .botignore or [policy]: a note beside text output, exit 2
from fermata check, a refusal under deny. Text holding NUL counts as a failed
parse: UTF-16 without a BOM is valid UTF-8 and would pass as garbage keys.
This commit is contained in:
2026-11-07 01:04:32 +01:00
parent 11328da30f
commit fb7fc80970
9 changed files with 557 additions and 48 deletions
+17 -2
View File
@@ -83,6 +83,10 @@ 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}");
return ExitCode::from(2);
}
let d = match policy.check(op, p) {
Ok(d) => d,
Err(e) => {
@@ -176,11 +180,19 @@ fn gate_policy(root: &Path) -> Result<Policy, Decision> {
return Err(refused);
}
}
Policy::load(root).map_err(|e| {
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,");
if refused.is_blocking() {
return Err(refused);
}
}
Ok(policy)
}
/// Handle a PreToolUse hook event (policy gate).
@@ -331,6 +343,9 @@ fn run_post_tool_use(
None => format!("the [files] patterns in .botsecrets cannot be used, {FIX_OR_CHANGE}"),
});
}
if shows_text {
notes.push("[fermata] The [files] patterns in .botsecrets cannot be used, so no value is masked and the read gate is off.".to_string());
}
return answer(None, &notes);
}
};
+65 -4
View File
@@ -2,7 +2,8 @@ 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::secrets::config::{PolicyConfig, SecretsConfig};
use crate::core::secrets::config::{GuardAction, PolicyConfig, SecretsConfig};
use crate::core::secrets::{unmaskable_reason, FileFormat, ManifestError, SecretFileSet};
use std::path::{Path, PathBuf};
use thiserror::Error;
@@ -22,6 +23,11 @@ pub struct Policy {
write_globs: globset::GlobSet,
read_patterns: Vec<String>,
write_patterns: Vec<String>,
/// The secret list, if `on_unparsed_read` is `deny` and its patterns compile.
read_gate: Option<SecretFileSet>,
/// What `[[file]]` overrides declare a file's format to be.
declared_formats: Vec<(PathBuf, FileFormat)>,
files_error: Option<ManifestError>,
}
impl Policy {
@@ -30,7 +36,18 @@ impl Policy {
// Load policy from .botsecrets (or fermata.toml fallback).
// A layer that fails costs only its own rules (fail-open).
let policy = SecretsConfig::load_or_default(root).0.policy.unwrap_or_default();
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);
let declared_formats = config
.file_overrides
.iter()
.filter_map(|file| Some((absolute(Path::new(&file.path), root), FileFormat::from_hint(file.format.as_deref()?)?)))
.collect();
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(&[]),
@@ -47,9 +64,18 @@ impl Policy {
write_globs,
read_patterns,
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<Decision, PolicyError> {
let bash = match self.policy.bash.as_ref() {
Some(b) => b,
@@ -85,9 +111,44 @@ impl Policy {
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.
/// The path rules and, for a Read, the read gate.
pub fn check(&self, op: Op, path: &Path) -> Result<Decision, PolicyError> {
let decision = self.check_path_rules(op, path)?;
if op == Op::Read && !decision.is_blocking() {
return Ok(self.check_read_gate(path));
}
Ok(decision)
}
/// Stops a Read of an existing file on the secret list that fermata cannot mask.
/// The reason names the file and quotes nothing of it, and it sends the agent to the
/// user, not to the setting: `.botsecrets` is writable by default.
pub fn check_read_gate(&self, path: &Path) -> Decision {
let path = absolute(path, &self.root);
let Some(files) = self.read_gate.as_ref().filter(|_| path.is_file()) else {
return Decision::Allow;
};
let listed = std::iter::once(path.clone()).chain(self.resolved(&path)).find(|p| files.matches(p, &self.root));
let Some(file) = listed else {
return Decision::Allow;
};
let declared = self.declared_formats.iter().find(|(declared, _)| *declared == file).map(|(_, format)| *format);
match unmaskable_reason(&file, declared) {
None => Decision::Allow,
Some(why) => Decision::Deny(Reason {
message: format!(
"[fermata] Read stopped: {} is on the secret list and {}, so its values would reach the model. To read it, ask the user: the setting is [enforcement] on_unparsed_read.",
file.strip_prefix(&self.root).unwrap_or(&file).display(),
why,
),
rule: None,
}),
}
}
/// `.botignore` and `[policy]`. 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_path_rules(&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) {
+95 -30
View File
@@ -6,7 +6,7 @@
use std::path::{Path, PathBuf};
use globset::{Glob, GlobSetBuilder};
use globset::{Glob, GlobSet, GlobSetBuilder};
use thiserror::Error;
use walkdir::WalkDir;
@@ -35,6 +35,97 @@ impl ManifestError {
}
}
// ---------------------------------------------------------------------------
// Which files are on the secret list
// ---------------------------------------------------------------------------
/// The `[files]` patterns, compiled once. The one answer to "is this a secret file?".
#[derive(Debug, Clone)]
pub struct SecretFileSet {
within: GlobSet,
anywhere: GlobSet,
}
impl SecretFileSet {
pub fn compile(patterns: &[String]) -> Result<Self, ManifestError> {
let glob = |pat: &str| Glob::new(pat).map_err(|e| ManifestError::Glob(e.to_string()));
let (mut within, mut anywhere) = (GlobSetBuilder::new(), GlobSetBuilder::new());
for pat in patterns {
within.add(glob(pat)?);
let nested = glob(&format!("**/{pat}"))?;
// `.env` means at the root and below it; `.docker/config.json` only at the root.
if !pat.contains('/') {
within.add(nested.clone());
}
anywhere.add(nested);
}
let build = |set: GlobSetBuilder| set.build().map_err(|e| ManifestError::Glob(e.to_string()));
Ok(Self { within: build(within)?, anywhere: build(anywhere)? })
}
/// Inside `root` a pattern meets the path from the root. Outside it there is no
/// such path to go by, so a pattern meets the end of the path.
pub fn matches(&self, path: &Path, root: &Path) -> bool {
match path.strip_prefix(root) {
Ok(rel) => self.within.is_match(rel),
Err(_) => self.anywhere.is_match(path),
}
}
}
/// Why fermata cannot mask a file on the secret list, in words that fit "`<file>` ...".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum UnmaskableFile {
#[error("has no parser")]
NoParser,
#[error("is a secret as a whole")]
WholeFile,
#[error("cannot be parsed")]
ParseFailed,
#[error("holds lines no value can be read from")]
NothingFound,
#[error("marks its secrets by position, not by key")]
StatePositions,
}
/// Extensions of source code and templates: `secrets.rs` handles secrets and is
/// no list of them. A real secret in one is a named limit.
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",
];
fn is_source_named_secret(path: &Path) -> bool {
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();
(name.starts_with("secrets.") || name.starts_with("credentials."))
&& path.extension().and_then(|e| e.to_str()).is_some_and(|ext| SOURCE_EXTENSIONS.contains(&ext))
}
/// Why a file on the secret list cannot be masked, or `None` if a Read of it may pass.
/// `format` is what a `[[file]]` override declares; without one the name decides.
///
/// Python yields entries only from one kind of line, so a module of functions with none
/// says nothing. A failed parse of text holding `{{` or `{%` is a template, whose values
/// live elsewhere: it passes, and the output carries the note about skipped files.
pub fn unmaskable_reason(path: &Path, format: Option<FileFormat>) -> Option<UnmaskableFile> {
let Some(format) = format.or_else(|| FileFormat::from_path(path)) else {
return (!is_source_named_secret(path)).then_some(UnmaskableFile::NoParser);
};
// NUL is valid UTF-8: UTF-16 without a BOM would "parse" into keys no filter knows.
let Some(text) = std::fs::read_to_string(path).ok().filter(|text| !text.contains('\0')) else {
return Some(UnmaskableFile::ParseFailed);
};
let entries = match parser::parse_content(&text, format, path) {
Ok(entries) => entries,
Err(_) if text.contains("{{") || text.contains("{%") => return None,
Err(_) => return Some(UnmaskableFile::ParseFailed),
};
let is_text = |line: &str| !line.is_empty() && !line.starts_with('#') && !(format == FileFormat::Properties && line.starts_with('!'));
let reads_every_line = matches!(format, FileFormat::Env | FileFormat::Properties);
(reads_every_line && entries.is_empty() && text.lines().map(str::trim).any(is_text)).then_some(UnmaskableFile::NothingFound)
}
// ---------------------------------------------------------------------------
// Manifest
// ---------------------------------------------------------------------------
@@ -281,25 +372,7 @@ fn discover_files(patterns: &[String], root: &Path) -> Result<Vec<PathBuf>, Mani
return Ok(Vec::new());
}
// Compile all patterns into a single GlobSet for efficient matching.
let mut builder = GlobSetBuilder::new();
for pat in patterns {
// `globset` patterns match against the full relative path including
// intermediate directories (e.g. `.docker/config.json`). We add
// both the literal pattern and a `**/` prefixed variant so that
// `.env` matches at the root and `subdir/.env` matches nested.
let glob = Glob::new(pat).map_err(|e| ManifestError::Glob(e.to_string()))?;
builder.add(glob);
// Also match nested occurrences: `**/<pattern>`.
if !pat.contains('/') {
let nested = format!("**/{pat}");
let nested_glob =
Glob::new(&nested).map_err(|e| ManifestError::Glob(e.to_string()))?;
builder.add(nested_glob);
}
}
let glob_set = builder.build().map_err(|e| ManifestError::Glob(e.to_string()))?;
let files = SecretFileSet::compile(patterns)?;
let mut result = Vec::new();
@@ -322,16 +395,8 @@ fn discover_files(patterns: &[String], root: &Path) -> Result<Vec<PathBuf>, Mani
continue;
}
let abs_path = entry.path();
// Match relative path against the glob set.
let rel = match abs_path.strip_prefix(root) {
Ok(r) => r,
Err(_) => continue,
};
if glob_set.is_match(rel) {
result.push(abs_path.to_path_buf());
if files.matches(entry.path(), root) {
result.push(entry.path().to_path_buf());
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ pub mod redactor;
pub mod scanner;
pub use config::{KeyMatcher, SecretsConfig};
pub use manifest::{Manifest, ManifestError};
pub use manifest::{unmaskable_reason, Manifest, ManifestError, SecretFileSet, UnmaskableFile};
pub use parser::{parse_secret_file, FileFormat, ParseError, SecretEntry};
pub use redactor::{RedactedText, Redaction, Redactor};
pub use scanner::{Confidence, Finding, Scanner};
+22 -11
View File
@@ -29,14 +29,7 @@ impl HarnessAdapter for ClaudeAdapter {
.to_string();
let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null);
let op = match tool_name.as_str() {
"Read" => path_op(&tool_input, PathKind::Read)?,
"Write" | "Edit" | "MultiEdit" => path_op(&tool_input, PathKind::Write)?,
// 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 op = tool_op(&tool_name, &tool_input)?;
Ok(ToolCall {
tool_name,
@@ -83,6 +76,10 @@ impl HarnessAdapter for ClaudeAdapter {
Ok(PostToolUsePayload { tool_name, tool_input, tool_response, cwd: payload_cwd(&v) })
}
fn post_tool_op(&self, payload: &PostToolUsePayload) -> Option<ToolOp> {
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);
@@ -149,6 +146,20 @@ 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<ToolOp, AdapterError> {
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),
// 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<PathBuf> {
@@ -491,11 +502,11 @@ fn withheld_shape(value: &Value, key: Option<&str>, refusal: &str) -> Value {
}
}
fn path_op(tool_input: &Value, kind: PathKind) -> Result<ToolOp, AdapterError> {
fn path_op(tool_input: &Value, field: &str, kind: PathKind) -> Result<ToolOp, AdapterError> {
let p = tool_input
.get("file_path")
.get(field)
.and_then(|x| x.as_str())
.ok_or_else(|| AdapterError::Parse("missing tool_input.file_path".into()))?;
.ok_or_else(|| AdapterError::Parse(format!("missing tool_input.{field}")))?;
Ok(ToolOp::Path {
path: PathBuf::from(p),
kind,
+4
View File
@@ -120,6 +120,10 @@ pub trait HarnessAdapter {
/// Parse a PostToolUse hook payload (tool name, input, response).
fn parse_post_tool_use(&self, input: &[u8]) -> Result<PostToolUsePayload, AdapterError>;
/// 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<ToolOp>;
/// Mask every known secret in the payload's output, in the output's own shape.
fn redact_output(&self, payload: &PostToolUsePayload, redactor: &Redactor) -> OutputEdit;
+299
View File
@@ -0,0 +1,299 @@
//! The read gate: a Read of a file on the secret list that fermata cannot mask is
//! stopped under every `on_parse_error`, and `on_unparsed_read = "allow"` turns that off.
//! A Grep with a `path` is a Read. All values are fake.
use assert_cmd::Command;
use dirigent_fermata::core::secrets::{parser::parse_content, FileFormat};
use serde_json::{json, Value};
use std::fs;
use std::path::Path;
use tempfile::TempDir;
const VALUE: &str = "fake-value-in-the-file";
const SETTINGS: [&str; 3] = ["", "[enforcement]\non_parse_error = \"allow\"\n", "[enforcement]\non_parse_error = \"deny\"\n"];
struct Project {
dir: TempDir,
home: TempDir,
}
fn project(botsecrets: &str, files: &[(&str, &[u8])]) -> Project {
let dir = tempfile::tempdir().unwrap();
fs::create_dir(dir.path().join(".git")).unwrap();
fs::write(dir.path().join(".botsecrets"), botsecrets).unwrap();
for (name, content) in files {
let path = dir.path().join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, 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));
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, file: &str) -> Value {
self.pre("Read", json!({"file_path": self.dir.path().join(file)}))
}
fn check(&self, file: &str) -> i32 {
Command::cargo_bin("fermata")
.unwrap()
.args(["check", "--op", "read", file])
.current_dir(self.dir.path())
.env("HOME", self.home.path())
.output()
.unwrap()
.status
.code()
.unwrap()
}
}
fn reason(out: &Value) -> &str {
assert_eq!(out["hookSpecificOutput"]["permissionDecision"], "deny", "{out}");
out["hookSpecificOutput"]["permissionDecisionReason"].as_str().unwrap()
}
/// What each row of the secret list that stays stopped holds. `.tfvars`, `.aws/credentials`
/// and `secrets.sh` get a parser next and leave this list then, so they are not on it.
fn unmaskable_files() -> Vec<(&'static str, Vec<u8>)> {
let private_pem = format!("-----BEGIN PRIVATE KEY-----\n{VALUE}\n-----END PRIVATE KEY-----\n").into_bytes();
vec![
("id_rsa", private_pem.clone()),
("id_ed25519", private_pem.clone()),
("server.pem", private_pem.clone()),
("server.key", private_pem.clone()),
("config/master.key", format!("{VALUE}-with-words and spaces\n").into_bytes()),
("a.p12", b"\x30\x82fake".to_vec()),
("a.pfx", b"\x30\x82fake".to_vec()),
("terraform.tfstate", format!("{{\"outputs\":{{\"db\":{{\"value\":\"{VALUE}\"}}}}}}").into_bytes()),
("x.tfstate", format!("{{\"outputs\":{{\"db\":{{\"value\":\"{VALUE}\"}}}}}}").into_bytes()),
(".netrc", format!("machine x login u password {VALUE}\n").into_bytes()),
(".htpasswd", format!("u:{VALUE}\n").into_bytes()),
("secrets.txt", format!("{VALUE}\n").into_bytes()),
("credentials.bak", format!("{VALUE}\n").into_bytes()),
("secrets.toml~", format!("{VALUE}\n").into_bytes()),
]
}
#[test]
fn a_read_of_a_file_with_no_parser_is_stopped_under_every_on_parse_error() {
for setting in SETTINGS {
for (name, content) in unmaskable_files() {
let p = project(setting, &[(name, &content)]);
let out = p.read(name);
let text = reason(&out);
assert!(text.contains(name), "{name} under {setting:?}: {text}");
assert!(text.contains("on_unparsed_read") && text.contains("ask the user"), "{text}");
assert!(!out.to_string().contains(VALUE), "{out}");
}
}
}
#[test]
fn on_unparsed_read_allow_lets_each_of_them_through() {
for (name, content) in unmaskable_files() {
let p = project("[enforcement]\non_unparsed_read = \"allow\"\n", &[(name, &content)]);
assert_eq!(p.read(name), json!({}), "{name}");
}
}
/// A file with a parser that fails cannot be masked either.
#[test]
fn a_file_that_fails_to_parse_is_stopped() {
for setting in SETTINGS {
for (name, content) in [
(".env.gpg", b"\x85\x02\xff\xfe\x00fake".to_vec()),
(".env", [0xff, 0xfe].into_iter().chain("API_TOKEN=fake-utf16-value\n".encode_utf16().flat_map(u16::to_le_bytes)).collect()),
(".env.local", "API_TOKEN=fake-utf16-value\n".encode_utf16().flat_map(u16::to_le_bytes).collect()),
("secrets.toml", format!("api_token = \"{VALUE}\" broken [\n").into_bytes()),
("credentials.json", format!("{{\n// a comment\n\"api_token\": \"{VALUE}\"}}").into_bytes()),
] {
let p = project(setting, &[(name, &content)]);
let out = p.read(name);
assert!(reason(&out).contains(name), "{out}");
assert!(!out.to_string().contains(VALUE), "{out}");
}
}
}
/// `.env` and properties yield a value from nearly any line, so a file with lines and no
/// entry holds something fermata does not understand. A comment or a blank line is nothing.
#[test]
fn an_env_file_with_lines_and_no_entry_is_stopped_and_an_empty_one_is_not() {
let p = project("", &[(".env", format!("{VALUE} with no sign in it\n").as_bytes())]);
assert!(reason(&p.read(".env")).contains(".env"));
let props = "[files]\npatterns = [\"a.properties\"]\n";
let p = project(props, &[("a.properties", b"=fake-value-with-no-key\n")]);
assert!(reason(&p.read("a.properties")).contains("a.properties"));
for content in ["", "\n\n", "# only a comment\n\n"] {
let p = project("", &[(".env", content.as_bytes())]);
assert_eq!(p.read(".env"), json!({}), "{content:?}");
}
let p = project(props, &[("a.properties", b"! a comment\n# another\n")]);
assert_eq!(p.read("a.properties"), json!({}));
}
/// The files fermata can mask, and source named like a secret file.
#[test]
fn what_can_be_masked_or_is_source_passes() {
for setting in SETTINGS {
for (name, content) in [
(".env", format!("API_TOKEN={VALUE}\n")),
("secrets.toml", format!("api_token = \"{VALUE}\"\n")),
("secrets.rs", "pub fn load() {}\n".to_string()),
("credentials.ts", "export const x = 1;\n".to_string()),
("secrets.tf", "variable \"x\" {}\n".to_string()),
("secrets.tpl", "{{ x }}\n".to_string()),
("credentials.example", "API_TOKEN=\n".to_string()),
("secrets.d.ts", "export {};\n".to_string()),
("notes.txt", "x\n".to_string()),
] {
let p = project(setting, &[(name, content.as_bytes())]);
assert_eq!(p.read(name), json!({}), "{name} under {setting:?}");
}
}
}
/// Python assignments are one kind of line in a source file. A module of functions has
/// none, and that says nothing.
#[test]
fn a_python_file_of_functions_passes() {
let source = "import os\n\ndef load():\n return os.environ[\"X\"]\n";
let p = project("", &[("secrets.py", source.as_bytes())]);
assert_eq!(p.read("secrets.py"), json!({}));
}
const HELM: &str = "{{- if .Values.x }}\napi_token: {{ .Values.t }}\n{{- end }}\n";
/// A template that does not parse holds its values elsewhere. Read passes with the note,
/// because a template can hold a literal value: a named limit.
#[test]
fn a_template_that_does_not_parse_passes_with_the_note() {
assert!(parse_content(HELM, FileFormat::Yaml, Path::new("x")).is_err(), "the fixture must fail to parse");
let json_template = "{\"api_token\": {% if x %}\"a\"{% endif %}}";
assert!(parse_content(json_template, FileFormat::Json, Path::new("x")).is_err(), "the fixture must fail to parse");
for (name, content) in [("templates/secrets.yaml", HELM), ("secrets.yml", HELM), ("credentials.json", json_template)] {
let p = project("", &[(name, content.as_bytes())]);
assert_eq!(p.read(name), json!({}), "{name}");
let path = p.dir.path().join(name);
let out = p.hook(
"post-tool-use",
json!({"tool_name": "Read", "tool_input": {"file_path": path}, "tool_response": {"type": "text", "file": {"filePath": path, "content": content, "numLines": 1, "startLine": 1, "totalLines": 1}}}),
);
assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains(name), "{out}");
}
}
#[test]
fn a_grep_with_a_path_is_a_read() {
let p = project("", &[("id_rsa", b"fake key text"), ("src/a.txt", b"x")]);
let path = p.dir.path().join("id_rsa");
assert!(reason(&p.pre("Grep", json!({"pattern": "x", "path": path}))).contains("id_rsa"));
// A relative path, against the session's directory.
let out = p.hook("pre-tool-use", json!({"tool_name": "Grep", "cwd": p.dir.path(), "tool_input": {"pattern": "x", "path": "id_rsa"}}));
assert!(reason(&out).contains("id_rsa"));
// A directory is no file the gate can judge, and no path is no read of anything named.
assert_eq!(p.pre("Grep", json!({"pattern": "x", "path": p.dir.path().join("src")})), json!({}));
assert_eq!(p.pre("Grep", json!({"pattern": "x"})), json!({}));
// The path rules meet a Grep too.
let p = project("", &[(".botignore", b"src/\n"), ("src/a.txt", b"x")]);
assert!(reason(&p.pre("Grep", json!({"pattern": "x", "path": p.dir.path().join("src/a.txt")}))).contains("botignore"));
}
#[test]
fn the_gate_stops_reads_and_nothing_else() {
let p = project("", &[("id_rsa", b"fake key text")]);
let path = p.dir.path().join("id_rsa");
assert_eq!(p.pre("Write", json!({"file_path": path, "content": "x"})), json!({}));
assert_eq!(p.pre("Edit", json!({"file_path": path, "old_string": "a", "new_string": "b"})), json!({}));
// A file that is not there yet has nothing to show.
assert_eq!(p.read("id_ecdsa"), json!({}));
}
#[cfg(unix)]
#[test]
fn a_link_to_a_file_on_the_list_is_stopped() {
let p = project("", &[("id_rsa", b"fake key text")]);
std::os::unix::fs::symlink(p.dir.path().join("id_rsa"), p.dir.path().join("notes")).unwrap();
assert!(reason(&p.read("notes")).contains("id_rsa"));
}
#[test]
fn a_check_of_the_read_op_meets_the_gate() {
let p = project("", &[("id_rsa", b"fake key text"), ("a.txt", b"x")]);
assert_eq!(p.check("id_rsa"), 1);
assert_eq!(p.check("a.txt"), 0);
}
/// A `[[file]]` override with a format gives the file a parser, and that parser may fail.
#[test]
fn a_file_override_with_a_format_gives_the_gate_a_parser() {
let config = "[[file]]\npath = \"secrets.txt\"\nformat = \"env\"\n";
let p = project(config, &[("secrets.txt", format!("API_TOKEN={VALUE}\n").as_bytes())]);
assert_eq!(p.read("secrets.txt"), json!({}));
let config = "[[file]]\npath = \"secrets.txt\"\nformat = \"json\"\n";
let p = project(config, &[("secrets.txt", format!("api_token = {VALUE}\n").as_bytes())]);
assert!(reason(&p.read("secrets.txt")).contains("secrets.txt"));
// No format means the file's name decides.
let config = "[[file]]\npath = \"secrets.txt\"\n";
let p = project(config, &[("secrets.txt", format!("API_TOKEN={VALUE}\n").as_bytes())]);
assert!(reason(&p.read("secrets.txt")).contains("secrets.txt"));
}
/// The list is the project's own: a file off the list is not stopped, one on it is.
#[test]
fn the_gate_follows_the_projects_list() {
let p = project("[files]\npatterns = [\".env\", \"private/*\"]\n", &[("id_rsa", b"x"), ("private/notes.txt", b"x")]);
assert_eq!(p.read("id_rsa"), json!({}));
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.
#[test]
fn a_bad_files_pattern_turns_the_gate_off_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("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"].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"}}));
assert_eq!(quiet, json!({}));
let p = project(&format!("{config}[enforcement]\non_parse_error = \"deny\"\n"), files);
assert!(reason(&p.read("id_rsa")).contains("[files]"));
assert!(reason(&p.pre("Bash", json!({"command": "ls"}))).contains("[files]"));
}
+28
View File
@@ -373,3 +373,31 @@ fn a_file_override_named_like_an_editors_file_still_refuses_and_a_found_one_does
);
assert!(Manifest::build(&config, dir.path()).is_err());
}
// ---------------------------------------------------------------------------
// The secret list
// ---------------------------------------------------------------------------
/// Inside the root a pattern means what discovery has always taken it to mean. Outside
/// there is no path from the root, so a pattern meets the end of the path.
#[test]
fn the_secret_list_reads_a_path_by_where_it_lies() {
let patterns: Vec<String> = [".env", "*.key", ".docker/config.json"].map(String::from).to_vec();
let set = dirigent_fermata::core::secrets::SecretFileSet::compile(&patterns).unwrap();
let root = std::path::Path::new("/proj");
for (path, listed) in [
("/proj/.env", true),
("/proj/sub/.env", true),
("/proj/a/b.key", true),
("/proj/.docker/config.json", true),
("/proj/sub/.docker/config.json", false),
("/proj/notes.txt", false),
("/other/.env", true),
("/home/x/.docker/config.json", true),
("/other/server.key", true),
("/other/notes.txt", false),
] {
assert_eq!(set.matches(std::path::Path::new(path), root), listed, "{path}");
}
assert!(dirigent_fermata::core::secrets::SecretFileSet::compile(&["a[".to_string()]).is_err());
}
+26
View File
@@ -165,3 +165,29 @@ fn a_payloads_working_directory_is_kept_for_both_events() {
assert_eq!(ClaudeAdapter.parse_request(without).unwrap().cwd, None);
assert_eq!(ClaudeAdapter.parse_post_tool_use(without).unwrap().cwd, None);
}
/// One mapping: a finished call reaches what the same call would before it runs, and a
/// Grep with a path is a Read of that path.
#[test]
fn a_grep_with_a_path_is_a_read_and_post_tool_op_reads_the_same_mapping() {
let post = |tool: &str, input: serde_json::Value| {
let payload = serde_json::json!({"tool_name": tool, "tool_input": input, "tool_response": "x"}).to_string();
ClaudeAdapter.post_tool_op(&ClaudeAdapter.parse_post_tool_use(payload.as_bytes()).unwrap())
};
let read = |p: &str| Some(ToolOp::Path { path: p.into(), kind: PathKind::Read });
let payload = br#"{"tool_name":"Grep","tool_input":{"pattern":"x","path":"src/a"}}"#;
assert_eq!(Some(ClaudeAdapter.parse_request(payload).unwrap().op), read("src/a"));
assert_eq!(post("Grep", serde_json::json!({"pattern": "x", "path": "src/a"})), read("src/a"));
assert_eq!(post("Read", serde_json::json!({"file_path": "/p/a"})), read("/p/a"));
assert_eq!(post("Write", serde_json::json!({"file_path": "/p/a"})), Some(ToolOp::Path { path: "/p/a".into(), kind: PathKind::Write }));
assert_eq!(post("Bash", serde_json::json!({"command": "ls"})), Some(ToolOp::Command { text: "ls".into() }));
// What names nothing: post-hook payloads often carry an empty input.
assert_eq!(post("Grep", serde_json::json!({"pattern": "x"})), None);
assert_eq!(post("Read", serde_json::json!({})), None);
assert_eq!(post("Glob", serde_json::json!({"path": "src"})), None);
let no_path = br#"{"tool_name":"Grep","tool_input":{"pattern":"x"}}"#;
assert!(matches!(ClaudeAdapter.parse_request(no_path), Err(dirigent_fermata::harness::AdapterError::UnsupportedTool(_))));
}