PreToolUse answers {} when no rule stopped a call: permissionDecision allow skipped Claude
Code's own prompt. allow_prefixes now only skips fermata's ask rules. PowerShell and Monitor
commands reach [policy.bash]. SCHEMA_VALUES covers the remaining getters of 2.1.314, Artifact
refuses in its read form, and data beside a binary type stays only in a top-level block.
623 lines
34 KiB
Rust
623 lines
34 KiB
Rust
//! 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 = "*****";
|
|
/// A fake token that fits the base64 alphabet.
|
|
const SECRET_B64: &str = "fakeTOKENinBASE64alphabet";
|
|
|
|
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<Value> {
|
|
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::<Vec<_>>(), a.keys().collect::<Vec<_>>(), "{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}));
|
|
}
|
|
|
|
/// Only a content block at the top of a result holds binary data. The same object
|
|
/// deeper down is the result's own data, and a server can shape it to look like one.
|
|
#[test]
|
|
fn data_beside_a_binary_type_is_text_unless_a_top_level_block_holds_it() {
|
|
let token = format!("{SECRET_B64}{}", "A".repeat(80));
|
|
let p = project(&format!("API_TOKEN={SECRET_B64}\n"), "[files]\npatterns = [\".env\"]\n");
|
|
|
|
for response in [
|
|
json!([{"type": "image", "data": token}]),
|
|
json!({"content": [{"type": "image", "data": token}]}),
|
|
json!({"type": "audio", "data": token}),
|
|
json!([{"type": "image", "source": {"type": "base64", "data": token}}]),
|
|
] {
|
|
assert_eq!(hook(&p, "mcp__srv__tool", &response), json!({}), "{response}");
|
|
}
|
|
for response in [
|
|
json!({"result": {"type": "image", "data": token}}),
|
|
json!([{"type": "text", "nested": [{"type": "image", "data": token}]}]),
|
|
json!({"content": [{"result": {"type": "image", "data": token}}]}),
|
|
] {
|
|
let out = hook(&p, "mcp__srv__tool", &response);
|
|
assert!(!updated(&out).to_string().contains(SECRET_B64), "{out}");
|
|
}
|
|
}
|
|
|
|
/// `data` shorter than an image can be is a token, even beside `type: image`.
|
|
#[test]
|
|
fn the_binary_rule_starts_at_64_characters() {
|
|
let p = project(&format!("API_TOKEN={SECRET_B64}\n"), "[files]\npatterns = [\".env\"]\n");
|
|
let fill = 64 - SECRET_B64.len();
|
|
let long = format!("{SECRET_B64}{}", "A".repeat(fill));
|
|
assert_eq!(hook(&p, "mcp__srv__tool", &json!([{"type": "image", "data": long}])), json!({}));
|
|
let short = format!("{SECRET_B64}{}", "A".repeat(fill - 1));
|
|
let out = hook(&p, "mcp__srv__tool", &json!([{"type": "image", "data": short}]));
|
|
assert!(!updated(&out).to_string().contains(SECRET_B64), "{out}");
|
|
}
|
|
|
|
/// 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::<Value>(&output.stdout).unwrap(), json!({}));
|
|
assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Every enum of every built-in (M-1, M-2)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// Per tool, the enum and literal fields of its output schema in v2.1.314, generated from
|
|
/// the bundle's `outputSchema` getters. Each value here must survive: a replacement that
|
|
/// changes one fails the schema, and Claude Code then uses the original output.
|
|
/// So a value dropped from `SCHEMA_VALUES` fails a test here.
|
|
const TOOL_ENUMS: &[(&str, &[(&str, &[&str])])] = &[
|
|
("memory_write", &[("outcome", &["ok", "conflict", "missing", "refused", "failed"]), ("store_kind", &["personal", "project"]), ("op", &["created", "updated"])]),
|
|
("memory_read", &[("outcome", &["ok", "not_found", "refused", "failed"]), ("store_kind", &["personal", "project"])]),
|
|
("memory_list", &[("outcome", &["ok", "refused", "failed"]), ("store_kind", &["personal", "project"])]),
|
|
("Write", &[("type", &["create", "update"]), ("status", &["modified", "added"]), ("stagedWording", &["true"])]),
|
|
("Edit", &[("status", &["modified", "added"]), ("stagedWording", &["true"])]),
|
|
("Grep", &[("mode", &["content", "files_with_matches", "count"])]),
|
|
("Read", &[("type", &["text", "image", "image/jpeg", "image/png", "image/gif", "image/webp", "notebook", "pdf", "parts", "file_unchanged"]), ("mediaType", &["image/jpeg", "image/png", "image/gif", "image/webp"]), ("source", &["seeded"])]),
|
|
("NotebookEdit", &[("cell_type", &["code", "markdown"])]),
|
|
("Bash", &[("kind", &["committed", "amended", "cherry-picked"]), ("action", &["merged", "rebased", "created", "edited", "commented", "closed", "reopened", "ready", "draft", "auto-merge-enabled", "auto-merge-disabled"])]),
|
|
("Agent", &[("handback", &["send", "flagged", "withheld"]), ("type", &["text"]), ("status", &["completed", "async_launched", "remote_launched", "teammate_spawned"])]),
|
|
("Skill", &[("status", &["inline", "forked"])]),
|
|
("AskUserQuestion", &[("kind", &["choice", "text", "number"]), ("unanswered", &["skipped", "replied_in_chat", "dismissed"])]),
|
|
("ShareOnboardingGuide", &[("status", &["created", "updated", "deleted", "has_existing", "unavailable"])]),
|
|
("OfferChromeSetup", &[("outcome", &["connected", "not_now", "no_attempt_yet"])]),
|
|
("ReportFindings", &[("level", &["low", "medium", "high", "xhigh", "max"]), ("verdict", &["CONFIRMED", "PLAUSIBLE"]), ("outcome", &["fixed", "skipped", "no_change_needed"])]),
|
|
("TaskGet", &[("status", &["pending", "in_progress", "completed"])]),
|
|
("TaskList", &[("status", &["pending", "in_progress", "completed"])]),
|
|
("TodoWrite", &[("status", &["pending", "in_progress", "completed"])]),
|
|
("GetTask", &[("status", &["working", "completed", "failed", "cancelled"]), ("type", &["text"])]),
|
|
("LSP", &[("operation", &["goToDefinition", "findReferences", "hover", "documentSymbol", "workspaceSymbol", "goToImplementation", "prepareCallHierarchy", "incomingCalls", "outgoingCalls"])]),
|
|
("RefreshMcpTools", &[("status", &["refreshed", "error", "not_connected"])]),
|
|
("ExitWorktree", &[("action", &["keep", "remove"])]),
|
|
("SuggestPluginInstall", &[("trigger", &["user_asked", "proactive"])]),
|
|
("SuggestSkills", &[("trigger", &["user_asked", "proactive"])]),
|
|
("Poll", &[("type", &["image", "base64", "document"]), ("media_type", &["image/jpeg", "image/png", "image/gif", "image/webp", "application/pdf"]), ("authority", &["human-principal", "human-other", "peer-agent", "world-event"])]),
|
|
("AppifactRepl", &[("media_type", &["image/png", "image/jpeg"])]),
|
|
("Projects", &[("method", &["project_info", "project_read", "project_search", "project_write", "project_delete", "project_memory_list", "project_memory_read"])]),
|
|
("SendUserFile", &[("display", &["render", "attach"])]),
|
|
("PublishPlugin", &[("state", &["published", "in-review", "publishing", "on-shelf", "refused"])]),
|
|
("PushNotification", &[("disabledReason", &["config_off", "user_present", "no_transport"])]),
|
|
("Appifact", &[("method", &["list_projects", "get_project", "list_files", "get_file", "finalize_plan", "write_files", "delete_files", "register_assets", "unregister_assets", "create_project", "report_validate"])]),
|
|
("SendToProject", &[("mode", &["new", "existing"]), ("message", &["sent", "uncertain", "not_sent"])]),
|
|
("SendToProjectContext", &[("status", &["delivered", "already_delivered", "nothing_read", "no_run"])]),
|
|
("Workflow", &[("status", &["async_launched", "remote_launched"]), ("taskType", &["local_workflow", "remote_agent"])]),
|
|
("Artifact", &[
|
|
("action", &["pin", "unpin"]), ("working_copy", &["bound", "left"]), ("verb", &["put", "retract", "read", "script"]),
|
|
("status", &["uploaded", "failed", "not_attempted"]), ("fallback", &["sequential"]), ("rail", &["durable_wake", "live_stopped"]),
|
|
("scope", &["shared", "all"]), ("editsNotWritten", &["write_failed", "not_writable", "changed_during_publish", "hard_linked"]),
|
|
("auto_open", &["at_create", "after_first_write"]), ("files_error_kind", &["type_owned_path"]), ("op", &["batch"]),
|
|
("unread", &["withheld", "not_listed", "not_text", "too_large", "unavailable", "result_full"]),
|
|
]),
|
|
];
|
|
|
|
/// These answer a fixed form under a refusal, so no field of the response survives.
|
|
const FIXED_REFUSAL: &[&str] = &["Bash", "Read", "Artifact"];
|
|
|
|
fn broken_secret_file() -> (TempDir, TempDir) {
|
|
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"), "API_TOKEN = broken [\n").unwrap();
|
|
(dir, tempfile::tempdir().unwrap())
|
|
}
|
|
|
|
/// Under a refusal every string of a built-in's output goes, but an enum value stays.
|
|
#[test]
|
|
fn a_refusal_keeps_every_enum_value_of_every_tool() {
|
|
let p = broken_secret_file();
|
|
for (tool, fields) in TOOL_ENUMS.iter().filter(|(tool, _)| !FIXED_REFUSAL.contains(tool)) {
|
|
for (field, values) in *fields {
|
|
for value in *values {
|
|
let out = hook(&p, tool, &json!({ *field: value, "note": "free text" }));
|
|
let output = updated(&out);
|
|
assert_eq!(output[*field], *value, "{tool}.{field}: {out}");
|
|
assert!(output["note"].as_str().unwrap().contains("withheld"), "{tool}: {out}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A secret equal to an enum value: the value stays, the text beside it takes a mask,
|
|
/// and nothing is refused.
|
|
#[test]
|
|
fn a_secret_equal_to_an_enum_value_keeps_the_value_in_every_tool() {
|
|
for (tool, fields) in TOOL_ENUMS {
|
|
for (field, values) in *fields {
|
|
for value in values.iter().filter(|v| v.len() >= 4) {
|
|
let p = project(&format!("API_TOKEN={value}\n"), "[files]\npatterns = [\".env\"]\n");
|
|
let out = hook(&p, tool, &json!({ *field: value, "note": format!("x {value} y") }));
|
|
let output = updated(&out);
|
|
assert_eq!(output[*field], *value, "{tool}.{field}: {out}");
|
|
assert_eq!(output["note"], format!("x {MASK} y"), "{tool}.{field}: {out}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `message` is an enum in one tool and text in most others.
|
|
#[test]
|
|
fn a_secret_in_a_message_takes_a_mask() {
|
|
let p = with_secret();
|
|
let out = hook(&p, "PushNotification", &json!({"message": format!("sent {SECRET}"), "pushSent": true}));
|
|
assert_eq!(updated(&out)["message"], format!("sent {MASK}"));
|
|
}
|
|
|
|
/// The Artifact tool's patterns and its run-time enum cannot be listed: a secret there
|
|
/// refuses, in the one form that fits every value of those fields.
|
|
#[test]
|
|
fn a_secret_under_an_unlisted_pattern_refuses_the_artifact_output() {
|
|
let p = with_secret();
|
|
for field in ["ver", "sha256", "id", "url", "content_type", "reason"] {
|
|
let out = hook(&p, "Artifact", &json!({"file_read": { field: SECRET, "path": "a" }}));
|
|
let output = updated(&out);
|
|
assert!(output["read"]["result"].as_str().unwrap().contains("withheld"), "{out}");
|
|
assert!(!out.to_string().contains(SECRET), "{out}");
|
|
}
|
|
// Elsewhere those names are plain text.
|
|
let out = hook(&p, "Glob", &json!({"id": SECRET}));
|
|
assert_eq!(updated(&out)["id"], MASK);
|
|
}
|
|
|
|
#[test]
|
|
fn the_artifact_refusal_is_its_read_form() {
|
|
let out = hook(&broken_secret_file(), "Artifact", &json!({"file_read": {"ver": "abc", "sha256": "def"}}));
|
|
let read = &updated(&out)["read"];
|
|
for field in ["url", "codeText", "result"] {
|
|
assert!(read[field].is_string(), "{out}");
|
|
}
|
|
for field in ["bytes", "code", "durationMs"] {
|
|
assert!(read[field].is_number(), "{out}");
|
|
}
|
|
assert!(!out.to_string().contains("def"), "{out}");
|
|
}
|
|
|
|
/// Records whose keys are free text: a secret there is masked, a refusal empties them.
|
|
#[test]
|
|
fn every_free_text_record_is_a_record() {
|
|
for field in ["fields", "content", "config", "pool", "sessions", "runners", "secrets", "health", "gauges"] {
|
|
let p = with_secret();
|
|
let out = hook(&p, "SomeTool", &json!({ field: { SECRET: 1 } }));
|
|
assert_eq!(updated(&out)[field], json!({ MASK: 1 }), "{field}: {out}");
|
|
let out = hook(&broken_secret_file(), "SomeTool", &json!({ field: { "name": 1 } }));
|
|
assert_eq!(updated(&out)[field], json!({}), "{field}: {out}");
|
|
}
|
|
}
|