fix(fermata): empty masked text becomes [fermata]; a Monitor without a command is left alone; tests for the CRLF and JSON-escaped spellings

This commit is contained in:
2026-11-07 01:29:03 +01:00
parent a583cc24dc
commit ac2fa03306
4 changed files with 75 additions and 2 deletions
+1 -1
View File
@@ -82,7 +82,7 @@ The PostToolUse hook redacts what Claude Code hands it and accepts back. These a
- **Values that never enter the manifest.** A commented `.env` line (`#API_TOKEN=old-prod-value`). A `.env` that is a symlink. A multi-document YAML file: by default the whole file is skipped with a line on stderr, and under `deny` every output is refused for a valid file. `secrets.py` with `SECRET_KEY = "x" # prod` or a triple-quoted value over lines. `.env` values with quoting inside them (`'a'\''b-x'`, `abc"def"-x`), when a program prints the decoded value. The first value of a duplicate JSON key. A `.env` value swallowed by an unclosed quote above it. A secret file outside the working project, such as a Read of `../other/.env`.
- **Files that cannot be parsed.** By default a BOM or a comment in JSON, or a Latin-1 or UTF-16 `.env`, skips the file with only a line on stderr. Neither the model nor the user sees more.
- **A tool that fails. This is the largest limit for values in the manifest.** Claude Code sends a failed tool's text through `PostToolUseFailure`, whose hooks can only add a note. That includes a Bash command with a non-zero exit code, whose error text holds the command's output, and an MCP error result. `cat .env; false` reaches the model unredacted, and so does a failing `npm test` that prints its environment, `curl -v -f` with a token header on a 500, or any failing `set -x` script. Fermata does not hook this event and cannot rewrite it. Only a `[policy.bash] deny` pattern stops such a command, and only for the spelling it names: a deny on `cat .env` stops `cat .env; false` but not `cat ./.env; false`, `env; false` or `grep -r TOKEN .; false`. `[policy.read]` and `.botignore` apply to the Read tool, not to what a command prints.
- **Monitor's output.** Each line of a Monitor's command goes to the model as an event, and PostToolUse only sees `{taskId, timeoutMs}`. `tail -f server.log` passes logged tokens straight through. `[policy.bash]` applies to Monitor's and PowerShell's commands, with the same spelling limit.
- **Monitor's output.** Each line of a Monitor's command goes to the model as an event, and PostToolUse only sees `{taskId, timeoutMs}`. `tail -f server.log` passes logged tokens straight through. `[policy.bash]` applies to Monitor's and PowerShell's commands, with the same spelling limit. A WebSocket Monitor (`ws`, no `command`) has no rule at all, and its frames reach the model; the hook answers `{}` quietly.
- **A changed file's attachment.** After a Read, a file that changes on disk comes back to the model as an attachment with a snippet, which no tool call and no hook handles. Read `.env`, rotate the token, and the next turn carries the new value. `@`-mentions likely take the same route; that has not been traced.
- **A value split across strings.** Each string is scanned on its own. A value divided between `stdout` and `stderr`, between two MCP content blocks, or across the lines of a diff (a multi-line value in `structuredPatch`) does not match.
- **An encoded or altered value.** Base64, URL encoding, a reversed string or a value cut short does not match. Spellings the value has in its own file are known: see [Spellings](#spellings). See the [threat model](threat-model.md).
+6 -1
View File
@@ -166,6 +166,8 @@ fn tool_op(tool: &str, input: &Value) -> Result<ToolOp, AdapterError> {
// A Grep on a named file is a Read by another name. Without a path it names nothing.
"Grep" if input.get("path").is_some_and(Value::is_string) => path_op(input, "path", PathKind::Read),
"Write" | "Edit" | "MultiEdit" => path_op(input, "file_path", PathKind::Write),
// A WebSocket Monitor (`ws`) has no command: no rule applies, so stay quiet.
"Monitor" if input.get("command").is_none() => Err(AdapterError::UnsupportedTool("Monitor".into())),
// The three that run a command line. Monitor's lines reach the model with
// no hook between them, so `[policy.bash]` is the only check its command gets.
"Bash" | "PowerShell" | "Monitor" => command_op(input),
@@ -430,7 +432,10 @@ impl RedactWalk<'_> {
self.unmaskable.extend(redacted.redactions.iter().map(|r| r.key.clone()));
}
self.redactions += redacted.redactions.len();
fit_schema(key, redacted.text)
// An empty text fails a schema's `.min(1)` and an API text block, and the
// original would go through. `absent` is the style that leaves it empty.
let text = if redacted.text.trim().is_empty() { "[fermata]".to_string() } else { redacted.text };
fit_schema(key, text)
}
/// An MCP result and a built-in's record ([`RECORD_FIELDS`]) take a masked key.
+35
View File
@@ -230,3 +230,38 @@ fn an_unclosed_quote_leaves_the_next_key_alone() {
let shown = read(&p, "nextfakevalue lastfakevalue");
assert_eq!(shown, "***** *****");
}
// ---------------------------------------------------------------------------
// Two spellings no other test needs
// ---------------------------------------------------------------------------
/// Short lines, so that no line is masked alone and only the whole value can match.
const SHORT_A: &str = "fakeab1";
const SHORT_B: &str = "fakecd2";
#[test]
fn a_value_read_from_a_file_with_windows_line_ends() {
let env = format!("API_TOKEN=\"{SHORT_A}\n{SHORT_B}\"\n");
let p = project(&[(".env", &env)]);
let shown = read(&p, &format!("{SHORT_A}\r\n{SHORT_B}\r\n"));
assert!(!shown.contains(SHORT_A) && !shown.contains(SHORT_B), "{shown}");
}
#[test]
fn a_value_with_a_quote_inside_a_json_string_of_a_tool_result() {
let p = project(&[(".env", "API_TOKEN='a\"b-fakevalue123'\n")]);
let text = json!({"k": "a\"b-fakevalue123"}).to_string();
let payload = json!({"tool_name": "mcp__srv__t", "tool_input": {}, "tool_response": {"content": [{"type": "text", "text": text}]}});
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(payload.to_string())
.assert()
.success()
.get_output()
.clone();
let out = String::from_utf8(output.stdout).unwrap();
assert!(out.contains("updatedToolOutput") && !out.contains("fakevalue123"), "{out}");
}
+33
View File
@@ -301,3 +301,36 @@ fn the_note_stands_beside_the_heuristic_warning() {
assert!(context.starts_with(NOTE) && context.contains("WARNING"), "{context}");
assert!(!context.contains("ghp_"), "{context}");
}
// ---------------------------------------------------------------------------
// Empty text and a Monitor without a command
// ---------------------------------------------------------------------------
#[test]
fn the_absent_style_leaves_no_empty_text() {
let p = project(&[(".env", &format!("API_TOKEN={SECRET}\n")), (".botsecrets", &styled("absent"))]);
let todo = json!({"oldTodos": [], "newTodos": [{"content": SECRET, "status": "pending", "activeForm": "Working"}]});
let out = p.post("TodoWrite", todo);
assert_eq!(out["hookSpecificOutput"]["updatedToolOutput"]["newTodos"][0]["content"], "[fermata]", "{out}");
let mcp = json!({"content": [{"type": "text", "text": SECRET}]});
let out = p.post("mcp__srv__t", mcp);
assert_eq!(out["hookSpecificOutput"]["updatedToolOutput"]["content"][0]["text"], "[fermata]", "{out}");
}
#[test]
fn a_monitor_without_a_command_is_left_alone() {
let p = project(&[]);
let output = Command::cargo_bin("fermata")
.unwrap()
.args(["hook", "--event", "pre-tool-use", "--harness", "claude"])
.current_dir(p.dir.path())
.env("HOME", p.home.path())
.write_stdin(json!({"tool_name": "Monitor", "tool_input": {"ws": "wss://example.test/x"}}).to_string())
.assert()
.success()
.get_output()
.clone();
assert_eq!(output.stdout, b"{}");
assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr));
}