|
|
|
@@ -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<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}));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// 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));
|
|
|
|
|
}
|