Skip to content

fix(redact_secrets): scrub tool attachment documents - #5017

Open
PerryLink wants to merge 2 commits into
docker:mainfrom
PerryLink:fix/redact-tool-documents
Open

PerryLink wants to merge 2 commits into
docker:mainfrom
PerryLink:fix/redact-tool-documents

Conversation

@PerryLink

Copy link
Copy Markdown
Contributor

DRAFT PR BODY — #5011 (do not post without root sign-off)

Title: fix(redact_secrets): scrub attachment documents in tool_response_transform


Fixes #5011

Problem

redact_secrets scrubs tool output on the tool_response_transform leg, but the
hook input only carries the tool's textual output (tool_response) and
tool_result_meta. Tool attachments are not part of it.

MCP servers return inline text resources as tools.DocumentContent{Text: ...}
(for example text/markdown). Those documents are emitted to event subscribers and
persisted in the session by recordToolResponse (chat.BuildToolResultMultiContent),
so the secret survives in the session file and in the side consumers (SSE / ACP / TUI).
The next LLM call is re-scrubbed by the before_llm_call leg, which is why this gap
is easy to miss.

Scope decision (from the issue)

#5011 asks for a scope decision: scrub DocumentContent.Text in the transform leg,
or extend the hook protocol to carry attachments. This PR implements the second,
additively:

  • hooks.Input gains tool_documents (the result's tools.DocumentContent list) for
    tool_response_transform and post_tool_use.
  • HookSpecificOutput gains updated_tool_documents: nil means no rewrite, a present
    list (even an empty one) replaces the attachments; the last non-nil rewrite wins in
    the sequential pipeline, matching updated_tool_response / updated_tool_result_meta.
  • The sequential pipeline, aggregate, and strict-output validation understand the new
    field, so existing hooks are unaffected.
  • The dispatcher applies the rewrite before emission and before recordToolResponse, so
    the event stream, the persisted session, the post_tool_use input, and the next model
    call all see the same redacted attachments.

redact_secrets now scrubs each attachment's name, uri, mime_type, and text
with portcullis, mirroring the before_llm_call leg (which already scrubs document
name / MIME type / inline text). Binary data is opaque base64 and is not scanned;
clean documents and binary payloads are preserved byte-for-byte. When nothing matches,
the builtin returns no rewrite, so the runtime's fast path is unchanged.

Tests

New end-to-end regression test TestDispatcherRedactsInlineTextToolDocuments
(pkg/runtime/toolexec): a tool returns an inline-text document carrying a GitHub PAT;
the test asserts the emitted ToolCallResult, the persisted session message, and the
post_tool_use input are all redacted, while a clean text document and a binary PDF
remain unchanged. Unit tests cover text and non-text attachment fields, the clean no-op
path, and sequential pipeline composition; the strict-output capability table gains an
updated_tool_documents row.

Docs

Updated docs/configuration/hooks/index.md (new input/output fields and composition
rules), docs/configuration/agents/index.md and docs/guides/secrets/index.md
(redaction coverage).

Validation

Ran locally on main @ c0062b8a with Go 1.27.4:

  • go build ./..., go vet ./..., gofmt — clean
  • go test ./... -count=1 — pass (266 packages ok)
  • go test ./pkg/hooks/... ./pkg/runtime/toolexec — pass
  • golangci-lint run --allow-parallel-runners (v2.14.0) and go run ./lint . — 0 issues
  • the same probe fails on unpatched c0062b8a and passes after the change (red → green)
  • commits are signed off per the DCO (git commit -S -s)

Notes / risk

  • Additive protocol change: new optional JSON fields, no config/schema change; existing
    hooks ignore them.
  • Cross-process hooks now receive attachment payloads for these two events (the same
    channel that already carries unbounded tool output). Binary data is included because
    a replacement list has to stay complete.
  • Happy to reshape this if maintainers prefer a different boundary (for example, declaring
    attachments explicitly out of scope for redaction).

Local draft produced by the hub recon run task-38; not posted.

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: docker#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 <changed files>                            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 c0062b8       OK (+ targeted tests ok)

Red -> green: regression test / probe fails on pristine c0062b8
(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 c0062b8..24b8327)
@PerryLink
PerryLink requested a review from a team as a code owner November 23, 2026 13:20
@aheritier aheritier added area/docs Documentation changes area/runtime Runtime engine, agent loop execution, tool dispatch, loop detection area/security Authentication, authorization, secrets, vulnerabilities area/tools For features/issues/fixes related to the usage of built-in and MCP tools kind/fix PR fixes a bug (maps to fix:). Use on PRs only. labels Nov 23, 2026
@aheritier

Copy link
Copy Markdown
Collaborator

@dgageot @rumpl any thoughts here ?

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for fixing #5011 and adding a regression test that checks both the emitted result and the stored session. The attachment redaction needs to cover the hook boundary too.

Comment thread pkg/runtime/toolexec/dispatcher.go Resolved
Comment thread pkg/hooks/types.go Resolved
@aheritier

Copy link
Copy Markdown
Collaborator

Moving to draft, please mark as ready when feedback are reviewed and potentially addressed if they make sense to you.

@aheritier
aheritier marked this pull request as draft November 24, 2026 11:46
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: docker#5017

----------------------------------------------------------------------
Validation (on this commit):
  go build ./...                                       EXIT=0
  go vet ./...                                         EXIT=0
  gofmt -l <changed files>                             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 265b5ff 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>

--------
@PerryLink
PerryLink marked this pull request as ready for review November 24, 2026 14:38
@PerryLink

Copy link
Copy Markdown
Contributor Author

Re: hook boundary for attachment redaction + omitzero

Thanks for the careful review. Both points are addressed on fix/redact-tool-documents (commit 649c3e38).

[blocking] Configured tool_response_transform command hooks received raw attachment contents

You are right: the new tool_documents input inherited the existing ordering, where ApplyAgentDefaults appends the auto-injected redact_secrets entry after the agent's configured transforms. Because command hooks receive the whole hook input as JSON on stdin, a hook that archives its input would record the raw MCP inline-text resources (along with the raw tool output and result metadata) — content it never received before this PR, even with redaction enabled.

Fixed by bracketing the configured transforms with the auto-injected redactor when redact_secrets is enabled (the default) and the agent configures tool_response_transform hooks:

  • a named redact_secrets leading pass is inserted ahead of the configured transforms in builtins.ApplyAgentDefaults (pkg/hooks/builtins/builtins.go), so the first thing every configured hook receives — including the JSON on stdin — is already scrubbed (tool_response, tool_result_meta, and tool_documents);
  • the existing appended entry is kept as the final pass, so a later rewrite that reintroduces a secret is still redacted before emission, persistence, post_tool_use, and the next LLM call (addressing "keep the final redaction pass so later rewrites are covered too");
  • the leading entry carries a distinct Name because Executor.hooksFor deduplicates identical hooks by value; without it the trailing entry would be collapsed into the leading one and the final pass would silently disappear;
  • when the agent configures no tool_response_transform hooks, no leading pass is injected — there is no hook to leak to, so the effective config and the per-tool-result cost of the common case are unchanged;
  • limit_large_tool_results still runs last, so it keeps spilling only scrubbed content.

The dispatcher is unchanged: it already hands the documents to the hook input and applies the aggregated rewrite before emission and recordToolResponse; the bug was the injection order, not the data flow.

Test added (the scenario you asked for): TestConfiguredCommandHookReceivesRedactedToolDocuments configures a real command hook that writes its stdin to a file, lets ApplyAgentDefaults inject the auto redactor, dispatches tool_response_transform with a PAT-bearing inline-text document, and asserts the captured stdin contains neither the raw secret nor the raw tool output, but the redaction marker and the unchanged clean attachment. The ordering test TestApplyAgentDefaultsOrdersTransformsAroundRedaction pins the leading/trailing placement and their distinct identity. Both fail on 265b5ffd (the captured stdin shows the raw PAT; the leading pass is absent) and pass with the fix.

[should-fix] omitempty dropped an explicit "remove all attachments"

Fixed: HookSpecificOutput.UpdatedToolDocuments is now tagged omitzero. A non-nil empty slice marshals as "updated_tool_documents":[] instead of being dropped and decoding back as "leave unchanged"; nil/absent still means "unchanged".

Test added: TestToolDocumentsJSONRoundTripDistinguishesNilFromEmpty (pkg/hooks/tool_documents_json_test.go) round-trips nil (field omitted, decodes to nil) vs an empty list (marshals to [], decodes to a non-nil empty slice, and the sequential pipeline/aggregate keep it as an explicit clear). It fails on 265b5ffd where omitempty removes the field from the marshaled output.

Docs

docs/configuration/hooks/index.md and docs/configuration/agents/index.md now document the before/after ordering guarantee for the auto-injected redactor and why it exists (command-hook stdin).

Local verification (Go 1.27.4)

  • go build ./... — OK
  • go vet ./... — OK
  • go test ./pkg/hooks/... ./pkg/runtime/toolexec/... -count=1 — OK
  • go test ./... -count=1 — OK, 266 packages (needs jq on PATH for a pre-existing pkg/runtime fixture)
  • gofmt -l on changed files — clean
  • golangci-lint run --allow-parallel-runners (v2.14.0) — 0 issues
  • go run ./lint . — no offenses (3004 files)
  • go mod tidy --diff — clean
  • red→green: the three new tests fail on pristine 265b5ffd and pass with the fix.

One scope note: the same pre-redaction ordering exists for configured tool_input_transform and before_llm_call hooks. I left those untouched because this PR is what introduced new sensitive input on tool_response_transform; happy to extend the same bracketing to the other legs in a follow-up if you prefer.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/docs Documentation changes area/runtime Runtime engine, agent loop execution, tool dispatch, loop detection area/security Authentication, authorization, secrets, vulnerabilities area/tools For features/issues/fixes related to the usage of built-in and MCP tools kind/fix PR fixes a bug (maps to fix:). Use on PRs only.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

redact_secrets misses secrets carried in tool attachments (MCP inline-text documents)

2 participants