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.
410 lines
17 KiB
Rust
410 lines
17 KiB
Rust
//! Claude Code hook adapter (PreToolUse + PostToolUse).
|
|
//!
|
|
//! Wire format: stdin is one JSON object with `tool_name` and `tool_input`
|
|
//! (and optionally `tool_response` for PostToolUse).
|
|
//! Stdout is `{"hookSpecificOutput": {...}}` with exit code 0; the JSON
|
|
//! carries the verdict / updated output.
|
|
|
|
use super::{AdapterError, HarnessAdapter, OutputEdit, PathKind, PostToolUsePayload, ToolCall, ToolOp};
|
|
use crate::core::secrets::Redactor;
|
|
use crate::core::Decision;
|
|
use serde_json::{json, Map, Value};
|
|
use std::path::PathBuf;
|
|
|
|
pub struct ClaudeAdapter;
|
|
|
|
impl HarnessAdapter for ClaudeAdapter {
|
|
fn name(&self) -> &'static str {
|
|
"claude"
|
|
}
|
|
|
|
// -- PreToolUse --------------------------------------------------------
|
|
|
|
fn parse_request(&self, input: &[u8]) -> Result<ToolCall, AdapterError> {
|
|
let v: Value = serde_json::from_slice(input)?;
|
|
let tool_name = v
|
|
.get("tool_name")
|
|
.and_then(|x| x.as_str())
|
|
.ok_or_else(|| AdapterError::Parse("missing tool_name".into()))?
|
|
.to_string();
|
|
let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null);
|
|
|
|
let op = match tool_name.as_str() {
|
|
"Read" => path_op(&tool_input, PathKind::Read)?,
|
|
"Write" | "Edit" | "MultiEdit" => path_op(&tool_input, PathKind::Write)?,
|
|
"Bash" => command_op(&tool_input)?,
|
|
other => return Err(AdapterError::UnsupportedTool(other.to_string())),
|
|
};
|
|
|
|
Ok(ToolCall {
|
|
tool_name,
|
|
op,
|
|
raw: v,
|
|
})
|
|
}
|
|
|
|
fn render_decision(
|
|
&self,
|
|
_call: &ToolCall,
|
|
decision: &Decision,
|
|
) -> Result<Vec<u8>, AdapterError> {
|
|
let (verdict, reason) = match decision {
|
|
Decision::Allow => ("allow", String::new()),
|
|
Decision::Ask(r) => ("ask", r.message.clone()),
|
|
Decision::Deny(r) => ("deny", r.message.clone()),
|
|
};
|
|
let out = json!({
|
|
"hookSpecificOutput": {
|
|
"hookEventName": "PreToolUse",
|
|
"permissionDecision": verdict,
|
|
"permissionDecisionReason": reason,
|
|
}
|
|
});
|
|
Ok(serde_json::to_vec(&out)?)
|
|
}
|
|
|
|
// -- PostToolUse -------------------------------------------------------
|
|
|
|
fn parse_post_tool_use(&self, input: &[u8]) -> Result<PostToolUsePayload, AdapterError> {
|
|
let v: Value = serde_json::from_slice(input)?;
|
|
let tool_name = v
|
|
.get("tool_name")
|
|
.and_then(|x| x.as_str())
|
|
.ok_or_else(|| AdapterError::Parse("missing tool_name".into()))?
|
|
.to_string();
|
|
let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null);
|
|
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,
|
|
updated_output: Option<&Value>,
|
|
context: Option<&str>,
|
|
) -> Result<Vec<u8>, AdapterError> {
|
|
// When there are no changes, return `{}` — Claude Code interprets
|
|
// an empty object as "use original output, no modifications".
|
|
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 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(
|
|
&self,
|
|
payload: &PostToolUsePayload,
|
|
refusal: &str,
|
|
) -> Result<Vec<u8>, AdapterError> {
|
|
let out = json!({
|
|
"hookSpecificOutput": {
|
|
"hookEventName": "PostToolUse",
|
|
"updatedToolOutput": withheld_output(payload, refusal),
|
|
"additionalContext": refusal,
|
|
}
|
|
});
|
|
Ok(serde_json::to_vec(&out)?)
|
|
}
|
|
}
|
|
|
|
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,
|
|
}
|
|
}
|
|
|
|
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<String, Value>>, 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<String>,
|
|
}
|
|
|
|
impl RedactWalk<'_> {
|
|
fn value(&mut self, value: &Value, key: Option<&str>, parent: Option<&Map<String, Value>>) -> 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, Value>>) -> 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, Value>) -> 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<String, Value>>,
|
|
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<ToolOp, AdapterError> {
|
|
let p = tool_input
|
|
.get("file_path")
|
|
.and_then(|x| x.as_str())
|
|
.ok_or_else(|| AdapterError::Parse("missing tool_input.file_path".into()))?;
|
|
Ok(ToolOp::Path {
|
|
path: PathBuf::from(p),
|
|
kind,
|
|
})
|
|
}
|
|
|
|
fn command_op(tool_input: &Value) -> Result<ToolOp, AdapterError> {
|
|
let c = tool_input
|
|
.get("command")
|
|
.and_then(|x| x.as_str())
|
|
.ok_or_else(|| AdapterError::Parse("missing tool_input.command".into()))?;
|
|
Ok(ToolOp::Command { text: c.to_string() })
|
|
}
|