From b69fbf3ae21d9e9028a1a209231dbf67889df834 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabor=20K=C3=B6rber?= Date: Fri, 6 Nov 2026 18:33:34 +0100 Subject: [PATCH] fix(fermata): PostToolUse redacts any response shape, and a refusal fits each tool's schema Built-in tools and normal MCP results send tool_response as an object or an array, which the hook read as empty: nothing was redacted under any setting. The hook now walks any shape, masks every string and returns the same shape. Enum and literal values of Claude Code's output schemas (read from v2.1.314) stay when they match exactly, because a mask there fails the schema and the original is used. A secret that cannot take a mask refuses the output under every setting. Refusals: Bash and Read answer a minimal schema-valid output, others keep their shape with exact enum values only. Also: an unreadable config layer no longer counts as deny, multi-line string spellings of deny count, vim's other swap names and Kate's are editor files, the heuristic warning moves to additionalContext, and PreToolUse answers quietly for tools it has no rules for. --- src/bin/fermata.rs | 150 +++++------ src/core/secrets/config.rs | 10 +- src/core/secrets/manifest.rs | 16 +- src/harness/claude.rs | 342 +++++++++++++++++++++---- src/harness/mod.rs | 44 +++- tests/cli_hook_fail_closed.rs | 72 +++--- tests/cli_hook_post_tool_use.rs | 13 +- tests/cli_hook_redaction.rs | 438 ++++++++++++++++++++++++++++++++ tests/core_secrets_manifest.rs | 2 +- tests/harness_claude.rs | 10 +- 10 files changed, 901 insertions(+), 196 deletions(-) create mode 100644 tests/cli_hook_redaction.rs diff --git a/src/bin/fermata.rs b/src/bin/fermata.rs index 2051814..9adb123 100644 --- a/src/bin/fermata.rs +++ b/src/bin/fermata.rs @@ -127,7 +127,7 @@ 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."; +const FIX_OR_CHANGE: &str = "and on_parse_error = \"deny\" is set. Fix the file or change the setting."; /// `path` as the project knows it. fn shown_path(path: &Path, root: &Path) -> String { @@ -166,19 +166,22 @@ fn gate_policy(root: &Path) -> Result { /// 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 +/// Fail-open unless `on_parse_error = "deny"` is set: see [`gate_failure`]. A tool +/// the gate has no rules for is no failure and answers `{}` quietly: the documented +/// wiring runs this hook for every tool. 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( adapter: &dyn dirigent_fermata::harness::HarnessAdapter, buf: &[u8], ) -> ExitCode { - use dirigent_fermata::harness::{PathKind, ToolOp}; + use dirigent_fermata::harness::{AdapterError, PathKind, ToolOp}; let call = match adapter.parse_request(buf) { Ok(c) => c, Err(e) => { - eprintln!("fermata: parse: {e}"); + if !matches!(e, AdapterError::UnsupportedTool(_)) { + eprintln!("fermata: parse: {e}"); + } // Fail-open: output empty JSON and exit 0. let _ = std::io::stdout().lock().write_all(b"{}"); return ExitCode::from(0); @@ -227,15 +230,17 @@ fn run_pre_tool_use( /// Handle a PostToolUse hook event (output redaction). /// -/// Fail-open: any error results in `{}` on stdout and exit 0, so the harness -/// 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. +/// Fail-open: an error results in `{}` on stdout and exit 0, so the harness +/// continues with the original output. Two exceptions replace the output with a +/// refusal: `on_parse_error = "deny"` when the secrets cannot be loaded, and, under +/// every setting, a secret that sits where it cannot be masked. Nothing printed +/// here quotes a file or a value. fn run_post_tool_use( adapter: &dyn dirigent_fermata::harness::HarnessAdapter, buf: &[u8], ) -> ExitCode { - use dirigent_fermata::core::secrets::{config::HeuristicMode, Manifest, Redactor, Scanner}; + use dirigent_fermata::core::secrets::{Manifest, Redactor}; + use dirigent_fermata::harness::OutputEdit; fn pass_through() -> ExitCode { let _ = std::io::stdout().lock().write_all(b"{}"); @@ -251,8 +256,7 @@ fn run_post_tool_use( } }; - // Empty tool response — nothing to redact. - if payload.tool_response.is_empty() && !payload.opaque_response { + if !payload.has_output() { return pass_through(); } @@ -264,7 +268,7 @@ fn run_post_tool_use( }; let withhold = |what: String| { - let refusal = format!("[fermata] Tool output withheld: {what} {FIX_OR_CHANGE}"); + let refusal = format!("[fermata] Tool output withheld: {what}"); let out = adapter .render_post_tool_use_withheld(&payload, &refusal) .unwrap_or_else(|_| b"{}".to_vec()); @@ -278,19 +282,13 @@ fn run_post_tool_use( Err(e) => { eprintln!("fermata: secrets config: {e}"); if SecretsConfig::denies_on_failure(&root) { - return withhold(format!("{} cannot be loaded,", shown_path(e.path(), &root))); + return withhold(format!("{} cannot be loaded, {FIX_OR_CHANGE}", 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.). let manifest = match Manifest::build(&config, &root) { Ok(m) => m, @@ -298,84 +296,74 @@ fn run_post_tool_use( eprintln!("fermata: manifest: {e}"); if deny { 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(), + Some(path) => format!("{} cannot be parsed, {FIX_OR_CHANGE}", shown_path(path, &root)), + None => format!("the [files] patterns in .botsecrets cannot be used, {FIX_OR_CHANGE}"), }); } return pass_through(); } }; - if payload.tool_response.is_empty() { - return pass_through(); - } - - // Run redactor over tool_response. + // Redact the response in its own shape. let redactor = Redactor::new(&manifest, config.redaction.style); - let redacted = redactor.redact(&payload.tool_response); - - // Run heuristic scanner if enabled. - let mut scanner_warning: Option = None; - if config.heuristic.enabled { - if let Ok(scanner) = Scanner::new(&config.heuristic) { - // Scan the (already redacted) text so we don't re-flag known secrets. - let findings = scanner.scan(&redacted.text); - if !findings.is_empty() { - match config.heuristic.mode { - HeuristicMode::Report => { - // Log to stderr only; do not modify output. - for f in &findings { - eprintln!( - "fermata: heuristic finding [{:?}] {}: {}", - f.confidence, f.pattern_id, f.description - ); - } - } - HeuristicMode::Enforce => { - let descriptions: Vec = findings - .iter() - .map(|f| format!("{} ({})", f.description, f.pattern_id)) - .collect(); - scanner_warning = Some(format!( - "\n[fermata] WARNING: heuristic scan found {} potential secret(s): {}", - findings.len(), - descriptions.join(", ") - )); - } - HeuristicMode::Disabled => {} - } - } + let updated = match adapter.redact_output(&payload, &redactor) { + OutputEdit::Unchanged => None, + OutputEdit::Replaced { output, redactions } => { + eprintln!("fermata: redacted {redactions} secret(s) from {} output", payload.tool_name); + Some(output) } - } - - // Determine whether we need to send back modified output. - let redaction_count = redacted.redactions.len(); - let was_redacted = redaction_count > 0; - let needs_update = was_redacted || scanner_warning.is_some(); - - let output = if needs_update { - let mut text = redacted.text; - if let Some(warning) = scanner_warning { - text.push_str(&warning); + // The harness would reject a masked replacement and use the original. + OutputEdit::Unmaskable { keys } => { + eprintln!("fermata: {} output withheld: a secret cannot be masked", payload.tool_name); + return withhold(format!( + "the value of {} appears in a field of this output that cannot be masked. If that value is a short or common word, change it or leave it out of [files].", + keys.join(", "), + )); } - if was_redacted { - eprintln!( - "fermata: redacted {} secret(s) from {} output", - redaction_count, payload.tool_name - ); - } - Some(text) - } else { - None }; + // Scan what is left, so that known secrets are not flagged again. + let output = updated.as_ref().unwrap_or(&payload.tool_response); + let warning = heuristic_warning(&config, &adapter.output_text(&payload, output)); + let out = adapter - .render_post_tool_use(&payload, output.as_deref()) + .render_post_tool_use(&payload, updated.as_ref(), warning.as_deref()) .unwrap_or_else(|_| b"{}".to_vec()); let _ = std::io::stdout().lock().write_all(&out); ExitCode::from(0) } +/// Run the heuristic scanner if enabled. `report` logs to stderr and changes +/// nothing. `enforce` returns a warning to put beside the output. Neither masks a +/// match, and neither text quotes one. +fn heuristic_warning(config: &SecretsConfig, text: &[&str]) -> Option { + use dirigent_fermata::core::secrets::{config::HeuristicMode, Scanner}; + + if !config.heuristic.enabled || config.heuristic.mode == HeuristicMode::Disabled { + return None; + } + let scanner = Scanner::new(&config.heuristic).ok()?; + let findings: Vec<_> = text.iter().flat_map(|t| scanner.scan(t)).collect(); + if findings.is_empty() { + return None; + } + if config.heuristic.mode == HeuristicMode::Report { + // Log to stderr only; do not modify output. + for f in &findings { + eprintln!("fermata: heuristic finding [{:?}] {}: {}", f.confidence, f.pattern_id, f.description); + } + return None; + } + let mut descriptions: Vec = findings.iter().map(|f| format!("{} ({})", f.description, f.pattern_id)).collect(); + descriptions.sort(); + descriptions.dedup(); + Some(format!( + "[fermata] WARNING: heuristic scan found {} potential secret(s): {}", + findings.len(), + descriptions.join(", ") + )) +} + fn merge_worst(a: Option, b: Decision) -> Decision { let rank = |d: &Decision| match d { Decision::Allow => 0, diff --git a/src/core/secrets/config.rs b/src/core/secrets/config.rs index d3930b3..9b5fc48 100644 --- a/src/core/secrets/config.rs +++ b/src/core/secrets/config.rs @@ -482,9 +482,9 @@ fn user_config_dir() -> Option { } /// 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. +/// `on_parse_error` to `deny`, in any of TOML's spellings of the key and the string. fn declares_deny(text: &str) -> bool { - let setting = regex::Regex::new(r#"on_parse_error["']?\s*=\s*["']deny["']"#).expect("valid regex"); + let setting = regex::Regex::new(r#"on_parse_error["']?\s*=\s*["']{1,3}deny["']{1,3}"#).expect("valid regex"); text.lines().any(|line| !line.trim_start().starts_with('#') && setting.is_match(line)) } @@ -535,13 +535,15 @@ impl SecretsConfig { /// 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`. + /// layer whose bytes cannot be read says nothing, so it does not count: an + /// unreadable `~/.config/fermata/.botsecrets` must not stop every project on + /// the machine. 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, + Err(_) => false, }), } } diff --git a/src/core/secrets/manifest.rs b/src/core/secrets/manifest.rs index 7a9ef80..16deb35 100644 --- a/src/core/secrets/manifest.rs +++ b/src/core/secrets/manifest.rs @@ -53,12 +53,20 @@ pub struct Manifest { const MIN_VALUE_LEN: usize = 4; /// File name endings of the working files editors leave beside what they edit: -/// vim's swap files (`.swp`, then `.swo`, `.swn` when one exists; `.swx` is its -/// write probe) and the `~` backup of vim and emacs. +/// Kate's swap file and the `~` backup of vim and emacs. Vim's swap names are +/// [`is_vim_swap`]. /// /// `.bak`, `.orig` and the like are not here: nothing makes those but a person /// copying a file by hand, and such a copy can hold live values. -const EDITOR_ARTEFACT_SUFFIXES: &[&str] = &[".swp", ".swo", ".swn", ".swx", "~"]; +const EDITOR_ARTEFACT_SUFFIXES: &[&str] = &[".kate-swp", "~"]; + +/// Vim's swap files: `.swp`, then `.swo`, `.swn` and on down to `.swa` when the +/// earlier names exist, and `.swx`, its write probe. +fn is_vim_swap(name: &str) -> bool { + name.rsplit_once('.') + .and_then(|(_, ext)| ext.strip_prefix("sw")) + .is_some_and(|letter| matches!(letter.as_bytes(), [b'a'..=b'p' | b'x'])) +} /// Whether `path` is an editor's working file. /// @@ -73,7 +81,7 @@ const EDITOR_ARTEFACT_SUFFIXES: &[&str] = &[".swp", ".swo", ".swn", ".swx", "~"] fn is_editor_artefact(path: &Path) -> bool { path.file_name() .and_then(|n| n.to_str()) - .is_some_and(|name| EDITOR_ARTEFACT_SUFFIXES.iter().any(|suffix| name.ends_with(suffix))) + .is_some_and(|name| is_vim_swap(name) || EDITOR_ARTEFACT_SUFFIXES.iter().any(|suffix| name.ends_with(suffix))) } /// Directories that are unconditionally skipped during file discovery. diff --git a/src/harness/claude.rs b/src/harness/claude.rs index e9bbe6b..6558faa 100644 --- a/src/harness/claude.rs +++ b/src/harness/claude.rs @@ -5,9 +5,10 @@ //! Stdout is `{"hookSpecificOutput": {...}}` with exit code 0; the JSON //! carries the verdict / updated output. -use super::{AdapterError, HarnessAdapter, PathKind, PostToolUsePayload, ToolCall, ToolOp}; +use super::{AdapterError, HarnessAdapter, OutputEdit, PathKind, PostToolUsePayload, ToolCall, ToolOp}; +use crate::core::secrets::Redactor; use crate::core::Decision; -use serde_json::{json, Value}; +use serde_json::{json, Map, Value}; use std::path::PathBuf; pub struct ClaudeAdapter; @@ -72,40 +73,54 @@ impl HarnessAdapter for ClaudeAdapter { .ok_or_else(|| AdapterError::Parse("missing tool_name".into()))? .to_string(); let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null); - let response = v.get("tool_response").unwrap_or(&Value::Null); - let tool_response = response.as_str().unwrap_or("").to_string(); - let opaque_response = !response.is_null() && !response.is_string(); - Ok(PostToolUsePayload { - tool_name, - tool_input, - tool_response, - opaque_response, - raw: v, - }) + let tool_response = v.get("tool_response").cloned().unwrap_or(Value::Null); + Ok(PostToolUsePayload { tool_name, tool_input, tool_response }) + } + + fn redact_output(&self, payload: &PostToolUsePayload, redactor: &Redactor) -> OutputEdit { + let mut walk = RedactWalk { redactor, mcp: is_mcp(payload), redactions: 0, unmaskable: Vec::new() }; + let output = walk.value(&payload.tool_response, None, None); + if !walk.unmaskable.is_empty() { + walk.unmaskable.sort(); + walk.unmaskable.dedup(); + return OutputEdit::Unmaskable { keys: walk.unmaskable }; + } + if walk.redactions == 0 { + return OutputEdit::Unchanged; + } + OutputEdit::Replaced { output, redactions: walk.redactions } + } + + fn output_text<'a>(&self, payload: &PostToolUsePayload, output: &'a Value) -> Vec<&'a str> { + let mut text = Vec::new(); + collect_text(output, None, None, is_mcp(payload), &mut text); + text } fn render_post_tool_use( &self, _payload: &PostToolUsePayload, - redacted_output: Option<&str>, + updated_output: Option<&Value>, + context: Option<&str>, ) -> Result, AdapterError> { // When there are no changes, return `{}` — Claude Code interprets // an empty object as "use original output, no modifications". - let out = match redacted_output { - Some(text) => json!({ - "hookSpecificOutput": { - "hookEventName": "PostToolUse", - "updatedToolOutput": text, - } - }), - None => json!({}), - }; - Ok(serde_json::to_vec(&out)?) + if updated_output.is_none() && context.is_none() { + return Ok(b"{}".to_vec()); + } + let mut specific = json!({ "hookEventName": "PostToolUse" }); + if let Some(output) = updated_output { + specific["updatedToolOutput"] = output.clone(); + } + if let Some(context) = context { + specific["additionalContext"] = json!(context); + } + Ok(serde_json::to_vec(&json!({ "hookSpecificOutput": specific }))?) } /// 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 + /// tool's output schema and uses the original, so a built-in tool gets a + /// replacement its schema takes: see [`withheld_output`]. 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( @@ -113,16 +128,10 @@ impl HarnessAdapter for ClaudeAdapter { payload: &PostToolUsePayload, refusal: &str, ) -> Result, 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, + "updatedToolOutput": withheld_output(payload, refusal), "additionalContext": refusal, } }); @@ -130,33 +139,254 @@ impl HarnessAdapter for ClaudeAdapter { } } -/// `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(), +fn is_mcp(payload: &PostToolUsePayload) -> bool { + payload.tool_name.starts_with("mcp__") +} + +// --------------------------------------------------------------------------- +// What Claude Code's output schemas fix +// --------------------------------------------------------------------------- + +/// The enum and literal string values of Claude Code's built-in tool outputs, by +/// field name, read from the schemas of v2.1.314 (the `outputSchema` of every +/// built-in tool, and the helpers they use). `type` also holds the MCP content +/// block types, which are no secret either. +/// +/// A built-in's replacement that changes such a value fails `safeParse`, and Claude +/// Code then uses the original output: the whole output would leak. An exact listed +/// value says nothing about a secret, so it stays. Anything else under these names +/// is treated as text. +const SCHEMA_VALUES: &[(&str, &[&str])] = &[ + ("type", &[ + "text", "image", "notebook", "pdf", "parts", "file_unchanged", "create", "update", + "image/jpeg", "image/png", "image/gif", "image/webp", + "audio", "resource", "resource_link", + ]), + ("mediaType", &["image/jpeg", "image/png", "image/gif", "image/webp"]), + ("mode", &["content", "files_with_matches", "count"]), + ("source", &["seeded"]), + ("status", &[ + "completed", "async_launched", "remote_launched", "teammate_spawned", "inline", "forked", + "working", "failed", "cancelled", "modified", "added", "created", "updated", "deleted", + "has_existing", "unavailable", "refreshed", "error", "not_connected", "pending", "in_progress", + ]), + ("kind", &["committed", "amended", "cherry-picked", "choice", "text", "number"]), + ("action", &[ + "merged", "rebased", "created", "edited", "commented", "closed", "reopened", "ready", "draft", + "auto-merge-enabled", "auto-merge-disabled", "keep", "remove", + ]), + ("cell_type", &["code", "markdown"]), + ("outcome", &[ + "ok", "conflict", "missing", "refused", "failed", "not_found", "connected", "not_now", + "no_attempt_yet", "fixed", "skipped", "no_change_needed", + ]), + ("store_kind", &["personal", "project"]), + ("op", &["created", "updated"]), + ("operation", &[ + "goToDefinition", "findReferences", "hover", "documentSymbol", "workspaceSymbol", + "goToImplementation", "prepareCallHierarchy", "incomingCalls", "outgoingCalls", + ]), + ("level", &["low", "medium", "high", "xhigh", "max"]), + ("verdict", &["CONFIRMED", "PLAUSIBLE"]), + ("handback", &["send", "flagged", "withheld"]), + ("unanswered", &["skipped", "replied_in_chat", "dismissed"]), +]; + +/// String fields with a maximum length in those schemas (ReportFindings). +const SCHEMA_MAX_LEN: &[(&str, usize)] = &[("short_summary", 60), ("category", 40)]; + +/// The built-in outputs whose object keys are free text (AskUserQuestion's +/// question -> answer records). Every other key in those schemas is a fixed name. +const RECORD_FIELDS: &[&str] = &["answers", "annotations"]; + +/// Whether this field name holds an enum in some schema, and the values it allows. +fn schema_values(key: Option<&str>) -> Option<&'static [&'static str]> { + let key = key?; + SCHEMA_VALUES.iter().find(|(name, _)| *name == key).map(|(_, values)| *values) +} + +fn is_schema_value(key: Option<&str>, value: &str) -> bool { + schema_values(key).is_some_and(|values| values.contains(&value)) +} + +/// `text` cut to the length the schema allows for this field, if it limits one. +fn fit_schema(key: Option<&str>, text: String) -> String { + match key.and_then(|k| SCHEMA_MAX_LEN.iter().find(|(name, _)| *name == k)) { + Some((_, max)) if text.chars().count() > *max => text.chars().take(*max).collect(), + _ => text, } } -/// `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 is_base64(s: &str) -> bool { + s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'-' | b'_' | b'\r' | b'\n')) +} + +/// Image and document bytes are not text. A short secret can match inside base64 +/// by chance, and masking it there breaks the image and with it the next API +/// request, so these stay: +/// - `base64` of a built-in tool (Read of an image or a PDF). +/// - `data` beside `type: image|audio|base64` (MCP and API content blocks), at +/// least 64 characters of base64, so that a token named `data` is still text. +/// - Bash's `stdout` under `isImage: true` that holds a base64 data URL. +fn is_binary(key: Option<&str>, parent: Option<&Map>, value: &str, mcp: bool) -> bool { + match key { + Some("base64") => !mcp && is_base64(value), + Some("data") => { + value.len() >= 64 + && is_base64(value) + && parent + .and_then(|p| p.get("type")) + .and_then(Value::as_str) + .is_some_and(|t| matches!(t, "image" | "audio" | "base64")) + } + Some("stdout") => { + !mcp && parent.and_then(|p| p.get("isImage")) == Some(&Value::Bool(true)) + && value.strip_prefix("data:image/").and_then(|rest| rest.split_once(";base64,")).is_some_and(|(_, data)| is_base64(data)) + } + _ => false, + } +} + +// --------------------------------------------------------------------------- +// Redacting a response in its own shape +// --------------------------------------------------------------------------- + +/// Walks a tool response and redacts every string, keeping the structure, numbers +/// and booleans. +struct RedactWalk<'a> { + redactor: &'a Redactor, + mcp: bool, + redactions: usize, + /// Keys of the secrets found where a built-in's schema cannot take a mask. + unmaskable: Vec, +} + +impl RedactWalk<'_> { + fn value(&mut self, value: &Value, key: Option<&str>, parent: Option<&Map>) -> Value { + match value { + Value::String(s) => Value::String(self.string(s, key, parent)), + Value::Array(items) => Value::Array(items.iter().map(|v| self.value(v, None, None)).collect()), + Value::Object(map) => { + let free_keys = self.mcp || key.is_some_and(|k| RECORD_FIELDS.contains(&k)); + let mut out = Map::with_capacity(map.len()); + for (k, v) in map { + let walked = self.value(v, Some(k), Some(map)); + out.insert(self.object_key(k, free_keys, &out), walked); + } + Value::Object(out) + } + other => other.clone(), + } + } + + fn string(&mut self, s: &str, key: Option<&str>, parent: Option<&Map>) -> String { + if is_binary(key, parent, s, self.mcp) { + return s.to_string(); + } + let redacted = self.redactor.redact(s); + if !redacted.was_redacted() { + return s.to_string(); + } + // MCP output has no schema: only a content block's `type` is structure. + // `source` is also a notebook cell's text, in the same Read output. + let fixed_field = if self.mcp { key == Some("type") } else { schema_values(key).is_some() && key != Some("source") }; + if fixed_field { + if is_schema_value(key, s) { + return s.to_string(); + } + if !self.mcp { + self.unmaskable.extend(redacted.redactions.iter().map(|r| r.key.clone())); + } + } + self.redactions += redacted.redactions.len(); + fit_schema(key, redacted.text) + } + + /// An MCP result and a built-in's record ([`RECORD_FIELDS`]) take a masked key. + /// Any other key of a built-in is its schema's name, so a secret there cannot + /// be masked without failing the schema, which would let the original through. + fn object_key(&mut self, key: &str, free: bool, taken: &Map) -> String { + let redacted = self.redactor.redact(key); + if !redacted.was_redacted() { + return key.to_string(); + } + if !free { + self.unmaskable.extend(redacted.redactions.iter().map(|r| r.key.clone())); + return key.to_string(); + } + self.redactions += redacted.redactions.len(); + let mut masked = redacted.text.clone(); + let mut n = 1; + while taken.contains_key(&masked) { + n += 1; + masked = format!("{}#{n}", redacted.text); + } + masked + } +} + +/// Every string a scanner should read: not binary data, not fixed schema values. +fn collect_text<'a>( + value: &'a Value, + key: Option<&str>, + parent: Option<&Map>, + mcp: bool, + text: &mut Vec<&'a str>, +) { + match value { + Value::String(s) if !is_binary(key, parent, s, mcp) && !is_schema_value(key, s) => text.push(s), + Value::Array(items) => items.iter().for_each(|v| collect_text(v, None, None, mcp, text)), + Value::Object(map) => { + for (k, v) in map { + text.push(k); + collect_text(v, Some(k), Some(map), mcp, text); + } + } + _ => {} + } +} + +// --------------------------------------------------------------------------- +// Replacing a response with a refusal +// --------------------------------------------------------------------------- + +/// A replacement for the whole response that holds only `refusal`. +/// +/// Bash and Read do not reuse the response at all. Their replacement is the +/// smallest form their schema accepts, so no optional field of the original can +/// make it fail (Bash's `gitOperation`), and no image flag makes the mapper send +/// the refusal to the API as image data (`isImage`, Read's `image` and `pdf`). +/// Other built-ins keep their shape: see [`withheld_shape`]. +fn withheld_output(payload: &PostToolUsePayload, refusal: &str) -> Value { + let response = &payload.tool_response; + if is_mcp(payload) || !(response.is_object() || response.is_array()) { + return Value::String(refusal.to_string()); + } + match payload.tool_name.as_str() { + "Bash" => json!({"stdout": refusal, "stderr": "", "interrupted": false, "isImage": false}), + "Read" => json!({ + "type": "text", + "file": {"filePath": "[fermata]", "content": refusal, "numLines": 1, "startLine": 1, "totalLines": 1}, + }), + _ => withheld_shape(response, None, refusal), + } +} + +/// `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 exact schema values ([`SCHEMA_VALUES`]). Records keyed by free +/// text ([`RECORD_FIELDS`]) are emptied, because their keys are text too. +fn withheld_shape(value: &Value, key: Option<&str>, refusal: &str) -> Value { + match value { + Value::String(s) if is_schema_value(key, s) => value.clone(), + Value::String(_) => Value::String(fit_schema(key, refusal.to_string())), + Value::Array(items) => Value::Array(items.iter().take(1).map(|v| withheld_shape(v, None, refusal)).collect()), + Value::Object(_) if key.is_some_and(|k| RECORD_FIELDS.contains(&k)) => json!({}), + Value::Object(map) => Value::Object( + map.iter().map(|(k, v)| (k.clone(), withheld_shape(v, Some(k), refusal))).collect(), + ), + other => other.clone(), + } } fn path_op(tool_input: &Value, kind: PathKind) -> Result { diff --git a/src/harness/mod.rs b/src/harness/mod.rs index 63dae86..0091043 100644 --- a/src/harness/mod.rs +++ b/src/harness/mod.rs @@ -1,6 +1,7 @@ //! Harness adapter layer. Normalizes harness-specific payloads into //! `core` types and renders `Decision` back to harness wire format. +use crate::core::secrets::Redactor; use crate::core::Decision; use std::path::PathBuf; use thiserror::Error; @@ -50,14 +51,28 @@ pub struct PostToolUsePayload { pub tool_name: String, /// The tool input that was originally provided. pub tool_input: serde_json::Value, - /// The tool's output text that may contain secrets. Empty when the harness - /// sent no text: see `opaque_response`. - 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. - pub raw: serde_json::Value, + /// The tool's output as the harness sent it, in any shape. It may contain + /// secrets. `Null` when the harness sent none. + pub tool_response: serde_json::Value, +} + +impl PostToolUsePayload { + /// Whether there is any output to look at. + pub fn has_output(&self) -> bool { + !self.tool_response.is_null() && self.tool_response != "" + } +} + +/// What redaction does to a tool's output. +#[derive(Debug, Clone, PartialEq)] +pub enum OutputEdit { + /// No secret in it: the original stands. + Unchanged, + /// The same shape with the secrets masked. + Replaced { output: serde_json::Value, redactions: usize }, + /// A secret sits where the harness would reject a masked replacement and use + /// the original. `keys` names the secrets (key names, never values). + Unmaskable { keys: Vec }, } /// Hook event type discriminator. @@ -101,12 +116,19 @@ pub trait HarnessAdapter { /// Parse a PostToolUse hook payload (tool name, input, response). fn parse_post_tool_use(&self, input: &[u8]) -> Result; - /// Render a PostToolUse response. `redacted_output` is the (possibly - /// modified) tool output to send back to the harness. + /// Mask every known secret in the payload's output, in the output's own shape. + fn redact_output(&self, payload: &PostToolUsePayload, redactor: &Redactor) -> OutputEdit; + + /// The strings of `output` that are text, for the heuristic scanner. + fn output_text<'a>(&self, payload: &PostToolUsePayload, output: &'a serde_json::Value) -> Vec<&'a str>; + + /// Render a PostToolUse response: the replacement output if there is one, and + /// a note to show beside the result. Neither means the original stands. fn render_post_tool_use( &self, payload: &PostToolUsePayload, - redacted_output: Option<&str>, + updated_output: Option<&serde_json::Value>, + context: Option<&str>, ) -> Result, AdapterError>; /// Render a PostToolUse response that puts `refusal` in place of the whole diff --git a/tests/cli_hook_fail_closed.rs b/tests/cli_hook_fail_closed.rs index f732c3f..54bd0b3 100644 --- a/tests/cli_hook_fail_closed.rs +++ b/tests/cli_hook_fail_closed.rs @@ -102,37 +102,29 @@ fn a_file_override_that_cannot_be_parsed_withholds_the_output_under_deny() { } /// 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. +/// and uses the original, so a plain string would withhold nothing here. Each tool +/// and shape against its schema: `tests/cli_hook_redaction.rs`. #[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. + // The control: without `deny` the output goes on, with this file's values unknown. let p = project(&[("secrets.toml", BROKEN_TOML)]); - assert_eq!(p.post(json!({"stdout": RESPONSE})), (json!({}), String::new())); + let (out, stderr) = p.post(json!({"stdout": RESPONSE})); + assert_eq!(out, json!({})); + assert!(stderr.contains("secrets.toml"), "{stderr}"); 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 (out, _) = p.hook( + "post-tool-use", + json!({"tool_name": "Grep", "tool_input": {}, "tool_response": {"mode": "files_with_matches", "numFiles": 2, "filenames": [VALUE, VALUE], "type": RESPONSE}}), + ); let updated = &out["hookSpecificOutput"]["updatedToolOutput"]; assert_eq!(updated["mode"], "files_with_matches"); + assert_eq!(updated["numFiles"], 2); + // A list keeps one item, and a value under a tag's name is no tag. assert_eq!(updated["filenames"].as_array().unwrap().len(), 1); + assert!(updated["type"].as_str().unwrap().contains("withheld"), "{out}"); + assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("secrets.toml"), "{out}"); assert!(!out.to_string().contains(VALUE), "{out}"); } @@ -181,20 +173,38 @@ fn a_broken_user_global_config_that_says_deny_withholds_the_output() { assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets")); } +/// A layer whose bytes cannot be read says nothing. It must not stop every project +/// on the machine when it is the user-global one, and another layer's `deny` counts. #[cfg(unix)] #[test] -fn a_config_whose_bytes_cannot_be_read_withholds_the_output() { +fn a_config_whose_bytes_cannot_be_read_says_nothing() { use std::os::unix::fs::PermissionsExt; - let p = project(&[(".botsecrets", "")]); - let file = p.dir.path().join(".botsecrets"); + let p = project(&[]); + let dir = p.home.path().join(".config/fermata"); + fs::create_dir_all(&dir).unwrap(); + let file = dir.join(".botsecrets"); + fs::write(&file, "").unwrap(); 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_eq!(p.post(json!(RESPONSE)).0, json!({})); + assert_eq!(verdict(&p.pre_bash()), "allow"); + + fs::write(p.dir.path().join(".botsecrets"), DENY).unwrap(); assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets")); assert_eq!(verdict(&p.pre_bash()), "deny"); } +/// TOML's multi-line strings are spellings of the setting too. +#[test] +fn a_broken_config_with_a_multi_line_string_deny_withholds_the_output() { + for setting in ["[enforcement]\non_parse_error = \"\"\"deny\"\"\"\n", "[enforcement]\non_parse_error = '''deny'''\n"] { + let broken = format!("{setting}{BROKEN_TOML}"); + assert!(refusal(&project(&[(".botsecrets", &broken)]).post(json!(RESPONSE)).0).contains(".botsecrets")); + } +} + /// A broken config that does not say `deny` stays open, as it always has. Only the /// message changes. #[test] @@ -228,11 +238,13 @@ fn other_settings_stay_open_and_quote_nothing() { /// An editor's file does not take down every tool output of a `deny` project. #[test] fn an_editors_swap_file_does_not_withhold_under_deny() { - let p = project(&[(".botsecrets", DENY), (".env", "API_TOKEN=value-on-the-failing-line\n")]); - fs::write(p.dir.path().join(".env.swp"), b"b0VIM \xff\xfe\x00\x01").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}"); + for name in [".env.swp", ".env.swm", ".env.kate-swp"] { + let p = project(&[(".botsecrets", DENY), (".env", "API_TOKEN=value-on-the-failing-line\n")]); + fs::write(p.dir.path().join(name), b"b0VIM \xff\xfe\x00\x01").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), "{name}: {text}"); + } } // --------------------------------------------------------------------------- diff --git a/tests/cli_hook_post_tool_use.rs b/tests/cli_hook_post_tool_use.rs index 463bff6..1c0c00b 100644 --- a/tests/cli_hook_post_tool_use.rs +++ b/tests/cli_hook_post_tool_use.rs @@ -126,7 +126,7 @@ fn post_tool_use_empty_response_passthrough() { } #[test] -fn post_tool_use_heuristic_enforce_appends_warning() { +fn post_tool_use_heuristic_enforce_warns_beside_the_output() { // Use a config with heuristic in enforce mode (the default). let botsecrets = r#" [files] @@ -159,13 +159,16 @@ mode = "enforce" .clone(); let v: serde_json::Value = serde_json::from_slice(&out).unwrap(); - let updated = v["hookSpecificOutput"]["updatedToolOutput"] + let context = v["hookSpecificOutput"]["additionalContext"] .as_str() - .expect("expected updatedToolOutput with heuristic warning"); + .expect("expected additionalContext with heuristic warning"); assert!( - updated.contains("[fermata] WARNING"), - "expected heuristic warning, got: {updated}" + context.contains("[fermata] WARNING"), + "expected heuristic warning, got: {context}" ); + assert!(!context.contains("ghp_"), "the warning quotes the match: {context}"); + // The warning takes no place in the output: it has no shape to put it in. + assert!(v["hookSpecificOutput"].get("updatedToolOutput").is_none(), "{v}"); } #[test] diff --git a/tests/cli_hook_redaction.rs b/tests/cli_hook_redaction.rs new file mode 100644 index 0000000..9230cc8 --- /dev/null +++ b/tests/cli_hook_redaction.rs @@ -0,0 +1,438 @@ +//! PostToolUse on the shapes Claude Code really sends. Built-in tools send objects, +//! normal MCP results arrays, so a hook that reads only strings redacts nothing. +//! +//! No test here runs Claude Code. `SCHEMAS` is the part of each tool's output schema +//! these payloads touch, read from the bundled source of v2.1.314, and `conforms` +//! stands in for its `safeParse`: a replacement that fails it would be dropped for +//! the original output. + +use assert_cmd::Command; +use serde_json::{json, Value}; +use std::fs; +use tempfile::TempDir; + +const SECRET: &str = "fake-token-4242-abcdef"; +const MASK: &str = "*****"; + +fn project(env: &str, botsecrets: &str) -> (TempDir, TempDir) { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join(".botignore"), "").unwrap(); + fs::write(dir.path().join(".env"), env).unwrap(); + fs::write(dir.path().join(".botsecrets"), botsecrets).unwrap(); + (dir, tempfile::tempdir().unwrap()) +} + +fn hook(p: &(TempDir, TempDir), tool: &str, response: &Value) -> Value { + let output = Command::cargo_bin("fermata") + .unwrap() + .args(["hook", "--event", "post-tool-use", "--harness", "claude"]) + .current_dir(p.0.path()) + .env("HOME", p.1.path()) + .write_stdin(json!({"tool_name": tool, "tool_input": {}, "tool_response": response}).to_string()) + .assert() + .success() + .get_output() + .clone(); + serde_json::from_slice(&output.stdout).unwrap() +} + +fn with_secret() -> (TempDir, TempDir) { + project(&format!("API_TOKEN={SECRET}\n"), "[files]\npatterns = [\".env\"]\n") +} + +/// Real-shaped responses, each with the secret in the text the model would read. +fn payloads() -> Vec<(&'static str, Value)> { + let line = format!("API_TOKEN={SECRET}"); + vec![ + ("Bash", json!({"stdout": format!("token {SECRET}\n"), "stderr": "", "interrupted": false, "isImage": false})), + ("Bash", json!({"stdout": "", "stderr": format!("failed with {SECRET}"), "interrupted": false, "noOutputExpected": false})), + ("Bash", json!({ + "stdout": format!("[main abc] {SECRET}"), "stderr": "", "interrupted": false, + "gitOperation": { + "commit": {"sha": "abc", "kind": "committed", "branch": "main"}, + "branch": {"ref": "main", "action": "merged"}, + "pr": {"number": 7, "url": "https://x/7", "action": "auto-merge-enabled"}, + }, + })), + ("Read", json!({ + "type": "text", + "file": {"filePath": "/p/.env", "content": format!("{line}\n"), "numLines": 1, "startLine": 1, "totalLines": 1}, + })), + ("Grep", json!({"mode": "content", "numFiles": 1, "filenames": [], "content": format!(".env:1:{line}"), "numLines": 1})), + ("Grep", json!({"mode": "files_with_matches", "numFiles": 1, "filenames": [format!("/p/{SECRET}.txt")]})), + ("Glob", json!({"durationMs": 1, "numFiles": 1, "filenames": [format!("/p/{SECRET}.txt")], "truncated": false})), + ("Write", json!({ + "type": "create", "filePath": "/p/x", "content": line, "structuredPatch": [], "originalFile": null, + })), + ("Write", json!({ + "type": "update", "filePath": "/p/x", "content": line, "originalFile": line, + "structuredPatch": [{"oldStart": 1, "oldLines": 1, "newStart": 1, "newLines": 1, "lines": [format!("-{line}"), "+x"]}], + "gitDiff": {"filename": "x", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": format!("-{line}"), "repository": null}, + })), + ("Edit", json!({ + "filePath": "/p/x", "oldString": line, "newString": "x", "originalFile": line, + "structuredPatch": [{"oldStart": 1, "oldLines": 1, "newStart": 1, "newLines": 1, "lines": [format!("-{line}"), "+x"]}], + "userModified": false, "replaceAll": false, + })), + ("WebFetch", json!({"bytes": 1, "code": 200, "codeText": "OK", "result": format!("page says {SECRET}"), "durationMs": 1, "url": "https://x"})), + ("NotebookEdit", json!({ + "new_source": line, "cell_type": "code", "language": "python", "edit_mode": "replace", + "notebook_path": "/p/n.ipynb", "original_file": line, "updated_file": line, + })), + ("Agent", json!({ + "status": "completed", "prompt": "p", "agentId": "a", + "content": [{"type": "text", "text": format!("subagent read {SECRET}")}], + "totalToolUseCount": 1, "totalDurationMs": 1, "totalTokens": 1, + })), + ("mcp__srv__tool", json!([{"type": "text", "text": format!("token {SECRET}")}])), + ("mcp__srv__tool", json!([{"type": "text", "text": "clean"}, {"type": "text", "text": format!("token {SECRET}")}])), + ("mcp__srv__tool", json!({"content": [{"type": "text", "text": line}], "isError": false})), + ] +} + +/// Types: `"string"`, `"number"`, `"bool"`; a trailing `?` allows null or absence; +/// an array of strings is an enum; an array of one schema is a list of it; an object +/// is an object with those fields, others being free (zod strips them). +fn schema(tool: &str) -> Option { + let patch = json!([{"oldStart": "number", "oldLines": "number", "newStart": "number", "newLines": "number", "lines": ["string"]}]); + let git_diff = json!({"filename": "string", "status": ["modified", "added"], "additions": "number", "deletions": "number", "changes": "number", "patch": "string"}); + Some(match tool { + "Bash" => json!({ + "stdout": "string", "stderr": "string", "interrupted": "bool", "isImage": "bool?", + "gitOperation?": { + "commit?": {"sha": "string", "kind": ["committed", "amended", "cherry-picked"], "branch": "string?"}, + "push?": {"branch": "string"}, + "branch?": {"ref": "string", "action": ["merged", "rebased"]}, + "pr?": {"number": "number", "url": "string?", "action": ["created", "edited", "merged", "commented", "closed", "reopened", "ready", "draft", "auto-merge-enabled", "auto-merge-disabled"]}, + }, + }), + "Read" => json!({"type": ["text"], "file": {"filePath": "string", "content": "string", "numLines": "number", "startLine": "number", "totalLines": "number"}}), + "Grep" => json!({"mode": ["content", "files_with_matches", "count"], "numFiles": "number", "filenames": ["string"], "content": "string?", "numLines": "number?"}), + "Glob" => json!({"durationMs": "number", "numFiles": "number", "filenames": ["string"], "truncated": "bool"}), + "Write" => json!({"type": ["create", "update"], "filePath": "string", "content": "string", "structuredPatch": patch, "originalFile": "string?", "gitDiff?": git_diff}), + "Edit" => json!({"filePath": "string", "oldString": "string", "newString": "string", "originalFile": "string?", "structuredPatch": patch, "userModified": "bool", "replaceAll": "bool", "gitDiff?": git_diff}), + "WebFetch" => json!({"bytes": "number", "code": "number", "codeText": "string", "result": "string", "durationMs": "number", "url": "string"}), + "NotebookEdit" => json!({"new_source": "string", "cell_type": ["code", "markdown"], "language": "string", "edit_mode": "string", "notebook_path": "string", "original_file": "string", "updated_file": "string"}), + "Agent" => json!({"status": ["completed"], "prompt": "string", "agentId": "string", "content": [{"type": ["text"], "text": "string"}], "totalToolUseCount": "number", "totalDurationMs": "number", "totalTokens": "number"}), + _ => return None, // MCP output is not validated. + }) +} + +fn conforms(schema: &Value, value: &Value, path: &str) -> Result<(), String> { + let fail = || Err(format!("{path}: {value} does not match {schema}")); + match schema { + Value::String(kind) => { + let (kind, optional) = kind.strip_suffix('?').map_or((kind.as_str(), false), |k| (k, true)); + let ok = (optional && value.is_null()) + || match kind { + "string" => value.is_string(), + "number" => value.is_number(), + _ => value.is_boolean(), + }; + if ok { Ok(()) } else { fail() } + } + Value::Array(items) if items.iter().all(|i| i.as_str().is_some_and(|s| !matches!(s, "string" | "number" | "bool"))) => { + if items.contains(value) { Ok(()) } else { fail() } + } + Value::Array(items) => match value.as_array() { + Some(values) => values.iter().try_for_each(|v| conforms(&items[0], v, path)), + None => fail(), + }, + Value::Object(fields) => { + if !value.is_object() { + return fail(); + } + for (name, field) in fields { + let (name, optional) = name.strip_suffix('?').map_or((name.as_str(), false), |n| (n, true)); + match value.get(name) { + None if optional || field.as_str().is_some_and(|k| k.ends_with('?')) => {} + None => return Err(format!("{path}.{name} is missing")), + Some(v) => conforms(field, v, &format!("{path}.{name}"))?, + } + } + Ok(()) + } + _ => fail(), + } +} + +/// `after` is `before` with the secret masked, and nothing else: same keys, same +/// order of lists, same numbers and booleans. +fn same_shape(before: &Value, after: &Value, path: &str) { + match (before, after) { + (Value::String(b), Value::String(a)) => assert_eq!(*a, b.replace(SECRET, MASK), "{path}"), + (Value::Array(b), Value::Array(a)) => { + assert_eq!(b.len(), a.len(), "{path}"); + b.iter().zip(a).for_each(|(b, a)| same_shape(b, a, path)); + } + (Value::Object(b), Value::Object(a)) => { + assert_eq!(b.keys().collect::>(), a.keys().collect::>(), "{path}"); + b.iter().for_each(|(k, v)| same_shape(v, &a[k], &format!("{path}.{k}"))); + } + (b, a) => assert_eq!(b, a, "{path}"), + } +} + +fn updated(out: &Value) -> &Value { + let updated = &out["hookSpecificOutput"]["updatedToolOutput"]; + assert!(!updated.is_null(), "nothing replaced: {out}"); + assert_eq!(out["hookSpecificOutput"]["hookEventName"], "PostToolUse"); + updated +} + +#[test] +fn every_shape_is_redacted_under_every_setting() { + let settings = ["", "[enforcement]\non_parse_error = \"allow\"\n", "[enforcement]\non_parse_error = \"deny\"\n"]; + for setting in settings { + let p = project(&format!("API_TOKEN={SECRET}\n"), &format!("{setting}[files]\npatterns = [\".env\"]\n")); + for (tool, response) in payloads() { + let out = hook(&p, tool, &response); + assert!(!out.to_string().contains(SECRET), "{tool} under {setting:?}: {out}"); + updated(&out); + } + } +} + +#[test] +fn only_the_secret_changes_and_the_shape_stays() { + let p = with_secret(); + for (tool, response) in payloads() { + let out = hook(&p, tool, &response); + same_shape(&response, updated(&out), tool); + assert!(out.to_string().contains(MASK), "{tool}: {out}"); + } +} + +#[test] +fn the_replacement_matches_the_tools_schema() { + let p = with_secret(); + for (tool, response) in payloads() { + // The fixture itself must be what the schema describes. + if let Some(schema) = schema(tool) { + conforms(&schema, &response, tool).unwrap(); + conforms(&schema, updated(&hook(&p, tool, &response)), tool).unwrap(); + } + } +} + +#[test] +fn a_string_response_stays_a_string_and_a_clean_response_answers_nothing() { + let p = with_secret(); + let out = hook(&p, "mcp__srv__tool", &json!(format!("token {SECRET}"))); + assert_eq!(*updated(&out), json!(format!("token {MASK}"))); + + for response in [ + json!({"stdout": "clean", "stderr": "", "interrupted": false, "isImage": false}), + json!([{"type": "text", "text": "clean"}]), + json!("clean"), + ] { + assert_eq!(hook(&p, "Bash", &response), json!({}), "{response}"); + } +} + +// --------------------------------------------------------------------------- +// Enum and literal fields +// --------------------------------------------------------------------------- + +/// A secret that is also an enum value. Masking it would fail the schema, and Claude +/// Code would then use the original output. The listed value stays: it tells nothing. +#[test] +fn a_secret_equal_to_a_schema_value_keeps_the_field_and_masks_the_text() { + for (word, tool, response) in [ + ("committed", "Bash", json!({"stdout": "it committed x", "stderr": "", "interrupted": false, "gitOperation": {"commit": {"sha": "abc", "kind": "committed"}}})), + ("completed", "Agent", json!({"status": "completed", "prompt": "p", "agentId": "a", "content": [{"type": "text", "text": "completed it"}], "totalToolUseCount": 1, "totalDurationMs": 1, "totalTokens": 1})), + ("markdown", "NotebookEdit", json!({"new_source": "a markdown cell", "cell_type": "markdown", "language": "python", "edit_mode": "replace", "notebook_path": "n", "original_file": "o", "updated_file": "u"})), + ("modified", "Edit", json!({"filePath": "/p/x", "oldString": "modified", "newString": "x", "originalFile": null, "structuredPatch": [], "userModified": false, "replaceAll": false, "gitDiff": {"filename": "x", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "p"}})), + ("text", "Read", json!({"type": "text", "file": {"filePath": "/p/x", "content": "plain text", "numLines": 1, "startLine": 1, "totalLines": 1}})), + ("create", "Write", json!({"type": "create", "filePath": "/p/x", "content": "create it", "structuredPatch": [], "originalFile": null})), + ("count", "Grep", json!({"mode": "count", "numFiles": 0, "filenames": ["/p/count"]})), + ] { + let p = project(&format!("API_TOKEN={word}\n"), "[files]\npatterns = [\".env\"]\n"); + let out = hook(&p, tool, &response); + conforms(&schema(tool).unwrap(), updated(&out), &format!("{tool} with {word}")).unwrap(); + assert!(out.to_string().contains(MASK), "{tool}: {out}"); + } +} + +/// A token under an enum's name that the schema does not list is no enum value. A +/// built-in's schema would refuse the mask, so the whole output is refused. +#[test] +fn a_secret_where_a_built_in_cannot_take_a_mask_withholds_the_output() { + let p = with_secret(); + for (tool, response) in [ + ("Bash", json!({"stdout": SECRET, "stderr": "", "interrupted": false, "type": SECRET})), + ("Bash", json!({"stdout": "x", "stderr": "", "interrupted": false, "gitOperation": {"commit": {"sha": "a", "kind": format!("{SECRET}-x")}}})), + ("Bash", json!({"stdout": SECRET, "stderr": "", "interrupted": false, SECRET: "x"})), + ] { + let out = hook(&p, tool, &response); + assert!(!out.to_string().contains(SECRET), "{out}"); + assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("API_TOKEN"), "{out}"); + assert!(updated(&out).to_string().contains("withheld"), "{out}"); + conforms(&schema(tool).unwrap(), updated(&out), tool).unwrap(); + } +} + +/// A word that is a key of the output is refused, not passed. A fixed name in the +/// schema cannot take a mask. +#[test] +fn a_secret_equal_to_a_schema_key_withholds_rather_than_passes() { + let p = project("API_TOKEN=stdout\n", "[files]\npatterns = [\".env\"]\n"); + let response = json!({"stdout": "x", "stderr": "", "interrupted": false}); + let out = hook(&p, "Bash", &response); + conforms(&schema("Bash").unwrap(), updated(&out), "Bash").unwrap(); + assert!(updated(&out)["stdout"].as_str().unwrap().contains("API_TOKEN"), "{out}"); +} + +/// A notebook cell's `source` is text, though `source` is also a literal elsewhere. +#[test] +fn a_notebook_cells_source_is_masked_not_refused() { + let p = with_secret(); + let response = json!({"type": "notebook", "file": {"filePath": "/p/n.ipynb", "cells": [{"cellType": "code", "source": format!("t = '{SECRET}'")}]}}); + let out = hook(&p, "Read", &response); + same_shape(&response, updated(&out), "Read"); +} + +// --------------------------------------------------------------------------- +// Object keys, and what stays +// --------------------------------------------------------------------------- + +#[test] +fn an_mcp_results_keys_are_masked_and_stay_apart() { + let p = with_secret(); + let out = hook(&p, "mcp__srv__tool", &json!({ + SECRET: 1, + format!("x{SECRET}"): "x", + "*****": 2, + "nested": [{SECRET: true}], + })); + assert!(!out.to_string().contains(SECRET), "{out}"); + let updated = updated(&out).as_object().unwrap(); + assert_eq!(updated.len(), 4, "{updated:?}"); + assert_eq!(updated["x*****"], "x"); +} + +/// AskUserQuestion's answers are keyed by question text, not by schema names. +#[test] +fn a_built_in_records_keys_are_masked() { + let p = with_secret(); + let out = hook(&p, "AskUserQuestion", &json!({"questions": [], "answers": {SECRET: "yes"}})); + assert_eq!(updated(&out)["answers"], json!({MASK: "yes"})); + assert!(!out.to_string().contains(SECRET), "{out}"); +} + +/// A short secret can match inside base64 by chance. Masking there breaks the image +/// and the next API request. +#[test] +fn binary_fields_stay_and_text_beside_them_is_masked() { + let p = project("API_TOKEN=QUJD\n", "[files]\npatterns = [\".env\"]\n"); + let data = "QUJD".repeat(32); + for (tool, response) in [ + ("Read", json!({"type": "image", "file": {"base64": data, "type": "image/png", "originalSize": 3}})), + ("Read", json!({"type": "pdf", "file": {"filePath": "/p/x.pdf", "base64": data, "originalSize": 3}})), + ("Bash", json!({"stdout": format!("data:image/png;base64,{data}"), "stderr": "", "interrupted": false, "isImage": true})), + ("mcp__srv__tool", json!([{"type": "image", "data": data, "mimeType": "image/png"}])), + ] { + assert_eq!(hook(&p, tool, &response), json!({}), "{tool}"); + } + + // A token named `data` is text, and so is `base64` in an MCP result. + let out = hook(&p, "mcp__srv__tool", &json!({"data": "QUJD", "base64": "QUJD"})); + assert_eq!(*updated(&out), json!({"data": MASK, "base64": MASK})); +} + +/// A value split across two strings is not one match: the documented limit. +#[test] +fn a_value_split_across_fields_is_not_found() { + let (head, tail) = SECRET.split_at(10); + let p = with_secret(); + let out = hook(&p, "Bash", &json!({"stdout": head, "stderr": tail, "interrupted": false})); + assert_eq!(out, json!({})); +} + +#[test] +fn the_heuristic_warning_sits_beside_an_object_response() { + let p = project("UNRELATED_KEY=foo\n", "[files]\npatterns = [\".env\"]\n"); + let response = json!({"stdout": "log: ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij", "stderr": "", "interrupted": false, "isImage": false}); + let out = hook(&p, "Bash", &response); + let specific = &out["hookSpecificOutput"]; + assert!(specific.get("updatedToolOutput").is_none(), "{out}"); + let context = specific["additionalContext"].as_str().unwrap(); + assert!(context.contains("WARNING") && !context.contains("ghp_"), "{context}"); +} + +// --------------------------------------------------------------------------- +// Refusals under `deny` +// --------------------------------------------------------------------------- + +/// Under `deny` with a broken secret file, each output is replaced by something its +/// schema takes. A rejected refusal would let the original through. +#[test] +fn the_refusal_matches_each_tools_schema() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join(".botignore"), "").unwrap(); + fs::write(dir.path().join(".botsecrets"), "[enforcement]\non_parse_error = \"deny\"\n").unwrap(); + fs::write(dir.path().join("secrets.toml"), format!("API_TOKEN = \"{SECRET}\" broken [\n")).unwrap(); + let p = (dir, tempfile::tempdir().unwrap()); + + for (tool, response) in payloads() { + let out = hook(&p, tool, &response); + assert!(!out.to_string().contains(SECRET), "{tool}: {out}"); + assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("secrets.toml"), "{out}"); + if let Some(schema) = schema(tool) { + conforms(&schema, updated(&out), tool).unwrap(); + } + } + + // Bash and Read drop what could fail or mislead the mapper. + let out = hook(&p, "Bash", &json!({"stdout": SECRET, "stderr": "", "interrupted": false, "isImage": true, "gitOperation": {"commit": {"sha": "a", "kind": "new-kind"}}})); + let bash = updated(&out); + assert_eq!(bash["isImage"], false); + assert!(bash.get("gitOperation").is_none(), "{out}"); + + for response in [ + json!({"type": "image", "file": {"base64": "QUJD", "type": "image/png", "originalSize": 3}}), + json!({"type": "pdf", "file": {"filePath": "/p/x.pdf", "base64": "QUJD", "originalSize": 3}}), + json!({"type": "notebook", "file": {"filePath": "/p/n", "cells": []}}), + ] { + let out = hook(&p, "Read", &response); + let read = updated(&out); + conforms(&schema("Read").unwrap(), read, "Read").unwrap(); + assert!(read["file"]["content"].as_str().unwrap().contains("withheld"), "{out}"); + assert!(!out.to_string().contains("QUJD"), "{out}"); + } + + // A built-in that answers a list takes a list. + let out = hook(&p, "ListMcpResourcesTool", &json!([{"uri": SECRET, "name": "n", "server": "s"}])); + assert!(updated(&out).is_array(), "{out}"); + assert!(!out.to_string().contains(SECRET), "{out}"); + + // Keys that are free text go, length limits hold. + let out = hook(&p, "AskUserQuestion", &json!({"questions": [], "answers": {SECRET: "yes"}})); + assert_eq!(updated(&out)["answers"], json!({})); + let out = hook(&p, "ReportFindings", &json!({"count": 1, "findings": [{"file": "f", "summary": SECRET, "failure_scenario": "x", "short_summary": "s", "category": "c", "verdict": "CONFIRMED"}]})); + let finding = &updated(&out)["findings"][0]; + assert!(finding["short_summary"].as_str().unwrap().chars().count() <= 60, "{out}"); + assert!(finding["category"].as_str().unwrap().chars().count() <= 40, "{out}"); + assert_eq!(finding["verdict"], "CONFIRMED"); + + // M-4: a token under an enum's name is not kept. + let out = hook(&p, "Grep", &json!({"mode": SECRET, "numFiles": 0, "filenames": []})); + assert!(!out.to_string().contains(SECRET), "{out}"); +} + +#[test] +fn the_pre_tool_use_hook_is_quiet_on_a_tool_it_has_no_rules_for() { + let p = with_secret(); + let output = Command::cargo_bin("fermata") + .unwrap() + .args(["hook", "--event", "pre-tool-use", "--harness", "claude"]) + .current_dir(p.0.path()) + .env("HOME", p.1.path()) + .write_stdin(json!({"tool_name": "Grep", "tool_input": {"pattern": "x"}}).to_string()) + .assert() + .success() + .get_output() + .clone(); + assert_eq!(serde_json::from_slice::(&output.stdout).unwrap(), json!({})); + assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr)); +} diff --git a/tests/core_secrets_manifest.rs b/tests/core_secrets_manifest.rs index 8edfde4..c736799 100644 --- a/tests/core_secrets_manifest.rs +++ b/tests/core_secrets_manifest.rs @@ -344,7 +344,7 @@ fn deny_config() -> SecretsConfig { fn an_editors_file_that_cannot_be_read_does_not_refuse_and_one_that_can_stays_known() { let dir = tempfile::tempdir().unwrap(); let config = deny_config(); - for name in [".env.swp", ".env.swo", ".env.swn", ".env.swx", ".env.local~"] { + for name in [".env.swp", ".env.swo", ".env.swn", ".env.swm", ".env.swa", ".env.swx", ".env.kate-swp", ".env.local~"] { fs::write(dir.path().join(name), NOT_UTF8).unwrap(); } fs::write(dir.path().join(".env.bak.swp"), "API_KEY=readable-swap-value-1234\n").unwrap(); diff --git a/tests/harness_claude.rs b/tests/harness_claude.rs index 41f96b6..eb068b2 100644 --- a/tests/harness_claude.rs +++ b/tests/harness_claude.rs @@ -95,14 +95,16 @@ fn parses_post_tool_use_payload() { let p = ClaudeAdapter.parse_post_tool_use(payload).unwrap(); assert_eq!(p.tool_name, "Read"); assert_eq!(p.tool_response, "SECRET=abc"); + assert!(p.has_output()); } #[test] fn parses_post_tool_use_missing_response() { - // tool_response absent → defaults to empty string. + // tool_response absent → no output to look at. let payload = br#"{"tool_name":"Bash","tool_input":{"command":"ls"}}"#; let p = ClaudeAdapter.parse_post_tool_use(payload).unwrap(); - assert_eq!(p.tool_response, ""); + assert_eq!(p.tool_response, serde_json::Value::Null); + assert!(!p.has_output()); } #[test] @@ -110,7 +112,7 @@ fn renders_post_tool_use_with_redacted_output() { let payload = br#"{"tool_name":"Read","tool_input":{},"tool_response":"x"}"#; let p = ClaudeAdapter.parse_post_tool_use(payload).unwrap(); let out = ClaudeAdapter - .render_post_tool_use(&p, Some("redacted text")) + .render_post_tool_use(&p, Some(&serde_json::json!("redacted text")), None) .unwrap(); let v: serde_json::Value = serde_json::from_slice(&out).unwrap(); assert_eq!(v["hookSpecificOutput"]["hookEventName"], "PostToolUse"); @@ -124,7 +126,7 @@ fn renders_post_tool_use_with_redacted_output() { fn renders_post_tool_use_passthrough() { let payload = br#"{"tool_name":"Read","tool_input":{},"tool_response":"clean"}"#; let p = ClaudeAdapter.parse_post_tool_use(payload).unwrap(); - let out = ClaudeAdapter.render_post_tool_use(&p, None).unwrap(); + let out = ClaudeAdapter.render_post_tool_use(&p, None, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&out).unwrap(); assert_eq!(v, serde_json::json!({})); }