From 265b5ffd3667f958a7c8e2aeb50062f50f9c3071 Mon Sep 17 00:00:00 2001 From: PerryLink Date: Mon, 23 Nov 2026 21:20:20 +0800 Subject: [PATCH 1/2] fix(redact_secrets): scrub tool attachment documents The tool_response_transform leg only saw the tool's textual output and result metadata. Inline document attachments returned by MCP tools (tools.DocumentContent with Text set) were emitted to event subscribers and persisted in the session verbatim, so redact_secrets scrubbed the next LLM call but left the secret in the session file and the event stream. Carry the attachments through the hook protocol: Input grows tool_documents, HookSpecificOutput grows updated_tool_documents (also threaded through the sequential pipeline and strict-output validation), and the dispatcher applies the rewrite to the tool result before emission and recordToolResponse. redact_secrets scrubs each attachment's name, URI, MIME type, and text, mirroring how the before_llm_call leg already handles document parts. Refs: #5011 Signed-off-by: PerryLink <255665900+PerryLink@users.noreply.github.com> ---------------------------------------------------------------------- Validation (on this commit): go build ./... EXIT=0 go vet ./... EXIT=0 gofmt -l clean (empty) go test ./pkg/hooks/... ./pkg/runtime/toolexec ok go test ./... -count=1 EXIT=0, 266 ok packages, no FAIL golangci-lint run --allow-parallel-runners (2.14.0) 0 issues go run ./lint . no offenses (3000 files) go mod tidy -diff EXIT=0 (clean) git apply --check PATCH.diff on base c0062b8a OK (+ targeted tests ok) Red -> green: regression test / probe fails on pristine c0062b8a (emitted result + persisted session contain the secret) and passes on this commit. Evidence : EVIDENCE.md, FILES/ (full changed files + logs) Patch : PATCH.diff (git diff c0062b8a..24b8327) --- docs/configuration/agents/index.md | 4 +- docs/configuration/hooks/index.md | 15 ++- docs/guides/secrets/index.md | 2 +- pkg/hooks/builtins/redact_secrets.go | 65 ++++++++-- pkg/hooks/builtins/redact_secrets_test.go | 87 +++++++++++++ pkg/hooks/contracts_test.go | 2 + pkg/hooks/executor.go | 3 + pkg/hooks/pipeline.go | 5 +- pkg/hooks/pipeline_test.go | 35 ++++++ pkg/hooks/protocol.go | 1 + pkg/hooks/types.go | 25 ++++ pkg/runtime/toolexec/dispatcher.go | 26 ++-- pkg/runtime/toolexec/hooks_input.go | 4 +- .../toolexec/tool_document_redaction_test.go | 117 ++++++++++++++++++ 14 files changed, 364 insertions(+), 27 deletions(-) create mode 100644 pkg/runtime/toolexec/tool_document_redaction_test.go diff --git a/docs/configuration/agents/index.md b/docs/configuration/agents/index.md index 4519382aeb..bfadf8949c 100644 --- a/docs/configuration/agents/index.md +++ b/docs/configuration/agents/index.md @@ -102,7 +102,7 @@ agents: | `add_prompt_files` | array | ✗ | List of file paths whose contents are appended to the system prompt. Useful for including coding standards, guidelines, or additional context. | | `add_prompt_files_depth` | int | ✗ | Also list, by path only, the `add_prompt_files` names found up to this many directory levels below the working directory (`1` = direct subdirectories). Contents are not loaded — the agent reads the ones it needs. Useful in monorepos. Default: `0` (no scan). See [Prompt Files](#prompt-files) below. | | `add_description_parameter` | boolean | ✗ | When `true`, adds agent descriptions as a parameter in tool schemas. Helps with tool selection in multi-agent scenarios. | -| `redact_secrets` | boolean | ✗ | Enabled by default; set `false` to opt out. Scrubs detected secrets (API keys, tokens, private keys, etc.) out of tool-call arguments, outgoing chat messages, and tool output before they reach a tool, the model, or downstream consumers. See [Redacting Secrets](#redacting-secrets) below. | +| `redact_secrets` | boolean | ✗ | Enabled by default; set `false` to opt out. Scrubs detected secrets (API keys, tokens, private keys, etc.) out of tool-call arguments, outgoing chat messages, and tool output — including inline document attachments — before they reach a tool, the model, or downstream consumers. See [Redacting Secrets](#redacting-secrets) below. | | `code_mode_tools` | boolean | ✗ | When `true`, replaces the agent's individual tools with a single tool that runs a JavaScript script calling as many of them as needed in one turn. See [Code Mode](../../features/code-mode/index.md). | | `max_iterations` | int | ✗ | Maximum number of tool-calling loops. Default: unlimited (0). Set this to prevent infinite loops. | | `max_consecutive_tool_calls` | int | ✗ | Maximum consecutive identical tool calls before the agent is terminated, preventing degenerate loops. Default: `5`. | @@ -320,7 +320,7 @@ Secret redaction is enabled by default. The `redact_secrets` field controls scru 1. A `tool_input_transform` built-in hook that scrubs detected secrets from the **arguments of every tool call**, before the tool sees them. 2. A `before_llm_call` built-in hook that scrubs the same patterns from **outgoing chat messages** — message content, multi-part text content, prior reasoning content, and the JSON-encoded arguments of any tool call still in the conversation — before they reach the model provider. -3. A `tool_response_transform` built-in hook that scrubs **tool output at the source**, so the secret never reaches event consumers, the persisted session file, the `post_tool_use` hook input, or the next LLM call. +3. A `tool_response_transform` built-in hook that scrubs **tool output, its display metadata, and its inline document attachments at the source**, so the secret never reaches event consumers, the persisted session file, the `post_tool_use` hook input, or the next LLM call. ```yaml agents: diff --git a/docs/configuration/hooks/index.md b/docs/configuration/hooks/index.md index e5f7b2b240..3d8f2ce691 100644 --- a/docs/configuration/hooks/index.md +++ b/docs/configuration/hooks/index.md @@ -288,7 +288,7 @@ Built-ins are typically zero-config and faster than equivalent shell hooks becau | `add_recent_commits` | `session_start` | _none_, or `[""]` | Adds `git log --oneline -n N`. `N` defaults to 10; pass a positive integer to override. | | `max_iterations` | `before_llm_call` | `[""]` (required) | Hard-stops the agent after `N` model calls. Stateless: the runtime supplies the iteration counter on every dispatch. | | `snapshot` | `session_start`, `turn_start`, `turn_end`, `pre_tool_use`, `post_tool_use`, `session_end` | _none_ | Records filesystem snapshots in a shadow git repo under the Docker Agent data directory. No-op outside git repos; respects the source repo's ignore rules and skips newly-added files larger than 2 MiB. | -| `redact_secrets` | `tool_input_transform`, `before_llm_call`, `tool_response_transform` | _none_ | Scrubs detected secrets (API keys, tokens, private keys, …) out of tool call arguments, outgoing chat content, and tool output. The same builtin handles all three events and dispatches on the event name. Auto-registered on all three events by `redact_secrets: true` on the agent — see [`examples/redact_secrets_hooks.yaml`](https://github.com/docker/docker-agent/blob/main/examples/redact_secrets_hooks.yaml) for the manual wiring. | +| `redact_secrets` | `tool_input_transform`, `before_llm_call`, `tool_response_transform` | _none_ | Scrubs detected secrets (API keys, tokens, private keys, …) out of tool call arguments, outgoing chat content, and tool output, including the text of inline document attachments and the result metadata. The same builtin handles all three events and dispatches on the event name. Auto-registered on all three events by `redact_secrets: true` on the agent — see [`examples/redact_secrets_hooks.yaml`](https://github.com/docker/docker-agent/blob/main/examples/redact_secrets_hooks.yaml) for the manual wiring. | | `transform_json` | `tool_response_transform` | JSON field names | Keeps only the named top-level fields of a JSON object. Nested values are preserved; missing fields are omitted. No expression language or domain validation. | | `limit_large_tool_results` | `tool_response_transform`, `session_end` | _none_ | **Always-on safety hook** — automatically injected by the runtime, no configuration required. When a tool result from the `filesystem`, `shell`, `background_jobs`, `mcp`, or `a2a` categories exceeds 2,000 lines or 50 KiB, the full payload is written to a per-session temp file and replaced in the conversation with a notice plus a bounded excerpt (up to 2,000 excerpt lines; 50 KiB including the notice): the tail for most tools, but the head for the built-in filesystem `read_file`, whose notice suggests a follow-up call with `line`/`limit` to continue reading. If saving the payload fails, a bounded inline excerpt is returned without a file reference. Background-job excerpts retain status metadata before the log tail. The `session_end` leg deletes the temp directory. Internal toolsets (`memory`, `plan`, `tasks`, `think`, …) are not affected. | | `keep_awake` | `session_start`, `session_end` | _none_ | CLI-owned sleep inhibitor, controlled by the disabled-by-default `settings.keep_awake` preference. | @@ -427,8 +427,8 @@ In addition to the common fields, each event ships its own payload: | `tool_input_transform` | `agent_name`, `tool_name`, `tool_use_id`, `tool_category`, `tool_input`, `safety_policy` | | `tool_guard` | `agent_name`, `tool_name`, `tool_use_id`, `tool_category`, `tool_input`, `safety_policy` | | `pre_tool_use` | `agent_name`, `tool_name`, `tool_use_id`, `tool_input` | -| `tool_response_transform` | `tool_name`, `tool_use_id`, `tool_input`, `tool_response`, `tool_result_meta` | -| `post_tool_use` | `agent_name`, `tool_name`, `tool_use_id`, `tool_input`, `tool_response`, `tool_error`, `tool_result_meta` | +| `tool_response_transform` | `tool_name`, `tool_use_id`, `tool_input`, `tool_response`, `tool_result_meta`, `tool_documents` | +| `post_tool_use` | `agent_name`, `tool_name`, `tool_use_id`, `tool_input`, `tool_response`, `tool_error`, `tool_result_meta`, `tool_documents` | | `permission_request` | `agent_name`, `tool_name`, `tool_use_id`, `tool_input` | | `session_start` | `source` — `startup` for each run stream | | `user_prompt_submit` | `prompt` — the text the user just submitted | @@ -659,9 +659,12 @@ The `hook_specific_output` for `tool_response_transform` supports: | ----------------------- | ------ | --------------------------------------------- | | `updated_tool_response` | string | Rewritten tool output (replaces the original) | | `updated_tool_result_meta` | JSON | Replacement for the tool result's display metadata (for example, the recorded diff of an `edit_file` call). A JSON value replaces the metadata, `null` clears it, and omitting the field leaves it unchanged | +| `updated_tool_documents` | array | Replacement for the tool result's inline document attachments, in the `tools.DocumentContent` shape (`name`, `uri`, `mimeType`, `data`, `text`). MCP servers return text resources as documents with `text` set; they are emitted and persisted with the response, so scrub them here too. A present list replaces the attachments (an empty list drops them); omitting the field leaves them unchanged | This is the symmetric counterpart of `tool_input_transform`'s `updated_input`, applied to tool **results** instead of tool **arguments**. The rewrite reaches every downstream consumer — event subscribers, the persisted session file, the `post_tool_use` hook input, and the next LLM call. Use it to truncate excessive output, scrub PII, or normalise tool dialects. The built-in `redact_secrets` registers itself on this event as the third leg of the redact_secrets feature. +Hooks on `tool_response_transform` and `post_tool_use` also receive `tool_documents`, the inline document attachments the tool returned. MCP servers return text resources this way (the payload is in `text`), and those documents are emitted to event subscribers and persisted in the session next to the textual output. Only `tool_response_transform` hooks can rewrite the list, with `updated_tool_documents`; the rewritten attachments are what gets emitted and persisted, and `post_tool_use` hooks receive the already-transformed list. `redact_secrets` scrubs each attachment's name, URI, MIME type, and text, so a secret carried in an MCP inline-text resource never reaches the session file or the event stream. + Hooks on `tool_response_transform` and `post_tool_use` also receive `tool_result_meta`, the structured display metadata a tool recorded alongside its text output (the TUI renders completed `edit_file` diffs from it). Only `tool_response_transform` hooks can rewrite it, with `updated_tool_result_meta` (independently of `updated_tool_response`); the rewritten metadata is what gets emitted and persisted. `post_tool_use` hooks receive the already-transformed metadata and cannot change it. `redact_secrets` also scrubs this metadata, and clears it when it cannot be serialized safely. ### Composing transformations @@ -673,7 +676,7 @@ Hooks for the following events run **sequentially in configuration order**: | `tool_input_transform` | `updated_input` | `tool_input` with the patch applied | | `pre_tool_use` (default lane) | `updated_input` | `tool_input` with the patch applied | | `before_llm_call` | `updated_messages` | The rewritten `messages` array | -| `tool_response_transform` | `updated_tool_response`, `updated_tool_result_meta` | The rewritten `tool_response` string and `tool_result_meta` | +| `tool_response_transform` | `updated_tool_response`, `updated_tool_result_meta`, `updated_tool_documents` | The rewritten `tool_response` string, `tool_result_meta`, and `tool_documents` list | Every matching hook on these events participates in the sequence, whether it rewrites, observes, or returns a verdict. Each hook sees the most recent @@ -685,7 +688,9 @@ arguments are preserved; nested objects are replaced, not deep-merged. An empty patch does not clear the arguments. Omitting a key no longer removes it; this patch protocol does not support key deletion. `updated_messages` replaces the entire message array, with an empty array treated as no rewrite. An explicit empty -`updated_tool_response` **does** clear the response. +`updated_tool_response` **does** clear the response. A present +`updated_tool_documents` list, including an empty one, replaces the +attachments; omitting the field keeps the current list. Verdicts still aggregate across all matching hooks: a later allow cannot undo a denial, and `pre_tool_use` keeps `deny > ask > allow` precedence. Blocking diff --git a/docs/guides/secrets/index.md b/docs/guides/secrets/index.md index 99470b8db5..2bfac0be1c 100644 --- a/docs/guides/secrets/index.md +++ b/docs/guides/secrets/index.md @@ -262,7 +262,7 @@ Secret redaction is enabled by default as a defense in depth. Set `redact_secret - the arguments of every outgoing tool call (before the tool sees them), - every outgoing chat message (before the model provider sees them), and -- every tool's output (before it reaches event consumers, the persisted session file, the `post_tool_use` hook input, or the next LLM call). +- every tool's output, including the text of the inline document attachments it returns (before they reach event consumers, the persisted session file, the `post_tool_use` hook input, or the next LLM call). ```yaml agents: diff --git a/pkg/hooks/builtins/redact_secrets.go b/pkg/hooks/builtins/redact_secrets.go index 49dcd519be..0d74be04ca 100644 --- a/pkg/hooks/builtins/redact_secrets.go +++ b/pkg/hooks/builtins/redact_secrets.go @@ -12,6 +12,7 @@ import ( "github.com/docker/docker-agent/pkg/chat" "github.com/docker/docker-agent/pkg/hooks" + "github.com/docker/docker-agent/pkg/tools" ) // RedactSecrets is the registered name of the builtin that scrubs @@ -25,10 +26,11 @@ import ( // explicit legacy YAML entries. // - [hooks.EventBeforeLLMCall] — scrub outgoing CHAT CONTENT // before each model call (returns UpdatedMessages). -// - [hooks.EventToolResponseTransform] — scrub tool OUTPUT before it -// reaches event consumers, the persisted session, the -// post_tool_use hook, or the next LLM call (returns -// UpdatedToolResponse). +// - [hooks.EventToolResponseTransform] — scrub tool OUTPUT, result +// metadata, and inline document attachments before they reach event +// consumers, the persisted session, the post_tool_use hook, or the +// next LLM call (returns UpdatedToolResponse / UpdatedToolResultMeta +// / UpdatedToolDocuments). // // The agent-level redact_secrets flag is shorthand for wiring the // builtin into all three events at once via [ApplyAgentDefaults]; the @@ -123,15 +125,22 @@ func redactOutgoingMessages(in *hooks.Input) *hooks.Output { } } -// redactToolOutput scrubs the tool's textual response. The payload is -// carried as `any` in the wire protocol because some MCP tools may -// produce structured shapes; the dispatcher's record path only feeds -// strings to the LLM today, so anything else is out of scope. +// redactToolOutput scrubs the tool's textual response, its display +// metadata, and its inline document attachments. The payload is carried +// as `any` in the wire protocol because some MCP tools may produce +// structured shapes; the dispatcher's record path only feeds strings to +// the LLM today, so anything else is out of scope. // // Returning a pointer-typed [HookSpecificOutput.UpdatedToolResponse] // preserves the empty-string-vs-no-rewrite distinction (see the field // docs); a redaction that wipes the entire output to "" is still // honoured by the runtime. +// +// Attachments are scrubbed because MCP servers return text resources as +// [tools.DocumentContent] with Text set. The dispatcher emits and +// persists those documents verbatim, so without this leg the secret +// stays in the session file and the event stream even though the next +// LLM call re-scrubs it. func redactToolOutput(in *hooks.Input) *hooks.Output { out := &hooks.HookSpecificOutput{HookEventName: hooks.EventToolResponseTransform} if original, ok := in.ToolResponse.(string); ok { @@ -142,12 +151,50 @@ func redactToolOutput(in *hooks.Input) *hooks.Output { if meta, changed := redactResultMeta(in.ToolResultMeta); changed { out.UpdatedToolResultMeta = meta } - if out.UpdatedToolResponse == nil && out.UpdatedToolResultMeta == nil { + if documents, changed := redactToolDocuments(in.ToolDocuments); changed { + out.UpdatedToolDocuments = documents + } + if out.UpdatedToolResponse == nil && out.UpdatedToolResultMeta == nil && out.UpdatedToolDocuments == nil { return nil } return &hooks.Output{HookSpecificOutput: out} } +// redactToolDocuments scrubs every string field of the tool result's +// inline document attachments. MCP text resources arrive as +// [tools.DocumentContent] with Text set and are emitted and persisted as +// [chat.Document] parts, so the tool_response_transform leg has to cover +// Name/URI/MimeType/Text as well — matching what the before_llm_call leg +// already does for document parts in chat messages. Binary Data is +// base64 and left alone. +// +// Returns a clone with only the rewritten entries differing from the +// input, and changed=false (nil documents) when nothing matched so the +// runtime takes the no-rewrite fast path. +func redactToolDocuments(documents []tools.DocumentContent) ([]tools.DocumentContent, bool) { + if len(documents) == 0 { + return nil, false + } + out := make([]tools.DocumentContent, len(documents)) + changed := false + for i, doc := range documents { + out[i] = tools.DocumentContent{ + Name: portcullis.Redact(doc.Name), + URI: portcullis.Redact(doc.URI), + MimeType: portcullis.Redact(doc.MimeType), + Data: doc.Data, + Text: portcullis.Redact(doc.Text), + } + if out[i] != doc { + changed = true + } + } + if !changed { + return nil, false + } + return out, true +} + func redactResultMeta(meta any) (json.RawMessage, bool) { if meta == nil { return nil, false diff --git a/pkg/hooks/builtins/redact_secrets_test.go b/pkg/hooks/builtins/redact_secrets_test.go index 26e3cf921d..97f7ac4a07 100644 --- a/pkg/hooks/builtins/redact_secrets_test.go +++ b/pkg/hooks/builtins/redact_secrets_test.go @@ -347,6 +347,93 @@ func TestRedactSecretsToolOutputIgnoresNonStringResponse(t *testing.T) { assert.Nil(t, out) } +// TestRedactSecretsScrubsToolDocuments: MCP text resources come back as +// tools.DocumentContent with Text set and are emitted and persisted +// verbatim. The tool_response_transform leg must scrub them too, and +// must leave binary data and clean documents byte-for-byte. +func TestRedactSecretsScrubsToolDocuments(t *testing.T) { + t.Parallel() + + secret := fakeGitHubPAT() + in := &hooks.Input{ + HookEventName: hooks.EventToolResponseTransform, + ToolName: "mcp_fetch", + ToolDocuments: []tools.DocumentContent{ + {Name: "notes.md", URI: "mcp://docs/notes.md", MimeType: "text/markdown", Text: "token=" + secret}, + {Name: "clean.md", MimeType: "text/markdown", Text: "nothing to see"}, + {Name: "report.pdf", MimeType: "application/pdf", Data: "cGRm"}, + }, + } + + out, err := redactSecrets(t.Context(), in, nil) + require.NoError(t, err) + require.NotNil(t, out) + require.NotNil(t, out.HookSpecificOutput) + docs := out.HookSpecificOutput.UpdatedToolDocuments + require.Len(t, docs, 3) + assert.NotContains(t, docs[0].Text, secret) + assert.Contains(t, docs[0].Text, portcullis.Marker) + assert.Equal(t, "nothing to see", docs[1].Text, "clean attachment must survive unchanged") + assert.Equal(t, "cGRm", docs[2].Data, "binary attachment must survive unchanged") + assert.Contains(t, in.ToolDocuments[0].Text, secret, "the caller's slice must not be mutated") +} + +// TestRedactSecretsScrubsToolDocumentStringFields pins the non-text +// fields of an attachment: name and MIME type are persisted as the +// document's display metadata and URI is emitted with the tool result, +// so a secret hiding there leaks through the same path. +func TestRedactSecretsScrubsToolDocumentStringFields(t *testing.T) { + t.Parallel() + + secret := fakeGitHubPAT() + for _, field := range []string{"name", "uri", "mime"} { + t.Run(field, func(t *testing.T) { + t.Parallel() + + doc := tools.DocumentContent{Name: "notes.md", URI: "mcp://docs/notes.md", MimeType: "text/markdown", Text: "clean"} + switch field { + case "name": + doc.Name = secret + ".md" + case "uri": + doc.URI = "mcp://docs/?token=" + secret + case "mime": + doc.MimeType = "text/plain; token=" + secret + } + + out, err := redactSecrets(t.Context(), &hooks.Input{ + HookEventName: hooks.EventToolResponseTransform, + ToolDocuments: []tools.DocumentContent{doc}, + }, nil) + require.NoError(t, err) + require.NotNil(t, out, "a hit in any string field must produce a rewrite") + require.Len(t, out.HookSpecificOutput.UpdatedToolDocuments, 1) + updated := out.HookSpecificOutput.UpdatedToolDocuments[0] + assert.NotContains(t, updated.Name, secret) + assert.NotContains(t, updated.URI, secret) + assert.NotContains(t, updated.MimeType, secret) + assert.NotContains(t, updated.Text, secret) + assert.Contains(t, updated.Name+updated.URI+updated.MimeType, portcullis.Marker) + }) + } +} + +// TestRedactSecretsToolDocumentsNoOpOnCleanAttachments: no secret in +// the attachments (and no textual output) ⇒ nil Output so the runtime +// keeps the no-rewrite fast path. +func TestRedactSecretsToolDocumentsNoOpOnCleanAttachments(t *testing.T) { + t.Parallel() + + out, err := redactSecrets(t.Context(), &hooks.Input{ + HookEventName: hooks.EventToolResponseTransform, + ToolDocuments: []tools.DocumentContent{ + {Name: "clean.md", MimeType: "text/markdown", Text: "nothing to see"}, + {Name: "report.pdf", MimeType: "application/pdf", Data: "cGRm"}, + }, + }, nil) + require.NoError(t, err) + assert.Nil(t, out) +} + // TestRedactSecretsLenientOnUnsupportedEvent: configuring the builtin // under an event that doesn't know how to handle it (e.g. session_start) // must be a no-op rather than crash the run loop. The event-keyed diff --git a/pkg/hooks/contracts_test.go b/pkg/hooks/contracts_test.go index 610b6c38f2..49cbe15d4f 100644 --- a/pkg/hooks/contracts_test.go +++ b/pkg/hooks/contracts_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/require" "github.com/docker/docker-agent/pkg/hooks/events" + "github.com/docker/docker-agent/pkg/tools" ) func TestEventContractsMatchConfigurationAndSchema(t *testing.T) { @@ -70,6 +71,7 @@ func TestStrictOutputContractCapabilities(t *testing.T) { {"input", &Output{HookSpecificOutput: &HookSpecificOutput{UpdatedInput: map[string]any{}}}, c.Rewrite == events.RewriteToolInput}, {"response", &Output{HookSpecificOutput: &HookSpecificOutput{UpdatedToolResponse: new("")}}, c.Rewrite == events.RewriteToolResponse}, {"result meta", &Output{HookSpecificOutput: &HookSpecificOutput{UpdatedToolResultMeta: json.RawMessage(`null`)}}, c.Rewrite == events.RewriteToolResponse}, + {"documents", &Output{HookSpecificOutput: &HookSpecificOutput{UpdatedToolDocuments: []tools.DocumentContent{{Name: "notes.md"}}}}, c.Rewrite == events.RewriteToolResponse}, {"context", NewAdditionalContextOutput(EventType(c.Name), "context"), c.Context}, {"metadata", &Output{HookSpecificOutput: &HookSpecificOutput{Metadata: map[string]string{}}}, c.Metadata}, {"summary", &Output{HookSpecificOutput: &HookSpecificOutput{Summary: "summary"}}, c.Summary}, diff --git a/pkg/hooks/executor.go b/pkg/hooks/executor.go index 9fb2e65196..ebb880376d 100644 --- a/pkg/hooks/executor.go +++ b/pkg/hooks/executor.go @@ -548,6 +548,9 @@ func aggregate(results []hookResult, event EventType) *Result { if contract.Rewrite == events.RewriteToolResponse && hso.UpdatedToolResultMeta != nil { final.UpdatedToolResultMeta = hso.UpdatedToolResultMeta } + if contract.Rewrite == events.RewriteToolResponse && hso.UpdatedToolDocuments != nil { + final.UpdatedToolDocuments = hso.UpdatedToolDocuments + } if contract.Metadata && len(hso.Metadata) > 0 { // Metadata from every matching hook is merged so multiple // hooks can each contribute keys. On a key clash the last diff --git a/pkg/hooks/pipeline.go b/pkg/hooks/pipeline.go index 3e973a8ca8..922bf942b3 100644 --- a/pkg/hooks/pipeline.go +++ b/pkg/hooks/pipeline.go @@ -59,7 +59,7 @@ func rewrittenInput(input Input, event EventType, out *HookSpecificOutput) (Inpu } input.Messages = out.UpdatedMessages case events.RewriteToolResponse: - if out.UpdatedToolResponse == nil && out.UpdatedToolResultMeta == nil { + if out.UpdatedToolResponse == nil && out.UpdatedToolResultMeta == nil && out.UpdatedToolDocuments == nil { return input, false } if out.UpdatedToolResponse != nil { @@ -68,6 +68,9 @@ func rewrittenInput(input Input, event EventType, out *HookSpecificOutput) (Inpu if out.UpdatedToolResultMeta != nil { input.ToolResultMeta = out.UpdatedToolResultMeta } + if out.UpdatedToolDocuments != nil { + input.ToolDocuments = out.UpdatedToolDocuments + } default: return input, false } diff --git a/pkg/hooks/pipeline_test.go b/pkg/hooks/pipeline_test.go index 6a116fd62a..5d64badfca 100644 --- a/pkg/hooks/pipeline_test.go +++ b/pkg/hooks/pipeline_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/require" "github.com/docker/docker-agent/pkg/chat" + "github.com/docker/docker-agent/pkg/tools" ) func TestPipelineToolInputPatchesCompose(t *testing.T) { @@ -113,6 +114,39 @@ func TestPipelineToolResponseComposesAndPreservesEmptyRewrite(t *testing.T) { } } +// TestPipelineToolDocumentsCompose pins that attachment rewrites ride the +// same sequential pipeline as the response string: the hook that runs +// second sees the first hook's list, the runtime receives the last +// non-nil list, and the caller's input is left untouched. +func TestPipelineToolDocumentsCompose(t *testing.T) { + t.Parallel() + + registry := NewRegistry() + require.NoError(t, registry.RegisterBuiltin("rewrite", func(_ context.Context, in *Input, _ []string) (*Output, error) { + require.Len(t, in.ToolDocuments, 1) + assert.Equal(t, "notes.md", in.ToolDocuments[0].Name) + return &Output{HookSpecificOutput: &HookSpecificOutput{UpdatedToolDocuments: []tools.DocumentContent{ + {Name: "redacted.md", MimeType: "text/markdown", Text: "[REDACTED]"}, + }}}, nil + })) + require.NoError(t, registry.RegisterBuiltin("observe", func(_ context.Context, in *Input, _ []string) (*Output, error) { + require.Len(t, in.ToolDocuments, 1) + assert.Equal(t, "redacted.md", in.ToolDocuments[0].Name) + return nil, nil + })) + exec := NewExecutorWithRegistry(&Config{ToolResponseTransform: []MatcherConfig{{Hooks: []Hook{ + {Type: HookTypeBuiltin, Command: "rewrite"}, + {Type: HookTypeBuiltin, Command: "observe"}, + }}}}, t.TempDir(), nil, registry) + in := &Input{ToolName: "mcp_fetch", ToolDocuments: []tools.DocumentContent{{Name: "notes.md", Text: "secret"}}} + + result, err := exec.Dispatch(t.Context(), EventToolResponseTransform, in) + require.NoError(t, err) + require.Len(t, result.UpdatedToolDocuments, 1) + assert.Equal(t, "redacted.md", result.UpdatedToolDocuments[0].Name) + assert.Equal(t, "notes.md", in.ToolDocuments[0].Name, "caller input must not be mutated") +} + func TestPipelineToolInputEmptyPatch(t *testing.T) { t.Parallel() @@ -142,6 +176,7 @@ func TestPipelineNoRewrite(t *testing.T) { assert.Nil(t, result.ModifiedInput) assert.Nil(t, result.UpdatedMessages) assert.Nil(t, result.UpdatedToolResponse) + assert.Nil(t, result.UpdatedToolDocuments) }) } } diff --git a/pkg/hooks/protocol.go b/pkg/hooks/protocol.go index e571bca372..18a2825ead 100644 --- a/pkg/hooks/protocol.go +++ b/pkg/hooks/protocol.go @@ -76,6 +76,7 @@ func validateOutput(event EventType, out *Output, strict bool) error { {"updated_messages", hso.UpdatedMessages != nil, c.Rewrite == events.RewriteMessages}, {"updated_tool_response", hso.UpdatedToolResponse != nil, c.Rewrite == events.RewriteToolResponse}, {"updated_tool_result_meta", hso.UpdatedToolResultMeta != nil, c.Rewrite == events.RewriteToolResponse}, + {"updated_tool_documents", hso.UpdatedToolDocuments != nil, c.Rewrite == events.RewriteToolResponse}, {"metadata", hso.Metadata != nil, c.Metadata}, {"additional_context", hso.AdditionalContext != "", c.Context}, {"instruction_context", hso.InstructionContext != nil, c.Instructions}, diff --git a/pkg/hooks/types.go b/pkg/hooks/types.go index aa4a562d38..c593d44f9c 100644 --- a/pkg/hooks/types.go +++ b/pkg/hooks/types.go @@ -385,6 +385,15 @@ type Input struct { ToolError bool `json:"tool_error,omitempty"` ToolResultMeta any `json:"tool_result_meta,omitempty"` + // ToolDocuments carries the tool result's inline document attachments + // for [EventToolResponseTransform] and [EventPostToolUse]. MCP servers + // return text resources as [tools.DocumentContent] with Text set; those + // documents are emitted to event subscribers and persisted in the + // session next to the textual output, so response transformers need to + // see them to scrub their string fields too. Data is opaque base64 and + // is never inspected. + ToolDocuments []tools.DocumentContent `json:"tool_documents,omitempty"` + // Messages is the conversation snapshot the runtime is about to send // to the model. Populated only for [EventBeforeLLMCall] dispatches // where rewriting is meaningful; nil for every other event so the @@ -686,6 +695,17 @@ type HookSpecificOutput struct { // JSON null clears metadata; nil leaves it unchanged. UpdatedToolResultMeta json.RawMessage `json:"updated_tool_result_meta,omitempty"` + // UpdatedToolDocuments replaces the tool result's inline document + // attachments on an [EventToolResponseTransform] response, before the + // runtime emits them, records them in the session, hands them to + // post_tool_use, or sends them to the next LLM call. nil leaves them + // unchanged; a non-nil slice (including an empty one, which drops every + // attachment) replaces them. + // + // Hooks run in config order; each sees the preceding rewrite. The last + // non-nil rewrite is returned. + UpdatedToolDocuments []tools.DocumentContent `json:"updated_tool_documents,omitempty"` + // Transition is a control hook's route request. Only // [EventBeforeAgentRun] and [EventAfterAgentComplete] accept it; any // other event rejects output that carries one. @@ -744,6 +764,11 @@ type Result struct { // "explicitly cleared" (empty string) from "no rewrite" (nil). UpdatedToolResponse *string UpdatedToolResultMeta json.RawMessage + // UpdatedToolDocuments is the rewritten attachment list produced by an + // [EventToolResponseTransform] hook. nil means "no rewrite"; a non-nil + // slice (possibly empty) replaces the tool result's documents before + // emission and persistence. + UpdatedToolDocuments []tools.DocumentContent // Metadata aggregates the key/value annotations contributed by // [EventPermissionRequest], [EventToolGuard] and control-event hooks. The runtime diff --git a/pkg/runtime/toolexec/dispatcher.go b/pkg/runtime/toolexec/dispatcher.go index de6a1c96dc..ff3453cb7c 100644 --- a/pkg/runtime/toolexec/dispatcher.go +++ b/pkg/runtime/toolexec/dispatcher.go @@ -1071,7 +1071,7 @@ func (r callRuntime) RunTool(ctx context.Context, tc tools.ToolCall, tool tools. } else if result != nil { response = *result } - response.Output, response.Meta = c.transformToolResult(ctx, response.Output, response.IsError, response.Meta) + response.Output, response.Meta, response.Documents = c.transformToolResult(ctx, response.Output, response.IsError, response.Meta, response.Documents) c.em.EmitToolCallResponse(tc.ID, tool, &response, response.Output, c.a.Name()) return result, err } @@ -1175,7 +1175,7 @@ func (c *call) invoke(ctx context.Context, spanName string, exec func(ctx contex // only paid when at least one hook is configured for the event, so // agents that haven't opted into output rewriting take the cheap // path through Dispatch's `exec.Has(event)` short-circuit. - res.Output, res.Meta = c.transformToolResult(ctx, res.Output, res.IsError, res.Meta) + res.Output, res.Meta, res.Documents = c.transformToolResult(ctx, res.Output, res.IsError, res.Meta, res.Documents) // gen_ai.tool.call.result captures the post-transform output so the // span matches what the LLM actually saw on the next turn (any @@ -1204,11 +1204,17 @@ func (c *call) invoke(ctx context.Context, spanName string, exec func(ctx contex // the persisted session file, the input the post_tool_use hook sees, // and the messages going to the next LLM call. func (c *call) applyToolResponseTransform(ctx context.Context, payload string, isError bool) string { - output, _ := c.transformToolResult(ctx, payload, isError, nil) + output, _, _ := c.transformToolResult(ctx, payload, isError, nil, nil) return output } -func (c *call) transformToolResult(ctx context.Context, payload string, isError bool, meta any) (output string, transformedMeta any) { +// transformToolResult fires [hooks.EventToolResponseTransform] and returns +// the hook-supplied rewrites for the textual output, the display metadata, +// and the inline document attachments. Documents ride through the transform +// because emission and recordToolResponse both read them off the result: +// skipping them leaks attachment text (MCP inline-text resources) verbatim +// into the event stream and the persisted session. +func (c *call) transformToolResult(ctx context.Context, payload string, isError bool, meta any, documents []tools.DocumentContent) (output string, transformedMeta any, transformedDocuments []tools.DocumentContent) { defer func() { output = builtins.BoundToolResult(c.tool.Category, c.tool.Name, output, "The full result was not saved by the output limiter; narrow the tool query to retrieve the part you need.") }() @@ -1219,17 +1225,18 @@ func (c *call) transformToolResult(ctx context.Context, payload string, isError } } if c.d.Hooks == nil { - return payload, meta + return payload, meta, documents } in := NewPostToolHooksInput(c.sess, c.tc, &tools.ToolCallResult{Output: payload, IsError: isError, Meta: meta}) in.ToolCategory = c.tool.Category + in.ToolDocuments = documents result := c.d.Hooks.Dispatch(ctx, c.a, hooks.EventToolResponseTransform, in) // A canceled hook can discard its rewrite; never fall back to the untransformed payload. if ctx.Err() != nil { - return c.cancellationMessage(ctx), nil + return c.cancellationMessage(ctx), nil, nil } if result == nil { - return payload, meta + return payload, meta, documents } if result.UpdatedToolResultMeta != nil { meta = result.UpdatedToolResultMeta @@ -1237,7 +1244,10 @@ func (c *call) transformToolResult(ctx context.Context, payload string, isError if result.UpdatedToolResponse != nil { payload = *result.UpdatedToolResponse } - return payload, meta + if result.UpdatedToolDocuments != nil { + documents = result.UpdatedToolDocuments + } + return payload, meta, documents } // translateError converts a tool-handler error into a [tools.ToolCallResult] diff --git a/pkg/runtime/toolexec/hooks_input.go b/pkg/runtime/toolexec/hooks_input.go index 0a66b40c54..2db1f64372 100644 --- a/pkg/runtime/toolexec/hooks_input.go +++ b/pkg/runtime/toolexec/hooks_input.go @@ -25,13 +25,15 @@ func NewHooksInput(sess *session.Session, toolCall tools.ToolCall) *hooks.Input // NewPostToolHooksInput builds a [hooks.Input] for the post-tool-use event. // It enriches the common fields built by [NewHooksInput] with the tool -// result so post-tool-use hooks can inspect the response and error flag. +// result so post-tool-use hooks can inspect the response, the error flag, +// the display metadata, and the inline document attachments. func NewPostToolHooksInput(sess *session.Session, toolCall tools.ToolCall, res *tools.ToolCallResult) *hooks.Input { input := NewHooksInput(sess, toolCall) if res != nil { input.ToolResponse = res.Output input.ToolError = res.IsError input.ToolResultMeta = res.Meta + input.ToolDocuments = res.Documents } return input } diff --git a/pkg/runtime/toolexec/tool_document_redaction_test.go b/pkg/runtime/toolexec/tool_document_redaction_test.go new file mode 100644 index 0000000000..4bf7d4e895 --- /dev/null +++ b/pkg/runtime/toolexec/tool_document_redaction_test.go @@ -0,0 +1,117 @@ +package toolexec_test + +import ( + "context" + "encoding/json" + "testing" + + "github.com/docker/portcullis" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/agent" + "github.com/docker/docker-agent/pkg/chat" + "github.com/docker/docker-agent/pkg/hooks" + "github.com/docker/docker-agent/pkg/hooks/builtins" + "github.com/docker/docker-agent/pkg/internal/portcullistest" + "github.com/docker/docker-agent/pkg/runtime/toolexec" + "github.com/docker/docker-agent/pkg/session" + "github.com/docker/docker-agent/pkg/tools" +) + +// TestDispatcherRedactsInlineTextToolDocuments pins that the +// tool_response_transform rewrite also covers the text of inline tool +// attachments. MCP servers return text resources as +// tools.DocumentContent{Text: ...}; those documents are emitted to event +// subscribers and persisted in the session by recordToolResponse, so a +// transform that only rewrites the textual output leaves the secret in +// both places. +func TestDispatcherRedactsInlineTextToolDocuments(t *testing.T) { + t.Parallel() + + secret := portcullistest.FakeGitHubPAT("cxLeRrvbJfmYdUtr70xnNE3Q7Gvli4") + reg := hooks.NewRegistry() + require.NoError(t, builtins.Register(reg)) + require.NoError(t, reg.RegisterBuiltin("observe", func(context.Context, *hooks.Input, []string) (*hooks.Output, error) { + return nil, nil + })) + cfg := &hooks.Config{ + ToolResponseTransform: []hooks.MatcherConfig{{Matcher: "*", Hooks: []hooks.Hook{{Type: hooks.HookTypeBuiltin, Command: builtins.RedactSecrets}}}}, + PostToolUse: []hooks.MatcherConfig{{Matcher: "*", Hooks: []hooks.Hook{{Type: hooks.HookTypeBuiltin, Command: "observe"}}}}, + } + hd := &postCapturingDispatcher{execHookDispatcher: &execHookDispatcher{exec: hooks.NewExecutorWithRegistry(cfg, t.TempDir(), nil, reg)}} + sess := session.New() + sess.ToolsApproved = true + a := newAgent() + tool := tools.Tool{Name: "fetch", Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + return &tools.ToolCallResult{ + Output: "fetched resource", + Documents: []tools.DocumentContent{ + {Name: "notes.md", URI: "mcp://docs/notes.md", MimeType: "text/markdown", Text: "token=" + secret}, + {Name: "clean.md", MimeType: "text/markdown", Text: "nothing to see"}, + {Name: "report.pdf", MimeType: "application/pdf", Data: "cGRm"}, + }, + }, nil + }} + emitter := &metaEmitter{} + dispatcher := &toolexec.Dispatcher{AgentFor: func(*session.Session) *agent.Agent { return a }, Hooks: hd} + dispatcher.Process(t.Context(), sess, []tools.ToolCall{{ID: "fetch", Function: tools.FunctionCall{Name: "fetch", Arguments: `{}`}}}, []tools.Tool{tool}, emitter) + + require.NotNil(t, emitter.result) + require.Len(t, emitter.result.Documents, 3) + + // The emitted result feeds SSE / ACP / TUI consumers. + event, err := json.Marshal(emitter.result) + require.NoError(t, err) + assert.NotContains(t, string(event), secret, "emitted attachment text must be scrubbed") + assert.Contains(t, string(event), portcullis.Marker) + + // The persisted session message feeds every later turn and export. + stored, err := json.Marshal(sess) + require.NoError(t, err) + assert.NotContains(t, string(stored), secret, "persisted attachment text must be scrubbed") + assert.Contains(t, string(stored), portcullis.Marker) + + // Only secret-bearing text is rewritten; clean and binary documents + // must survive byte-for-byte. + assert.Equal(t, "nothing to see", emitter.result.Documents[1].Text) + assert.Equal(t, "cGRm", emitter.result.Documents[2].Data) + + msg := lastToolMessage(t, sess) + require.Len(t, msg.MultiContent, 4) + require.NotNil(t, msg.MultiContent[1].Document) + assert.NotContains(t, msg.MultiContent[1].Document.Source.InlineText, secret) + assert.Contains(t, msg.MultiContent[1].Document.Source.InlineText, portcullis.Marker) + + // post_tool_use sees the already-rewritten attachments, matching the + // documented "post_tool_use receives the transformed result" contract. + require.NotNil(t, hd.postInput) + require.Len(t, hd.postInput.ToolDocuments, 3) + assert.NotContains(t, hd.postInput.ToolDocuments[0].Text, secret) + assert.Equal(t, "nothing to see", hd.postInput.ToolDocuments[1].Text) +} + +// postCapturingDispatcher records the post_tool_use input so tests can +// assert the hook sees the already-rewritten attachments. +type postCapturingDispatcher struct { + *execHookDispatcher + + postInput *hooks.Input +} + +func (d *postCapturingDispatcher) Dispatch(ctx context.Context, a *agent.Agent, event hooks.EventType, in *hooks.Input) *hooks.Result { + if event == hooks.EventPostToolUse { + d.postInput = in + } + return d.execHookDispatcher.Dispatch(ctx, a, event, in) +} + +func lastToolMessage(t *testing.T, sess *session.Session) chat.Message { + t.Helper() + require.NotEmpty(t, sess.Messages) + item := sess.Messages[len(sess.Messages)-1] + require.NotNil(t, item.Message) + msg := item.Message.Message + require.Equal(t, chat.MessageRoleTool, msg.Role) + return msg +} From 649c3e38d4b9ed18cedd43f0abd1fb5db96b2711 Mon Sep 17 00:00:00 2001 From: PerryLink Date: Tue, 24 Nov 2026 22:38:27 +0800 Subject: [PATCH 2/2] fix(redact_secrets): redact before configured transform hooks ApplyAgentDefaults appended the auto-injected redact_secrets tool_response_transform entry after the agent's configured transforms, so a configured hook ran on unredacted input. Command hooks receive the whole hook input as JSON on stdin (pkg/hooks/handler.go), so a hook that archives its input recorded the raw tool output, result metadata, and - once the hook protocol started carrying them - the inline document attachments MCP servers return as text resources, even with redaction enabled. When the agent-level redact_secrets flag is on (the default) and the agent configures tool_response_transform hooks, inject a named redaction pass ahead of them, and keep the auto-injected trailing entry as the final scrub so a rewrite that reintroduces a secret is still caught before emission, persistence, and the next LLM call. The leading pass carries its own Name because the executor deduplicates identical hooks: without it the trailing pass would collapse into the leading one. With no configured transforms no leading pass is injected, so the effective config and the per-tool-result cost of the common case are unchanged. Tag HookSpecificOutput.updated_tool_documents with omitzero instead of omitempty, so an empty but non-nil slice - the explicit "remove every attachment" rewrite - keeps its [] wire form when a Go hook marshals its output instead of being dropped back to "leave them unchanged". Tests: - TestConfiguredCommandHookReceivesRedactedToolDocuments configures a real command hook that captures its stdin, lets ApplyAgentDefaults inject the auto redactor, dispatches tool_response_transform with an inline-text document carrying a PAT, and asserts the captured stdin has no raw secret (it is the redacted form). - TestApplyAgentDefaultsOrdersTransformsAroundRedaction pins the leading/trailing placement and their distinct identity. - TestToolDocumentsJSONRoundTripDistinguishesNilFromEmpty round-trips nil (field omitted) vs an empty list (present [], kept as a rewrite). Refs: #5017 ---------------------------------------------------------------------- Validation (on this commit): go build ./... EXIT=0 go vet ./... EXIT=0 gofmt -l clean (empty) go test ./pkg/hooks/... ./pkg/runtime/toolexec/... ok go test ./... -count=1 EXIT=0, 266 ok packages golangci-lint run --allow-parallel-runners (2.14.0) 0 issues go run ./lint . no offenses (3004 files) go mod tidy --diff EXIT=0 (clean) Red -> green: on pristine 265b5ffd the new command-hook test fails with the raw PAT in the captured stdin (and the ordering / JSON round-trip tests fail too); all three pass with this change. Signed-off-by: PerryLink <255665900+PerryLink@users.noreply.github.com> -------- --- docs/configuration/agents/index.md | 2 +- docs/configuration/hooks/index.md | 9 ++- pkg/hooks/builtins/builtins.go | 43 +++++++++- pkg/hooks/builtins/builtins_test.go | 72 +++++++++++++---- .../builtins/capture_stdin_other_test.go | 14 ++++ .../builtins/capture_stdin_windows_test.go | 14 ++++ .../redact_secrets_hook_boundary_test.go | 78 +++++++++++++++++++ pkg/hooks/tool_documents_json_test.go | 62 +++++++++++++++ pkg/hooks/types.go | 9 ++- 9 files changed, 280 insertions(+), 23 deletions(-) create mode 100644 pkg/hooks/builtins/capture_stdin_other_test.go create mode 100644 pkg/hooks/builtins/capture_stdin_windows_test.go create mode 100644 pkg/hooks/builtins/redact_secrets_hook_boundary_test.go create mode 100644 pkg/hooks/tool_documents_json_test.go diff --git a/docs/configuration/agents/index.md b/docs/configuration/agents/index.md index bfadf8949c..963dc982c7 100644 --- a/docs/configuration/agents/index.md +++ b/docs/configuration/agents/index.md @@ -320,7 +320,7 @@ Secret redaction is enabled by default. The `redact_secrets` field controls scru 1. A `tool_input_transform` built-in hook that scrubs detected secrets from the **arguments of every tool call**, before the tool sees them. 2. A `before_llm_call` built-in hook that scrubs the same patterns from **outgoing chat messages** — message content, multi-part text content, prior reasoning content, and the JSON-encoded arguments of any tool call still in the conversation — before they reach the model provider. -3. A `tool_response_transform` built-in hook that scrubs **tool output, its display metadata, and its inline document attachments at the source**, so the secret never reaches event consumers, the persisted session file, the `post_tool_use` hook input, or the next LLM call. +3. A `tool_response_transform` built-in hook that scrubs **tool output, its display metadata, and its inline document attachments at the source**, so the secret never reaches event consumers, the persisted session file, the `post_tool_use` hook input, or the next LLM call. When other `tool_response_transform` hooks are configured, the auto-injected redactor runs once **before** them — command hooks receive the whole hook input as JSON on stdin, so they never see raw tool results — and once **after** them, so a later rewrite cannot reintroduce a secret. ```yaml agents: diff --git a/docs/configuration/hooks/index.md b/docs/configuration/hooks/index.md index 3d8f2ce691..81cc82f9b5 100644 --- a/docs/configuration/hooks/index.md +++ b/docs/configuration/hooks/index.md @@ -665,6 +665,8 @@ This is the symmetric counterpart of `tool_input_transform`'s `updated_input`, a Hooks on `tool_response_transform` and `post_tool_use` also receive `tool_documents`, the inline document attachments the tool returned. MCP servers return text resources this way (the payload is in `text`), and those documents are emitted to event subscribers and persisted in the session next to the textual output. Only `tool_response_transform` hooks can rewrite the list, with `updated_tool_documents`; the rewritten attachments are what gets emitted and persisted, and `post_tool_use` hooks receive the already-transformed list. `redact_secrets` scrubs each attachment's name, URI, MIME type, and text, so a secret carried in an MCP inline-text resource never reaches the session file or the event stream. +When the agent-level `redact_secrets` flag is on (the default) and other `tool_response_transform` hooks are configured, the auto-injected redactor runs both **before** and **after** them. The leading pass matters because command hooks receive the whole hook input as JSON on stdin: without it, a hook that archives its input would record the raw tool output, display metadata, and inline document attachments. The trailing pass is the final scrub, so a later rewrite that reintroduces a secret is still caught. Configured hooks therefore observe the already-redacted values, with detected secrets replaced by markers. + Hooks on `tool_response_transform` and `post_tool_use` also receive `tool_result_meta`, the structured display metadata a tool recorded alongside its text output (the TUI renders completed `edit_file` diffs from it). Only `tool_response_transform` hooks can rewrite it, with `updated_tool_result_meta` (independently of `updated_tool_response`); the rewritten metadata is what gets emitted and persisted. `post_tool_use` hooks receive the already-transformed metadata and cannot change it. `redact_secrets` also scrubs this metadata, and clears it when it cannot be serialized safely. ### Composing transformations @@ -681,7 +683,12 @@ Hooks for the following events run **sequentially in configuration order**: Every matching hook on these events participates in the sequence, whether it rewrites, observes, or returns a verdict. Each hook sees the most recent successful rewrite. Hooks that return no rewrite leave the current value -unchanged; the runtime receives the final result of the sequence. +unchanged; the runtime receives the final result of the sequence. The +runtime's auto-injected defaults respect that order: the always-on +`limit_large_tool_results` runs last, and when `redact_secrets` is enabled it +runs both ahead of the configured transforms (so command hooks never receive +raw tool results on stdin) and after them (so a later rewrite is still +scrubbed). `updated_input` patches replace only the top-level keys they supply. Other arguments are preserved; nested objects are replaced, not deep-merged. An empty diff --git a/pkg/hooks/builtins/builtins.go b/pkg/hooks/builtins/builtins.go index a9ab36ad7c..a295f89f81 100644 --- a/pkg/hooks/builtins/builtins.go +++ b/pkg/hooks/builtins/builtins.go @@ -161,8 +161,13 @@ type AutoInjector interface { AutoInject(cfg *hooks.Config) } -// ApplyAgentDefaults appends the stock builtin hook entries implied by -// d to cfg. A nil cfg is treated as empty. Returns nil iff no hook +// ApplyAgentDefaults adds the stock builtin hook entries implied by d to +// cfg, appending them after any user-configured hooks. There is one +// deliberate exception: when d.RedactSecrets is set and cfg already +// carries configured tool_response_transform hooks, a named redaction +// pass is inserted ahead of them so command hooks cannot observe raw +// tool output, display metadata, or inline document attachments on +// stdin. A nil cfg is treated as empty. Returns nil iff no hook // (user-configured or auto-injected) is present. // // Snapshot auto-injection is handled separately via [SnapshotController] @@ -201,10 +206,40 @@ func ApplyAgentDefaults(cfg *hooks.Config, d AgentDefaults) *hooks.Config { Hooks: []hooks.Hook{builtinHook(RedactSecrets)}, }) cfg.BeforeLLMCall = append(cfg.BeforeLLMCall, builtinHook(RedactSecrets)) - cfg.ToolResponseTransform = append(cfg.ToolResponseTransform, hooks.MatcherConfig{ + + // tool_response_transform carries the tool's textual output, its + // display metadata, and (since attachments became part of the hook + // protocol) the inline document attachments MCP servers return as + // text resources. Configured transforms must not see those fields + // unredacted: command hooks receive the whole hook input as JSON on + // stdin, so a hook that archives its input would record credentials + // that redact_secrets is supposed to keep out of downstream + // consumers. Run the redactor ahead of the configured transforms, + // and keep the trailing entry as the final pass so a later rewrite + // that reintroduces a secret is scrubbed before emission, + // persistence, and the next LLM call. + // + // The preamble is only injected when there are configured + // transforms to protect; with none there is no hook to leak to and + // a single pass keeps the per-tool-result cost unchanged. It also + // carries its own Name: the executor deduplicates identical hooks, + // and without the name it would collapse into the trailing pass. + responseRedactor := hooks.MatcherConfig{ Matcher: "*", Hooks: []hooks.Hook{builtinHook(RedactSecrets)}, - }) + } + if len(cfg.ToolResponseTransform) > 0 { + preamble := hooks.MatcherConfig{ + Matcher: "*", + Hooks: []hooks.Hook{{ + Name: "redact_secrets (before configured hooks)", + Type: hooks.HookTypeBuiltin, + Command: RedactSecrets, + }}, + } + cfg.ToolResponseTransform = append([]hooks.MatcherConfig{preamble}, cfg.ToolResponseTransform...) + } + cfg.ToolResponseTransform = append(cfg.ToolResponseTransform, responseRedactor) } // Redact before the limiter writes oversized responses to disk. cfg.ToolResponseTransform = append(cfg.ToolResponseTransform, hooks.MatcherConfig{ diff --git a/pkg/hooks/builtins/builtins_test.go b/pkg/hooks/builtins/builtins_test.go index c921d6418b..ff85c99072 100644 --- a/pkg/hooks/builtins/builtins_test.go +++ b/pkg/hooks/builtins/builtins_test.go @@ -845,25 +845,65 @@ func TestApplyAgentDefaultsAppendsToUserHooks(t *testing.T) { assert.Equal(t, builtins.AddDate, got.TurnStart[1].Command) } -func TestApplyAgentDefaultsOrdersTransformsBeforeLimiter(t *testing.T) { +// TestApplyAgentDefaultsOrdersTransformsAroundRedaction pins the +// tool_response_transform ordering: the always-on large-result limiter runs +// last, and when redaction is enabled the auto-injected redaction pass +// brackets the configured transforms — a preamble so command hooks cannot +// observe raw tool results (the hook input is piped to their stdin as JSON) +// and a trailing pass so a rewrite that reintroduces a secret is still +// scrubbed. The two redaction entries are the same builtin, so the preamble +// must stay distinguishable (by Name) from the trailing pass: the executor +// deduplicates identical hooks and would otherwise drop the final pass. +func TestApplyAgentDefaultsOrdersTransformsAroundRedaction(t *testing.T) { t.Parallel() - for _, redact := range []bool{false, true} { - cfg := builtins.ApplyAgentDefaults(&hooks.Config{ - ToolResponseTransform: []hooks.MatcherConfig{{Hooks: []hooks.Hook{{Type: hooks.HookTypeBuiltin, Command: "custom"}}}}, - }, builtins.AgentDefaults{RedactSecrets: redact}) - var names []string - for _, matcher := range cfg.ToolResponseTransform { - for _, hook := range matcher.Hooks { - names = append(names, hook.Command) + for _, tc := range []struct { + name string + redact bool + configured bool + want []string + }{ + { + name: "no redaction", + configured: true, + want: []string{"custom", builtins.LimitLargeToolResults}, + }, + { + name: "redaction brackets configured transforms", + redact: true, + configured: true, + want: []string{builtins.RedactSecrets, "custom", builtins.RedactSecrets, builtins.LimitLargeToolResults}, + }, + { + name: "redaction without configured transforms needs one pass", + redact: true, + want: []string{builtins.RedactSecrets, builtins.LimitLargeToolResults}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + cfg := &hooks.Config{} + if tc.configured { + cfg.ToolResponseTransform = []hooks.MatcherConfig{{Hooks: []hooks.Hook{{Type: hooks.HookTypeBuiltin, Command: "custom"}}}} } - } - want := []string{"custom"} - if redact { - want = append(want, builtins.RedactSecrets) - } - want = append(want, builtins.LimitLargeToolResults) - assert.Equal(t, want, names) + cfg = builtins.ApplyAgentDefaults(cfg, builtins.AgentDefaults{RedactSecrets: tc.redact}) + + var names []string + for _, matcher := range cfg.ToolResponseTransform { + for _, hook := range matcher.Hooks { + names = append(names, hook.Command) + } + } + assert.Equal(t, tc.want, names) + + if tc.redact && tc.configured { + assert.NotEmpty(t, cfg.ToolResponseTransform[0].Hooks[0].Name, + "the pre-hook redaction pass needs a distinct identity to survive hook dedup") + assert.Empty(t, cfg.ToolResponseTransform[2].Hooks[0].Name, + "the trailing redaction pass must stay identical to the historical auto-injection") + } + }) } } diff --git a/pkg/hooks/builtins/capture_stdin_other_test.go b/pkg/hooks/builtins/capture_stdin_other_test.go new file mode 100644 index 0000000000..63a8eba315 --- /dev/null +++ b/pkg/hooks/builtins/capture_stdin_other_test.go @@ -0,0 +1,14 @@ +//go:build !windows + +package builtins + +import "testing" + +// captureStdinCommand returns a POSIX shell command that writes the hook's +// JSON stdin to path verbatim, produces no stdout, and exits 0. Mirrored for +// PowerShell in capture_stdin_windows_test.go. t.TempDir() paths only contain +// letters, digits and path separators, so single quoting needs no escaping. +func captureStdinCommand(t *testing.T, path string) string { + t.Helper() + return "cat > '" + path + "'" +} diff --git a/pkg/hooks/builtins/capture_stdin_windows_test.go b/pkg/hooks/builtins/capture_stdin_windows_test.go new file mode 100644 index 0000000000..06c50aa002 --- /dev/null +++ b/pkg/hooks/builtins/capture_stdin_windows_test.go @@ -0,0 +1,14 @@ +//go:build windows + +package builtins + +import "testing" + +// captureStdinCommand returns a PowerShell command that writes the hook's +// JSON stdin to path verbatim, produces no stdout, and exits 0. Mirrors the +// POSIX helper in capture_stdin_other_test.go. t.TempDir() paths only contain +// letters, digits and path separators, so the literal path needs no escaping. +func captureStdinCommand(t *testing.T, path string) string { + t.Helper() + return "[Console]::In.ReadToEnd() | Set-Content -NoNewline -LiteralPath '" + path + "'" +} diff --git a/pkg/hooks/builtins/redact_secrets_hook_boundary_test.go b/pkg/hooks/builtins/redact_secrets_hook_boundary_test.go new file mode 100644 index 0000000000..2a801b13e6 --- /dev/null +++ b/pkg/hooks/builtins/redact_secrets_hook_boundary_test.go @@ -0,0 +1,78 @@ +package builtins + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/docker/portcullis" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/hooks" + "github.com/docker/docker-agent/pkg/tools" +) + +// TestConfiguredCommandHookReceivesRedactedToolDocuments pins the hook +// boundary: with the agent-level redact_secrets flag on (the default), an +// auto-injected redaction pass runs ahead of user-configured +// tool_response_transform hooks. Command hooks receive the whole hook input +// as JSON on stdin, so without that preamble a hook that archives its input +// would record the raw inline document attachments (and raw tool output) +// that MCP servers return as text resources. +// +// The assertion is on the captured stdin, not on in-process hook input: +// that is exactly the channel the review flagged (pkg/hooks/handler.go +// pipes the serialized Input to the hook process). +func TestConfiguredCommandHookReceivesRedactedToolDocuments(t *testing.T) { + t.Parallel() + + secret := fakeGitHubPAT() + capture := filepath.Join(t.TempDir(), "hook-stdin.json") + cfg := ApplyAgentDefaults(&hooks.Config{ + ToolResponseTransform: []hooks.MatcherConfig{{ + Matcher: "*", + Hooks: []hooks.Hook{{ + Type: hooks.HookTypeCommand, + Command: captureStdinCommand(t, capture), + }}, + }}, + }, AgentDefaults{RedactSecrets: true}) + + registry := hooks.NewRegistry() + require.NoError(t, Register(registry)) + exec := hooks.NewExecutorWithRegistry(cfg, t.TempDir(), nil, registry) + + result, err := exec.Dispatch(t.Context(), hooks.EventToolResponseTransform, &hooks.Input{ + ToolName: "mcp_fetch", + ToolCategory: "mcp", + ToolResponse: "fetched token=" + secret, + ToolDocuments: []tools.DocumentContent{ + {Name: "notes.md", URI: "mcp://docs/notes.md", MimeType: "text/markdown", Text: "token=" + secret}, + {Name: "clean.md", MimeType: "text/markdown", Text: "nothing to see"}, + }, + }) + require.NoError(t, err) + require.NotNil(t, result) + + raw, err := os.ReadFile(capture) + require.NoError(t, err, "the configured command hook must have run and captured its stdin") + + stdin := string(raw) + assert.NotContains(t, stdin, secret, "the configured command hook's stdin must not carry the raw secret") + assert.Contains(t, stdin, portcullis.Marker, "the hook must see the redacted form instead") + + var captured hooks.Input + require.NoError(t, json.Unmarshal(raw, &captured), "the captured stdin must be the hook input protocol") + require.Len(t, captured.ToolDocuments, 2) + assert.NotContains(t, captured.ToolDocuments[0].Text, secret) + assert.Contains(t, captured.ToolDocuments[0].Text, portcullis.Marker) + assert.Equal(t, "nothing to see", captured.ToolDocuments[1].Text, "clean attachments must survive byte-for-byte") + + // The trailing pass still runs after the configured hooks: the rewrite + // the runtime consumes is the redacted list. + require.Len(t, result.UpdatedToolDocuments, 2) + assert.NotContains(t, result.UpdatedToolDocuments[0].Text, secret) + assert.Equal(t, "nothing to see", result.UpdatedToolDocuments[1].Text) +} diff --git a/pkg/hooks/tool_documents_json_test.go b/pkg/hooks/tool_documents_json_test.go new file mode 100644 index 0000000000..f425ed22ee --- /dev/null +++ b/pkg/hooks/tool_documents_json_test.go @@ -0,0 +1,62 @@ +package hooks + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/tools" +) + +// TestToolDocumentsJSONRoundTripDistinguishesNilFromEmpty pins the wire +// contract of updated_tool_documents: nil means "leave the attachments +// unchanged" and is omitted from JSON, while an empty non-nil list means +// "remove every attachment" and must survive both marshaling (a Go hook +// writing its output) and parsing (a command hook reading its input back). +func TestToolDocumentsJSONRoundTripDistinguishesNilFromEmpty(t *testing.T) { + t.Parallel() + + // nil: the field is omitted entirely, so the runtime keeps the current + // attachment list. + encoded, err := json.Marshal(&Output{HookSpecificOutput: &HookSpecificOutput{}}) + require.NoError(t, err) + assert.NotContains(t, string(encoded), "updated_tool_documents") + + // Empty but non-nil: a literal empty array on the wire, not an omitted + // field. omitempty would have dropped it here and turned the explicit + // "remove all attachments" rewrite into a no-op. + encoded, err = json.Marshal(&Output{HookSpecificOutput: &HookSpecificOutput{ + UpdatedToolDocuments: []tools.DocumentContent{}, + }}) + require.NoError(t, err) + assert.JSONEq(t, `{"hook_specific_output":{"updated_tool_documents":[]}}`, string(encoded)) + + // Round-trip: an omitted field decodes to nil (no rewrite)... + var omitted Output + require.NoError(t, json.Unmarshal([]byte(`{"hook_specific_output":{}}`), &omitted)) + require.NotNil(t, omitted.HookSpecificOutput) + assert.Nil(t, omitted.HookSpecificOutput.UpdatedToolDocuments) + + // ...while a literal [] decodes to a non-nil empty slice. + cleared, err := parseStdoutJSON(`{"hook_specific_output":{"updated_tool_documents":[]}}`, false) + require.NoError(t, err) + require.NotNil(t, cleared) + require.NotNil(t, cleared.HookSpecificOutput) + assert.NotNil(t, cleared.HookSpecificOutput.UpdatedToolDocuments) + assert.Empty(t, cleared.HookSpecificOutput.UpdatedToolDocuments) + + // The empty list participates in the sequential pipeline as a rewrite: + // the rewritten input drops the attachments and aggregate keeps the + // empty slice instead of falling back to "no rewrite". + input := Input{ToolDocuments: []tools.DocumentContent{{Name: "notes.md", Text: "hello"}}} + rewritten, changed := rewrittenInput(input, EventToolResponseTransform, cleared.HookSpecificOutput) + assert.True(t, changed) + assert.NotNil(t, rewritten.ToolDocuments) + assert.Empty(t, rewritten.ToolDocuments) + + result := aggregate([]hookResult{{HandlerResult: HandlerResult{Output: cleared}}}, EventToolResponseTransform) + assert.NotNil(t, result.UpdatedToolDocuments, "an explicit clear must not be conflated with nil") + assert.Empty(t, result.UpdatedToolDocuments) +} diff --git a/pkg/hooks/types.go b/pkg/hooks/types.go index c593d44f9c..85a8ea7514 100644 --- a/pkg/hooks/types.go +++ b/pkg/hooks/types.go @@ -704,7 +704,14 @@ type HookSpecificOutput struct { // // Hooks run in config order; each sees the preceding rewrite. The last // non-nil rewrite is returned. - UpdatedToolDocuments []tools.DocumentContent `json:"updated_tool_documents,omitempty"` + // + // Tagged omitzero rather than omitempty: an empty but non-nil slice is + // the explicit "remove every attachment" rewrite, so it must keep its + // wire form (`[]`) when a Go hook marshals its output instead of being + // dropped as an empty omitempty value and silently turning the rewrite + // into a no-op. A literal `[]` on a command hook's stdout already + // decodes to a non-nil empty slice. + UpdatedToolDocuments []tools.DocumentContent `json:"updated_tool_documents,omitzero"` // Transition is a control hook's route request. Only // [EventBeforeAgentRun] and [EventAfterAgentComplete] accept it; any