fix(fermata): the hooks refuse under on_parse_error = "deny", and no error quotes a file

PostToolUse replaced nothing when a secret file or the config failed. Under deny
it now puts a refusal naming the file in place of the output, in the tool's own
shape: Claude Code ignores a replacement that does not match a built-in tool's
schema. PreToolUse answers deny for a config or rules it cannot load or apply.

A config that cannot be loaded leaves the setting unknown: a layer with a line
setting deny counts, a layer whose bytes cannot be read counts as deny, and
anything else stays open as today.

Parse errors keep the format and line number and drop the parser's text.
This commit is contained in:
2026-11-06 23:36:57 +01:00
parent 0dc0b87b9d
commit 969cff212f
13 changed files with 599 additions and 133 deletions
+8
View File
@@ -31,6 +31,14 @@ Developed in this monorepo; planned to be exported as a standalone repo in the f
`dirigent_tools` depends on `dirigent_fermata`, never the reverse. Fermata must remain usable as a standalone hook/MCP without dragging in the in-process ACP tool runtime. `dirigent_tools` depends on `dirigent_fermata`, never the reverse. Fermata must remain usable as a standalone hook/MCP without dragging in the in-process ACP tool runtime.
## Failure behaviour and known limits
- **Hooks fail open, except under `on_parse_error = "deny"`.** With `deny` in effect, PostToolUse replaces the tool output with a refusal naming the file when the config or a secret file cannot be loaded, and PreToolUse answers `deny` when the config or the rules cannot be loaded or applied. A malformed hook payload and a missing working directory stay open: no payload means nothing to render, no directory means no setting to read. `fermata check` does not refuse on a broken config.
- **A config that cannot be read: the setting is unknown.** `SecretsConfig::denies_on_failure` reads the raw bytes of every layer: an uncommented line setting `deny` counts, broken layer or not; without one the hook stays open as for any default root; a layer whose bytes cannot be read counts as `deny`.
- **Withholding depends on the harness.** Claude Code ignores an `updatedToolOutput` that does not match a built-in tool's output schema and then uses the original, so `harness/claude.rs` keeps the object's shape (strings replaced, arrays cut to one item, `type`/`mode` tags kept). A tool whose schema has another enum field can still reject that. PreToolUse does not look at secret files, so the tool has already run.
- **Redaction sees only a string `tool_response`.** Claude Code's built-in tools send objects. Those count as empty and pass unredacted under every setting; only the `deny` failure path above handles them.
- **Errors never quote a file.** `ParseError::Format` and `SecretsConfigError::Parse` keep the format and line number and drop the parser's text, because it can quote the failing line. Patterns (`.botignore`, `[policy]`, `[files]`) can appear in messages: they are not values, and a deny reason names them too.
## Out of scope (v0.2) ## Out of scope (v0.2)
Codex / Gemini hook adapters, MCP server mode, `readonly_only` Bash mode, audit log, filesystem watcher, context taint tracking. Each is a future task with its own plan. Codex / Gemini hook adapters, MCP server mode, `readonly_only` Bash mode, audit log, filesystem watcher, context taint tracking. Each is a future task with its own plan.
+3 -1
View File
@@ -75,7 +75,9 @@ The hook payload is always read from **stdin** as JSON. The response is written
| 0 | Success. The JSON response on stdout tells the harness what to do. | | 0 | Success. The JSON response on stdout tells the harness what to do. |
| 2 | Internal error (unknown harness, unknown event type, stdin read failure) | | 2 | Internal error (unknown harness, unknown event type, stdin read failure) |
Fermata follows a **fail-open** policy for hooks: if the payload cannot be parsed or the policy cannot be loaded, it writes `{}` to stdout and exits 0 so the agent can continue. Errors are reported on stderr. Fermata follows a **fail-open** policy for hooks: if the payload cannot be parsed or the policy cannot be loaded, it writes `{}` to stdout (PreToolUse: an allow) and exits 0 so the agent can continue. Errors are reported on stderr and never quote a file.
The exception is a project that sets `on_parse_error = "deny"`. If the config or a secret file cannot be loaded, `post-tool-use` replaces the tool output with a refusal naming the file; if the config or the rules cannot be loaded or applied, `pre-tool-use` answers deny. See [`on_parse_error`](configuration.md) for what happens when the config itself is the broken file.
**Event types** **Event types**
+6 -2
View File
@@ -173,9 +173,13 @@ Parse error actions:
| Action | Behavior | | Action | Behavior |
|--------|----------| |--------|----------|
| `mask-entire-file` | Treat the entire file content as a secret. Default and safest. | | `mask-entire-file` | Default. Warn on stderr and go on without that file's values: they are not redacted. Masking the whole file is not implemented. |
| `allow` | Skip the unparseable file (secrets may leak). | | `allow` | Skip the unparseable file (secrets may leak). |
| `deny` | Block all access to the file. | | `deny` | The hooks refuse. PostToolUse replaces each tool output with a refusal naming the file, until it parses. |
Messages name the file and the line, never the line's text.
If the config itself cannot be read, the setting is unknown. Any layer with an uncommented line setting `deny` counts, even in a file that does not parse, and PreToolUse then refuses too. A layer whose bytes cannot be read counts as `deny`. Otherwise the hooks stay open.
```toml ```toml
[enforcement] [enforcement]
+1 -1
View File
@@ -58,7 +58,7 @@ fermata does not own this layer. It is provided by your container runtime, VM, o
## Design Principles ## Design Principles
**Fail-open for availability.** A parse error in `.botsecrets`, an unrecognized file format, or a scanner timeout does not block the agent from working. Redaction failures are logged, not fatal. The agent's productivity is not sacrificed for edge-case security failures. **Fail-open for availability.** A parse error in `.botsecrets`, an unrecognized file format, or a scanner timeout does not block the agent from working. Redaction failures are logged, not fatal. The agent's productivity is not sacrificed for edge-case security failures. The exception is a project that sets `on_parse_error = "deny"`: there the hooks refuse instead.
**Zero false negatives for declared secrets.** If a value appears in the secret manifest (loaded from files matched by `.botsecrets`), it will be redacted from every tool output, every time. The Aho-Corasick automaton guarantees this -- it finds all occurrences in a single pass at memory-bandwidth speed. **Zero false negatives for declared secrets.** If a value appears in the secret manifest (loaded from files matched by `.botsecrets`), it will be redacted from every tool output, every time. The Aho-Corasick automaton guarantees this -- it finds all occurrences in a single pass at memory-bandwidth speed.
+113 -90
View File
@@ -1,8 +1,9 @@
use clap::{Parser, Subcommand, ValueEnum}; use clap::{Parser, Subcommand, ValueEnum};
use dirigent_fermata::core::{project::find_project_root, Decision, Op, Policy}; use dirigent_fermata::core::secrets::{config::ParseErrorAction, SecretsConfig};
use dirigent_fermata::core::{project::find_project_root, Decision, Op, Policy, Reason};
use dirigent_fermata::harness::HookEvent; use dirigent_fermata::harness::HookEvent;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::process::ExitCode; use std::process::ExitCode;
#[derive(Parser)] #[derive(Parser)]
@@ -125,7 +126,49 @@ fn run_hook(event_str: &str, harness: &str) -> ExitCode {
} }
} }
/// The refusal text of the failure paths. It names files, never their contents.
const FIX_OR_CHANGE: &str = "and this project sets on_parse_error = \"deny\". Fix the file or change the setting.";
/// `path` as the project knows it.
fn shown_path(path: &Path, root: &Path) -> String {
path.strip_prefix(root).unwrap_or(path).display().to_string()
}
/// What the gate answers when it cannot do its work: a refusal if the project
/// asked for that, else the fail-open allow.
fn gate_failure(root: &Path, what: &str) -> Decision {
if SecretsConfig::denies_on_failure(root) {
Decision::Deny(Reason {
message: format!("[fermata] Tool call refused: {what} {FIX_OR_CHANGE}"),
rule: None,
})
} else {
Decision::Allow
}
}
/// The project's policy, or the decision to give without one. `Policy::load`
/// treats a broken config as no rules, which a project under `deny` did not ask for.
fn gate_policy(root: &Path) -> Result<Policy, Decision> {
if let Err(e) = SecretsConfig::load(root) {
let refused = gate_failure(root, &format!("{} cannot be loaded,", shown_path(e.path(), root)));
if refused.is_blocking() {
eprintln!("fermata: secrets config: {e}");
return Err(refused);
}
}
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,")
})
}
/// Handle a PreToolUse hook event (policy gate). /// Handle a PreToolUse hook event (policy gate).
///
/// Fail-open unless the project sets `on_parse_error = "deny"`: see
/// [`gate_failure`]. With no working directory there is no root and so no setting
/// to read, the same as a path in no project.
fn run_pre_tool_use( fn run_pre_tool_use(
adapter: &dyn dirigent_fermata::harness::HarnessAdapter, adapter: &dyn dirigent_fermata::harness::HarnessAdapter,
buf: &[u8], buf: &[u8],
@@ -142,85 +185,38 @@ fn run_pre_tool_use(
} }
}; };
let check_failed = |root: &Path, e: &dirigent_fermata::core::policy::PolicyError| {
eprintln!("fermata: check error: {e}");
gate_failure(root, "the .botignore or [policy] rules cannot be applied,")
};
let decision = match &call.op { let decision = match &call.op {
ToolOp::Path { path, kind } => { ToolOp::Path { path, kind } => match find_project_root(path) {
let root = match find_project_root(path) { None => Decision::Allow,
Some(r) => r, Some(root) => match gate_policy(&root) {
None => { Err(decision) => decision,
let out = adapter Ok(policy) => {
.render_decision(&call, &Decision::Allow)
.unwrap_or_default();
let _ = std::io::stdout().lock().write_all(&out);
return ExitCode::from(0);
}
};
let policy = match Policy::load(&root) {
Ok(p) => p,
Err(e) => {
eprintln!("fermata: load error: {e}");
let out = adapter
.render_decision(&call, &Decision::Allow)
.unwrap_or_default();
let _ = std::io::stdout().lock().write_all(&out);
return ExitCode::from(0);
}
};
let op = match kind { let op = match kind {
PathKind::Read => Op::Read, PathKind::Read => Op::Read,
PathKind::Write => Op::Write, PathKind::Write => Op::Write,
}; };
match policy.check(op, path) { policy.check(op, path).unwrap_or_else(|e| check_failed(&root, &e))
Ok(d) => d,
Err(e) => {
eprintln!("fermata: check error: {e}");
let out = adapter
.render_decision(&call, &Decision::Allow)
.unwrap_or_default();
let _ = std::io::stdout().lock().write_all(&out);
return ExitCode::from(0);
} }
} },
} },
ToolOp::Command { text } => { ToolOp::Command { text } => match std::env::current_dir() {
let cwd = match std::env::current_dir() {
Ok(d) => d,
Err(e) => { Err(e) => {
eprintln!("fermata: cwd error: {e}"); eprintln!("fermata: cwd error: {e}");
let out = adapter Decision::Allow
.render_decision(&call, &Decision::Allow)
.unwrap_or_default();
let _ = std::io::stdout().lock().write_all(&out);
return ExitCode::from(0);
} }
}; Ok(cwd) => match find_project_root(&cwd) {
match find_project_root(&cwd) {
None => Decision::Allow, None => Decision::Allow,
Some(root) => { Some(root) => match gate_policy(&root) {
let policy = match Policy::load(&root) { Err(decision) => decision,
Ok(p) => p, Ok(policy) => policy.check_command(text).unwrap_or_else(|e| check_failed(&root, &e)),
Err(e) => { },
eprintln!("fermata: load error: {e}"); },
let out = adapter },
.render_decision(&call, &Decision::Allow)
.unwrap_or_default();
let _ = std::io::stdout().lock().write_all(&out);
return ExitCode::from(0);
}
};
match policy.check_command(text) {
Ok(d) => d,
Err(e) => {
eprintln!("fermata: check error: {e}");
let out = adapter
.render_decision(&call, &Decision::Allow)
.unwrap_or_default();
let _ = std::io::stdout().lock().write_all(&out);
return ExitCode::from(0);
}
}
}
}
}
}; };
let out = adapter let out = adapter
.render_decision(&call, &decision) .render_decision(&call, &decision)
@@ -231,62 +227,89 @@ fn run_pre_tool_use(
/// Handle a PostToolUse hook event (output redaction). /// Handle a PostToolUse hook event (output redaction).
/// ///
/// Fail-open: any error results in `{}` on stdout and exit 0, so the /// Fail-open: any error results in `{}` on stdout and exit 0, so the harness
/// harness continues with the original output. /// continues with the original output. The exception is a project that sets
/// `on_parse_error = "deny"`: when its secrets cannot be loaded the output is
/// replaced by a refusal that names the file. Nothing printed here quotes a file.
fn run_post_tool_use( fn run_post_tool_use(
adapter: &dyn dirigent_fermata::harness::HarnessAdapter, adapter: &dyn dirigent_fermata::harness::HarnessAdapter,
buf: &[u8], buf: &[u8],
) -> ExitCode { ) -> ExitCode {
use dirigent_fermata::core::secrets::{ use dirigent_fermata::core::secrets::{config::HeuristicMode, Manifest, Redactor, Scanner};
config::HeuristicMode, Manifest, Redactor, Scanner, SecretsConfig,
}; fn pass_through() -> ExitCode {
let _ = std::io::stdout().lock().write_all(b"{}");
ExitCode::from(0)
}
// Parse payload; fail-open on error. // Parse payload; fail-open on error.
let payload = match adapter.parse_post_tool_use(buf) { let payload = match adapter.parse_post_tool_use(buf) {
Ok(p) => p, Ok(p) => p,
Err(e) => { Err(e) => {
eprintln!("fermata: post-tool-use parse: {e}"); eprintln!("fermata: post-tool-use parse: {e}");
let _ = std::io::stdout().lock().write_all(b"{}"); return pass_through();
return ExitCode::from(0);
} }
}; };
// Empty tool response — nothing to redact. // Empty tool response — nothing to redact.
if payload.tool_response.is_empty() { if payload.tool_response.is_empty() && !payload.opaque_response {
let _ = std::io::stdout().lock().write_all(b"{}"); return pass_through();
return ExitCode::from(0);
} }
// Find project root from cwd (PostToolUse has no reliable path). // Find project root from cwd (PostToolUse has no reliable path).
let root = match std::env::current_dir().ok().and_then(|d| find_project_root(&d)) { let root = match std::env::current_dir().ok().and_then(|d| find_project_root(&d)) {
Some(r) => r, Some(r) => r,
None => {
// No project root → nothing to redact, pass through. // No project root → nothing to redact, pass through.
let _ = std::io::stdout().lock().write_all(b"{}"); None => return pass_through(),
return ExitCode::from(0);
}
}; };
// Load secrets config; fail-open if missing or broken. let withhold = |what: String| {
let refusal = format!("[fermata] Tool output withheld: {what} {FIX_OR_CHANGE}");
let out = adapter
.render_post_tool_use_withheld(&payload, &refusal)
.unwrap_or_else(|_| b"{}".to_vec());
let _ = std::io::stdout().lock().write_all(&out);
ExitCode::from(0)
};
// Load secrets config; fail-open if missing or broken, unless it says `deny`.
let config = match SecretsConfig::load(&root) { let config = match SecretsConfig::load(&root) {
Ok(c) => c, Ok(c) => c,
Err(e) => { Err(e) => {
eprintln!("fermata: secrets config: {e}"); eprintln!("fermata: secrets config: {e}");
let _ = std::io::stdout().lock().write_all(b"{}"); if SecretsConfig::denies_on_failure(&root) {
return ExitCode::from(0); return withhold(format!("{} cannot be loaded,", shown_path(e.path(), &root)));
}
return pass_through();
} }
}; };
let deny = config.enforcement.on_parse_error == ParseErrorAction::Deny;
// A response that is not text cannot be redacted here. Only `deny` needs to
// know whether it would have had to be withheld, by building the manifest.
if payload.tool_response.is_empty() && !deny {
return pass_through();
}
// Build manifest from config (discovers .env files etc.). // Build manifest from config (discovers .env files etc.).
let manifest = match Manifest::build(&config, &root) { let manifest = match Manifest::build(&config, &root) {
Ok(m) => m, Ok(m) => m,
Err(e) => { Err(e) => {
eprintln!("fermata: manifest: {e}"); eprintln!("fermata: manifest: {e}");
let _ = std::io::stdout().lock().write_all(b"{}"); if deny {
return ExitCode::from(0); return withhold(match e.path() {
Some(path) => format!("{} cannot be parsed,", shown_path(path, &root)),
None => "the [files] patterns in .botsecrets cannot be used,".to_string(),
});
}
return pass_through();
} }
}; };
if payload.tool_response.is_empty() {
return pass_through();
}
// Run redactor over tool_response. // Run redactor over tool_response.
let redactor = Redactor::new(&manifest, config.redaction.style); let redactor = Redactor::new(&manifest, config.redaction.style);
let redacted = redactor.redact(&payload.tool_response); let redacted = redactor.redact(&payload.tool_response);
+53 -22
View File
@@ -27,11 +27,18 @@ pub enum SecretsConfigError {
path: PathBuf, path: PathBuf,
source: std::io::Error, source: std::io::Error,
}, },
#[error("TOML parse error in {path}: {source}")] /// `message` holds the line number only: `toml`'s own text quotes the line.
Parse { #[error("TOML parse error in {path}: {message}")]
path: PathBuf, Parse { path: PathBuf, message: String },
source: toml::de::Error, }
},
impl SecretsConfigError {
/// The layer that failed.
pub fn path(&self) -> &Path {
match self {
Self::Io { path, .. } | Self::Parse { path, .. } => path,
}
}
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -474,6 +481,13 @@ fn user_config_dir() -> Option<PathBuf> {
} }
} }
/// Whether a text that may not parse has an uncommented line setting
/// `on_parse_error` to `deny`, in any of TOML's spellings of the key.
fn declares_deny(text: &str) -> bool {
let setting = regex::Regex::new(r#"on_parse_error["']?\s*=\s*["']deny["']"#).expect("valid regex");
text.lines().any(|line| !line.trim_start().starts_with('#') && setting.is_match(line))
}
impl SecretsConfig { impl SecretsConfig {
/// Load `.botsecrets` configuration for a project. /// Load `.botsecrets` configuration for a project.
/// ///
@@ -484,35 +498,52 @@ impl SecretsConfig {
/// 4. `<root>/.botsecrets.local` /// 4. `<root>/.botsecrets.local`
pub fn load(root: &Path) -> Result<Self, SecretsConfigError> { pub fn load(root: &Path) -> Result<Self, SecretsConfigError> {
let mut config = Self::default(); let mut config = Self::default();
for file in Self::layer_files(root) {
config.merge_layer(Self::read_partial(&file)?);
}
Ok(config)
}
/// The layer files that exist for `root`, least specific first.
fn layer_files(root: &Path) -> Vec<PathBuf> {
let mut files = Vec::new();
// Layer 2: user-global // Layer 2: user-global
if let Some(user_dir) = user_config_dir() { if let Some(user_dir) = user_config_dir() {
let user_file = user_dir.join(".botsecrets"); files.push(user_dir.join(".botsecrets"));
if user_file.is_file() {
let layer = Self::read_partial(&user_file)?;
config.merge_layer(layer);
}
} }
// Layer 3: project root (.botsecrets takes priority over fermata.toml) // Layer 3: project root (.botsecrets takes priority over fermata.toml)
let project_file = root.join(".botsecrets"); let project_file = root.join(".botsecrets");
let fermata_file = root.join("fermata.toml");
if project_file.is_file() { if project_file.is_file() {
let layer = Self::read_partial(&project_file)?; files.push(project_file);
config.merge_layer(layer); } else {
} else if fermata_file.is_file() { files.push(root.join("fermata.toml"));
let layer = Self::read_partial(&fermata_file)?;
config.merge_layer(layer);
} }
// Layer 4: local overrides // Layer 4: local overrides
let local_file = root.join(".botsecrets.local"); files.push(root.join(".botsecrets.local"));
if local_file.is_file() {
let layer = Self::read_partial(&local_file)?; files.retain(|f| f.is_file());
config.merge_layer(layer); files
} }
Ok(config) /// Whether a hook must refuse when it cannot do its work for `root`: the
/// effective `on_parse_error` is `deny`.
///
/// When a layer cannot be loaded the setting is unknown. A layer whose bytes
/// can be read still says what it meant: any layer with a line setting `deny`
/// counts, broken or not (a typo elsewhere must not turn off the owner's
/// choice), and without one the hook stays open as for any default root. A
/// layer whose bytes cannot be read may say anything, so it counts as `deny`.
pub fn denies_on_failure(root: &Path) -> bool {
match Self::load(root) {
Ok(config) => config.enforcement.on_parse_error == ParseErrorAction::Deny,
Err(_) => Self::layer_files(root).iter().any(|file| match std::fs::read(file) {
Ok(bytes) => declares_deny(&String::from_utf8_lossy(&bytes)),
Err(_) => true,
}),
}
} }
/// Parse a single `.botsecrets` file into a partial layer. /// Parse a single `.botsecrets` file into a partial layer.
@@ -523,7 +554,7 @@ impl SecretsConfig {
})?; })?;
toml::from_str(&text).map_err(|e| SecretsConfigError::Parse { toml::from_str(&text).map_err(|e| SecretsConfigError::Parse {
path: path.to_path_buf(), path: path.to_path_buf(),
source: e, message: super::parser::toml_message(&e, &text),
}) })
} }
+10
View File
@@ -25,6 +25,16 @@ pub enum ManifestError {
Glob(String), Glob(String),
} }
impl ManifestError {
/// The secret file that failed, if a file did (a bad glob is the config's).
pub fn path(&self) -> Option<&Path> {
match self {
Self::Parse(e) => Some(e.path()),
Self::Glob(_) => None,
}
}
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Manifest // Manifest
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
+28 -3
View File
@@ -19,10 +19,35 @@ pub enum ParseError {
path: PathBuf, path: PathBuf,
source: std::io::Error, source: std::io::Error,
}, },
/// `message` names the format and the line, never the line's text: a
/// parser's own message can quote it, and this one reaches logs.
#[error("parse error in {path}: {message}")] #[error("parse error in {path}: {message}")]
Format { path: PathBuf, message: String }, Format { path: PathBuf, message: String },
} }
impl ParseError {
/// The file that failed.
pub fn path(&self) -> &Path {
match self {
Self::Io { path, .. } | Self::Format { path, .. } => path,
}
}
}
/// `invalid <format> at line <n>`, the only text kept of a parser's error.
fn format_message(format: &str, line: Option<usize>) -> String {
match line {
Some(line) => format!("invalid {format} at line {line}"),
None => format!("invalid {format}"),
}
}
/// [`format_message`] for a TOML error over `text`.
pub(crate) fn toml_message(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)
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Types // Types
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -218,7 +243,7 @@ fn strip_env_value(raw: &str) -> String {
fn parse_toml(content: &str, source: &Path) -> Result<Vec<SecretEntry>, ParseError> { fn parse_toml(content: &str, source: &Path) -> Result<Vec<SecretEntry>, ParseError> {
let table: toml::Value = content.parse().map_err(|e: toml::de::Error| ParseError::Format { let table: toml::Value = content.parse().map_err(|e: toml::de::Error| ParseError::Format {
path: source.to_path_buf(), path: source.to_path_buf(),
message: e.to_string(), message: toml_message(&e, content),
})?; })?;
let mut entries = Vec::new(); let mut entries = Vec::new();
@@ -273,7 +298,7 @@ fn parse_json(content: &str, source: &Path) -> Result<Vec<SecretEntry>, ParseErr
let value: serde_json::Value = let value: serde_json::Value =
serde_json::from_str(content).map_err(|e| ParseError::Format { serde_json::from_str(content).map_err(|e| ParseError::Format {
path: source.to_path_buf(), path: source.to_path_buf(),
message: e.to_string(), message: format_message("JSON", Some(e.line())),
})?; })?;
let mut entries = Vec::new(); let mut entries = Vec::new();
@@ -328,7 +353,7 @@ fn parse_yaml(content: &str, source: &Path) -> Result<Vec<SecretEntry>, ParseErr
let value: serde_yaml::Value = let value: serde_yaml::Value =
serde_yaml::from_str(content).map_err(|e| ParseError::Format { serde_yaml::from_str(content).map_err(|e| ParseError::Format {
path: source.to_path_buf(), path: source.to_path_buf(),
message: e.to_string(), message: format_message("YAML", e.location().map(|l| l.line())),
})?; })?;
let mut entries = Vec::new(); let mut entries = Vec::new();
+59 -5
View File
@@ -72,15 +72,14 @@ impl HarnessAdapter for ClaudeAdapter {
.ok_or_else(|| AdapterError::Parse("missing tool_name".into()))? .ok_or_else(|| AdapterError::Parse("missing tool_name".into()))?
.to_string(); .to_string();
let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null); let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null);
let tool_response = v let response = v.get("tool_response").unwrap_or(&Value::Null);
.get("tool_response") let tool_response = response.as_str().unwrap_or("").to_string();
.and_then(|x| x.as_str()) let opaque_response = !response.is_null() && !response.is_string();
.unwrap_or("")
.to_string();
Ok(PostToolUsePayload { Ok(PostToolUsePayload {
tool_name, tool_name,
tool_input, tool_input,
tool_response, tool_response,
opaque_response,
raw: v, raw: v,
}) })
} }
@@ -103,6 +102,61 @@ impl HarnessAdapter for ClaudeAdapter {
}; };
Ok(serde_json::to_vec(&out)?) Ok(serde_json::to_vec(&out)?)
} }
/// Claude Code ignores an `updatedToolOutput` that does not match a built-in
/// tool's output schema and uses the original, so a built-in tool's object
/// comes back in its own shape with the text taken out. MCP output is not
/// validated and takes the refusal as it is. `additionalContext` says the same
/// beside the result, because a shape can hide the text from the reader.
fn render_post_tool_use_withheld(
&self,
payload: &PostToolUsePayload,
refusal: &str,
) -> Result<Vec<u8>, AdapterError> {
let response = payload.raw.get("tool_response").unwrap_or(&Value::Null);
let updated = if payload.tool_name.starts_with("mcp__") || !response.is_object() {
Value::String(refusal.to_string())
} else {
withheld_shape(response, refusal)
};
let out = json!({
"hookSpecificOutput": {
"hookEventName": "PostToolUse",
"updatedToolOutput": updated,
"additionalContext": refusal,
}
});
Ok(serde_json::to_vec(&out)?)
}
}
/// `value` with every string replaced by `refusal` and every array cut to its
/// first item. Numbers and booleans stay: they are counts and flags the schema
/// requires. So do the short tokens of [`is_schema_tag`]: a schema allows only
/// its own values there.
fn withheld_shape(value: &Value, refusal: &str) -> Value {
match value {
Value::String(_) => Value::String(refusal.to_string()),
Value::Array(items) => Value::Array(items.iter().take(1).map(|v| withheld_shape(v, refusal)).collect()),
Value::Object(map) => Value::Object(
map.iter()
.map(|(key, v)| {
let kept = is_schema_tag(key, v);
(key.clone(), if kept { v.clone() } else { withheld_shape(v, refusal) })
})
.collect(),
),
other => other.clone(),
}
}
/// `type` and `mode` are the enums of Claude Code's built-in tool outputs
/// (`"text"`, `"create"`, `"image/png"`, `"files_with_matches"`).
fn is_schema_tag(key: &str, value: &Value) -> bool {
matches!(key, "type" | "mode")
&& value.as_str().is_some_and(|s| {
s.len() <= 32 && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '/'))
})
} }
fn path_op(tool_input: &Value, kind: PathKind) -> Result<ToolOp, AdapterError> { fn path_op(tool_input: &Value, kind: PathKind) -> Result<ToolOp, AdapterError> {
+13 -1
View File
@@ -50,8 +50,12 @@ pub struct PostToolUsePayload {
pub tool_name: String, pub tool_name: String,
/// The tool input that was originally provided. /// The tool input that was originally provided.
pub tool_input: serde_json::Value, pub tool_input: serde_json::Value,
/// The tool's output text that may contain secrets. /// The tool's output text that may contain secrets. Empty when the harness
/// sent no text: see `opaque_response`.
pub tool_response: String, pub tool_response: String,
/// The harness sent a response that is not plain text, so `tool_response`
/// holds none of it and redaction does not see it.
pub opaque_response: bool,
/// Original raw payload. /// Original raw payload.
pub raw: serde_json::Value, pub raw: serde_json::Value,
} }
@@ -104,6 +108,14 @@ pub trait HarnessAdapter {
payload: &PostToolUsePayload, payload: &PostToolUsePayload,
redacted_output: Option<&str>, redacted_output: Option<&str>,
) -> Result<Vec<u8>, AdapterError>; ) -> Result<Vec<u8>, AdapterError>;
/// Render a PostToolUse response that puts `refusal` in place of the whole
/// tool output, in whatever form this harness accepts as a replacement.
fn render_post_tool_use_withheld(
&self,
payload: &PostToolUsePayload,
refusal: &str,
) -> Result<Vec<u8>, AdapterError>;
} }
#[cfg(feature = "harness-claude")] #[cfg(feature = "harness-claude")]
+265
View File
@@ -0,0 +1,265 @@
//! The hook's failure paths: a project that sets `on_parse_error = "deny"` gets a
//! refusal instead of a pass, every other project stays open, and nothing printed
//! or returned quotes a file that failed.
use assert_cmd::Command;
use serde_json::{json, Value};
use std::fs;
use tempfile::TempDir;
const VALUE: &str = "value-on-the-failing-line";
const BROKEN_TOML: &str = "API_TOKEN = \"value-on-the-failing-line\" broken [\n";
const DENY: &str = "[enforcement]\non_parse_error = \"deny\"\n";
const RESPONSE: &str = "output of the tool, value-on-the-failing-line in it";
/// A project with these files, and a home of its own so that the machine's
/// `~/.config/fermata/.botsecrets` plays no part.
struct Project {
dir: TempDir,
home: TempDir,
}
fn project(files: &[(&str, &str)]) -> Project {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join(".botignore"), "").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, String) {
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();
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(!stderr.contains(VALUE), "stderr quotes the file: {stderr}");
(serde_json::from_slice(&output.stdout).unwrap(), stderr)
}
fn post(&self, response: Value) -> (Value, String) {
self.hook("post-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "x"}, "tool_response": response}))
}
fn pre_read(&self, file: &str) -> Value {
let path = self.dir.path().join(file);
self.hook("pre-tool-use", json!({"tool_name": "Read", "tool_input": {"file_path": path}})).0
}
fn pre_bash(&self) -> Value {
self.hook("pre-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "ls"}})).0
}
}
/// The refusal that replaced a text response.
fn refusal(out: &Value) -> &str {
let text = out["hookSpecificOutput"]["updatedToolOutput"].as_str().unwrap_or_else(|| panic!("not withheld: {out}"));
assert!(text.starts_with("[fermata] Tool output withheld"), "{text}");
assert!(!out.to_string().contains(VALUE), "{out}");
text
}
fn verdict(out: &Value) -> &str {
out["hookSpecificOutput"]["permissionDecision"].as_str().unwrap()
}
fn deny_reason(out: &Value) -> &str {
assert_eq!(verdict(out), "deny", "{out}");
out["hookSpecificOutput"]["permissionDecisionReason"].as_str().unwrap()
}
// ---------------------------------------------------------------------------
// PostToolUse, under `deny`
// ---------------------------------------------------------------------------
#[test]
fn a_discovered_file_that_cannot_be_parsed_withholds_the_output_under_deny() {
let p = project(&[(".botsecrets", DENY), ("secrets.toml", BROKEN_TOML)]);
let (out, _) = p.post(json!(RESPONSE));
assert!(refusal(&out).contains("secrets.toml"), "{out}");
// The control: once it parses, the hook redacts and keeps the rest.
fs::write(p.dir.path().join("secrets.toml"), format!("API_TOKEN = \"{VALUE}\"\n")).unwrap();
let (out, _) = p.post(json!(RESPONSE));
let text = out["hookSpecificOutput"]["updatedToolOutput"].as_str().unwrap();
assert!(text.starts_with("output of the tool") && !text.contains(VALUE), "{text}");
}
#[test]
fn a_file_override_that_cannot_be_parsed_withholds_the_output_under_deny() {
let config = format!("{DENY}[[file]]\npath = \"conf.toml\"\n");
let p = project(&[(".botsecrets", &config), ("conf.toml", BROKEN_TOML)]);
let (out, _) = p.post(json!(RESPONSE));
assert!(refusal(&out).contains("conf.toml"), "{out}");
}
/// Claude Code ignores a replacement that does not match a built-in tool's schema
/// and uses the original, so a plain string would withhold nothing here.
#[test]
fn an_object_response_is_withheld_in_its_own_shape_under_deny() {
// The control: without `deny` an object response is what it was, not looked at.
let p = project(&[("secrets.toml", BROKEN_TOML)]);
assert_eq!(p.post(json!({"stdout": RESPONSE})), (json!({}), String::new()));
let p = project(&[(".botsecrets", DENY), ("secrets.toml", BROKEN_TOML)]);
let (out, _) = p.post(json!({"stdout": RESPONSE, "stderr": "", "interrupted": false, "isImage": false}));
let updated = &out["hookSpecificOutput"]["updatedToolOutput"];
assert!(updated["stdout"].as_str().unwrap().contains("secrets.toml"), "{out}");
assert_eq!((&updated["interrupted"], &updated["isImage"]), (&json!(false), &json!(false)));
assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("secrets.toml"), "{out}");
assert!(!out.to_string().contains(VALUE), "{out}");
let (out, _) = p.post(json!({
"type": "text",
"file": {"filePath": "/p/x", "content": RESPONSE, "numLines": 1, "startLine": 1, "totalLines": 1},
}));
let updated = &out["hookSpecificOutput"]["updatedToolOutput"];
assert_eq!(updated["type"], "text");
assert_eq!(updated["file"]["numLines"], 1);
assert!(updated["file"]["content"].as_str().unwrap().contains("withheld"), "{out}");
assert!(!out.to_string().contains(VALUE), "{out}");
// A list keeps one item, and a value under a tag's name is no tag.
let (out, _) = p.post(json!({"mode": "files_with_matches", "filenames": [VALUE, VALUE], "type": RESPONSE}));
let updated = &out["hookSpecificOutput"]["updatedToolOutput"];
assert_eq!(updated["mode"], "files_with_matches");
assert_eq!(updated["filenames"].as_array().unwrap().len(), 1);
assert!(!out.to_string().contains(VALUE), "{out}");
}
#[test]
fn an_mcp_tools_object_response_is_replaced_whole_under_deny() {
let p = project(&[(".botsecrets", DENY), ("secrets.toml", BROKEN_TOML)]);
let (out, _) = p.hook(
"post-tool-use",
json!({"tool_name": "mcp__x__y", "tool_input": {}, "tool_response": {"type": VALUE, "text": RESPONSE}}),
);
assert!(refusal(&out).contains("secrets.toml"), "{out}");
}
#[test]
fn file_patterns_that_cannot_be_compiled_withhold_the_output_under_deny() {
let config = format!("[files]\npatterns = [\"a[\"]\n{DENY}");
let (out, _) = project(&[(".botsecrets", &config)]).post(json!(RESPONSE));
assert!(refusal(&out).contains(".botsecrets"), "{out}");
}
// ---------------------------------------------------------------------------
// PostToolUse, when the config itself cannot be read
// ---------------------------------------------------------------------------
#[test]
fn a_broken_config_that_says_deny_withholds_the_output() {
let broken = format!("{DENY}{BROKEN_TOML}");
let (out, stderr) = project(&[(".botsecrets", &broken)]).post(json!(RESPONSE));
assert!(refusal(&out).contains(".botsecrets"), "{out}");
assert!(stderr.contains(".botsecrets"), "{stderr}");
// Other spellings, and another layer than the broken one.
let p = project(&[(".botsecrets", BROKEN_TOML), (".botsecrets.local", "enforcement.on_parse_error = 'deny'\n")]);
assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets"));
let p = project(&[(".botsecrets", DENY), (".botsecrets.local", BROKEN_TOML)]);
assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets.local"));
}
/// A config in a user's home counts as the others do.
#[test]
fn a_broken_user_global_config_that_says_deny_withholds_the_output() {
let p = project(&[]);
let dir = p.home.path().join(".config/fermata");
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join(".botsecrets"), format!("{DENY}{BROKEN_TOML}")).unwrap();
assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets"));
}
#[cfg(unix)]
#[test]
fn a_config_whose_bytes_cannot_be_read_withholds_the_output() {
use std::os::unix::fs::PermissionsExt;
let p = project(&[(".botsecrets", "")]);
let file = p.dir.path().join(".botsecrets");
fs::set_permissions(&file, fs::Permissions::from_mode(0o000)).unwrap();
if fs::read(&file).is_ok() {
return; // Running as root: the file cannot be made unreadable.
}
assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets"));
assert_eq!(verdict(&p.pre_bash()), "deny");
}
/// A broken config that does not say `deny` stays open, as it always has. Only the
/// message changes.
#[test]
fn a_broken_config_without_deny_stays_open_and_quotes_nothing() {
for broken in [BROKEN_TOML.to_string(), format!("# on_parse_error = \"deny\"\n{BROKEN_TOML}")] {
let p = project(&[(".botsecrets", &broken)]);
let (out, stderr) = p.post(json!(RESPONSE));
assert_eq!(out, json!({}));
assert!(stderr.contains(".botsecrets") && stderr.contains("line "), "{stderr}");
assert_eq!(verdict(&p.pre_bash()), "allow");
}
}
// ---------------------------------------------------------------------------
// PostToolUse, other settings
// ---------------------------------------------------------------------------
/// `hook` itself asserts that stderr quotes nothing.
#[test]
fn other_settings_stay_open_and_quote_nothing() {
for setting in ["", "[enforcement]\non_parse_error = \"allow\"\n", "[enforcement]\non_parse_error = \"mask-entire-file\"\n"] {
// A discovered file, and a `[[file]]` override.
let config = format!("{setting}[[file]]\npath = \"conf.toml\"\n");
let p = project(&[(".botsecrets", &config), ("secrets.toml", BROKEN_TOML), ("conf.toml", BROKEN_TOML)]);
let (out, stderr) = p.post(json!("no secrets here"));
assert_eq!(out, json!({}), "setting {setting:?}");
assert!(stderr.contains("secrets.toml") && stderr.contains("conf.toml"), "{stderr}");
}
}
// ---------------------------------------------------------------------------
// PreToolUse
// ---------------------------------------------------------------------------
#[test]
fn the_gate_refuses_when_a_config_that_says_deny_is_broken() {
let broken = format!("{DENY}{BROKEN_TOML}");
let p = project(&[(".botsecrets", &broken), ("safe.txt", "")]);
let (read, bash) = (p.pre_read("safe.txt"), p.pre_bash());
for out in [&read, &bash] {
let reason = deny_reason(out);
assert!(reason.contains(".botsecrets") && !reason.contains(VALUE), "{reason}");
}
}
#[test]
fn the_gate_refuses_when_rules_cannot_be_loaded_under_deny() {
let bad_rules = "[policy.read]\npatterns = [\"a[\"]\n";
let p = project(&[(".botsecrets", &format!("{DENY}{bad_rules}")), ("safe.txt", "")]);
assert!(deny_reason(&p.pre_read("safe.txt")).contains("rules"));
assert!(deny_reason(&p.pre_bash()).contains("rules"));
// The control: the same rules with no `deny` stay open.
let p = project(&[(".botsecrets", bad_rules), ("safe.txt", "")]);
assert_eq!(verdict(&p.pre_read("safe.txt")), "allow");
assert_eq!(verdict(&p.pre_bash()), "allow");
}
#[test]
fn the_gate_refuses_when_a_command_rule_cannot_be_applied_under_deny() {
let bad_rules = "[policy.bash]\ndeny = [\"a[\"]\n";
let p = project(&[(".botsecrets", &format!("{DENY}{bad_rules}"))]);
assert!(deny_reason(&p.pre_bash()).contains("rules"));
let p = project(&[(".botsecrets", bad_rules)]);
assert_eq!(verdict(&p.pre_bash()), "allow");
}
+12
View File
@@ -386,3 +386,15 @@ on_parse_error = "allow"
ParseErrorAction::Allow ParseErrorAction::Allow
); );
} }
#[test]
fn a_broken_layer_names_its_line_and_never_quotes_it() {
let dir = tempfile::tempdir().unwrap();
let value = "value-on-the-failing-line";
std::fs::write(dir.path().join(".botsecrets"), format!("ok = 1\nkey = \"{value}\" broken [\n")).unwrap();
let error = SecretsConfig::load(dir.path()).unwrap_err();
let text = error.to_string();
assert!(text.ends_with("invalid TOML at line 2") && !text.contains(value), "{text}");
assert!(!format!("{error:?}").contains(value));
assert_eq!(error.path(), dir.path().join(".botsecrets"));
}
+20
View File
@@ -402,3 +402,23 @@ fn parse_secret_file_with_format_override() {
assert_eq!(entries.len(), 1); assert_eq!(entries.len(), 1);
assert_eq!(entries[0].key, "KEY"); assert_eq!(entries[0].key, "KEY");
} }
// ---------------------------------------------------------------------------
// Errors quote nothing
// ---------------------------------------------------------------------------
#[test]
fn a_format_error_names_the_line_and_never_quotes_it() {
let value = "value-on-the-failing-line";
let cases = [
(FileFormat::Toml, format!("ok = 1\nkey = \"{value}\" broken [\n"), "invalid TOML at line 2"),
(FileFormat::Json, format!("{{\n\"key\": \"{value}\" broken\n}}"), "invalid JSON at line 2"),
(FileFormat::Yaml, format!("ok: 1\nkey: \"{value}\" broken\n"), "invalid YAML at line 2"),
];
for (format, content, expected) in cases {
let error = parse_content(&content, format, Path::new("f")).unwrap_err();
let text = error.to_string();
assert!(text.ends_with(expected) && !text.contains(value), "{format:?}: {text}");
assert!(!format!("{error:?}").contains(value), "{format:?}");
}
}