Skip to content

fix(checks): fail closed on a redact error and carry the session caller on replies - #10

Merged
luanlorenzo merged 15 commits into
mainfrom
luan/eng-965
Nov 10, 2026
Merged

luanlorenzo merged 15 commits into
mainfrom
luan/eng-965

Conversation

@luanlorenzo

@luanlorenzo luanlorenzo commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

The redactor fails closed and masks every result string, and replies the gateway sends on its own carry the session's caller.

  • checks/redact.go: masks content[].text, content[].resource.text, contents[].text and every string value of structuredContent in tools/call, resources/read and tasks/result results. structuredContent is scanned once; keys, numbers and unmasked strings stay byte for byte. Nesting past 128 levels, or a canceled request, denies the result.
  • Only the exact keys content, contents, structuredContent, text and resource are read. Object keys, other spellings and a duplicate of one of those keys are not masked. README and the hook godoc say so.
  • A Redact hook error denies the result: the client gets -32010 "result withheld: redaction failed" and the session lives. The mcp.tool_denied event (rule redact) has the same fixed reason. The hook's own error can quote the text, so it never enters a reply, an event or a log line.
  • mcp.redacted stays one event per message; redactions sums every field. field names the masked fields, comma-joined when there are several.
  • Replies to server requests (S2C gate deny, queue-drop error) used context.Background(). They now carry the values of the session's latest POST, so a TokenSource resolves the same caller. The S2C pipeline gets the same context.
  • No SSE change (the refusal is reverted). Docs now state the existing behaviour: an sse stream opens once per session with the opener's credential; a rotated token reaches message POSTs, not that stream.
  • Behaviour change for hoop's agent MCP gateway: a Redact hook error used to forward the result unmasked; now it denies.
  • Known cost: the hook runs once per string. A structuredContent table of 1,000 rows by 10 columns makes 10,000 calls, and hoop's agent hook makes one DLP network call per string.
  • Exported API: adds mcp.MethodTasksResult. Nothing else changes.

Part of ENG-965
Part of ENG-961

Testing

Result: PII in structured results, embedded resources and task results is now masked, a failing masker blocks the result instead of leaking it, and the gateway's own replies to a server carry the caller's latest token.

Tested on dbdf63ab3 (QA round 2 at d5d7e0ddb; later commits are docs only) against v0.1.7, through a test host that embeds the gateway with a regex Redact hook. Test data only. 94811bb (Qodo review) withholds a result with an ambiguous key or a hook canceled mid-call; unit tests only. 861b327 and 826f2e6 report a message refused before the pipeline (invalid params, folded field, unknown tool) to the observer as a deny with no tool: TestAMessageRefusedBeforeThePipelineIsObserved, which fails without it. 7d089fd (hoop QA) withholds a result, or a read field, of an unexpected type: TestRedactDeniesAFieldOfAnUnexpectedType, whose 9 deny cases fail without it.

  • PII in results: on v0.1.7 the email and SSN reach the client in structuredContent, resource.text and tasks/result; on the branch they are masked, and keys, a 20-digit id, 42, true and null are unchanged. resources/read was already masked.
  • Hook failure: v0.1.7 forwards the text unmasked; the branch answers -32010, the next call on the session works, and the audit reason holds no text.
  • Replies to server requests: on v0.1.7 none reached the upstream; on the branch the sampling/createMessage denial and the 6 dropped-ping replies carry the latest POST's token.

What it solves: teams that put an MCP server behind hoop with masking on get no PII through structured or task results and no leak on a masker outage. Users get it when hoop bumps to this release.

  • Hook error on each field denies; the hook's error quotes the text and enters neither reply nor event: TestRedactHookErrorDeniesResult; through the gateway, session survives: TestRedactHookErrorWithholdsResult
  • One test per field: TestRedactStructuredContentEveryString (exact bytes out), TestRedactNestedResourceText, TestRedactResourcesRead, TestRedactTasksResult; through the gateway: TestRedactMasksTasksResult
  • Depth 129 and 9000 denied before any hook call, depth 128 masked: TestRedactStructuredContentDepthCap; cancel: TestRedactStopsOnCancel. QA's 9000-deep probe: 0.69 s before, 0.3 ms now.
  • Count per message: TestRedactCountsPerMessage
  • Replies carry the caller: TestServerRequestReplyCarriesSessionCaller (real passthrough source, upstream sees the token), TestDroppedServerRequestReplyCarriesSessionCaller
  • SSE stream keeps the opener's credential, POSTs carry each request's: TestSSEStreamUsesSessionOpenerCredential
  • Each new test fails on v0.1.7, except TestSSEStreamUsesSessionOpenerCredential, which pins existing behaviour.
go vet ./...
go test -race ./...
go test -race -count=3 ./gateway/ ./backend/ ./checks/

@luanlorenzo
luanlorenzo marked this pull request as ready for review November 6, 2026 14:03
@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fail closed on redaction errors and preserve caller context on replies

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Mask structured, embedded-resource, and task-result strings; withhold results when redaction
 fails.
• Carry the session’s latest caller context on gateway-generated server replies.
• Document redaction limits and SSE credential behavior, with regression tests for both fixes.
Diagram

graph TD
  A["Backend result"] --> B["S2C pipeline"] --> C["Redact walker"] --> D["Redact hook"] --> E{"Mask succeeded?"}
  E -->|yes| F["Masked reply"] --> G["Client"]
  E -->|no| H["Policy denial"] --> G
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Add an optional batch redaction hook
  • ➕ Could reduce DLP network calls for large structured results.
  • ➖ Expands the hook API and complicates per-string counts and failure handling.

Recommendation: Keep the existing per-string hook for this compatibility-focused security fix. Consider an optional batch interface separately if measured DLP costs justify it.

Files changed (17) +915 / -69

Enhancement (1) +1 / -0
mcp.goName the tasks/result method +1/-0

Name the tasks/result method

• Exports MethodTasksResult for method correlation and redaction eligibility.

mcp/mcp.go

Bug fix (4) +268 / -53
redact.goExpand result masking and withhold results on failure +241/-49

Expand result masking and withhold results on failure

• Masks selected text leaves and structuredContent strings in tools/call, resources/read, and tasks/result responses. Preserves untouched structured values, aggregates redaction audit counts, and denies the whole result with a fixed reason on hook errors, excessive nesting, or cancellation.

checks/redact.go

conn.goRetain the latest session caller for S2C handling +25/-4

Retain the latest session caller for S2C handling

• Stores request context values without request cancellation. Uses them for server-to-client inspection, gate-denial replies, and queue-drop replies instead of background contexts.

gateway/conn.go

gateway.goCapture the session opener’s caller context +1/-0

Capture the session opener’s caller context

• Initializes the session’s retained caller context when the session starts.

gateway/gateway.go

http.goRefresh the session caller on subsequent POSTs +1/-0

Refresh the session caller on subsequent POSTs

• Records the context of each validated session POST so later gateway-generated replies use its caller values.

gateway/http.go

Tests (5) +599 / -11
redact_test.goCover expanded masking and fail-closed decisions +229/-11

Cover expanded masking and fail-closed decisions

• Tests task results, nested resources, structured JSON preservation, depth and cancellation limits, and per-message audit totals. Verifies hook errors deny results without exposing sensitive text in replies or events.

checks/redact_test.go

caller_test.goTest caller credentials on gateway-generated replies +154/-0

Test caller credentials on gateway-generated replies

• Exercises a gated server request against a passthrough-token upstream and a dropped request against a fake backend. Verifies replies carry the session’s caller credential.

gateway/caller_test.go

gateway_test.goSupport custom headers in gateway test requests +4/-0

Support custom headers in gateway test requests

• Extends the test client to attach request headers, enabling credential-rotation regression tests.

gateway/gateway_test.go

redact_test.goTest gateway-level redaction denials and task results +93/-0

Test gateway-level redaction denials and task results

• Verifies a failing hook returns a policy error without ending the session. Also checks that correlated tasks/result responses are masked.

gateway/redact_test.go

sse_caller_test.goLock in existing SSE credential behavior +119/-0

Lock in existing SSE credential behavior

• Tests that the stream opens once with the session opener’s credential while a later POST uses a rotated credential.

gateway/sse_caller_test.go

Documentation (7) +47 / -5
README.mdDocument embedding-facing redaction and credential behavior +22/-0

Document embedding-facing redaction and credential behavior

• Describes masked fields, exact-key and duplicate-key limits, per-string hook cost, and fail-closed errors. Clarifies caller context on gateway replies and the existing SSE stream credential behavior.

README.md

audit.goClarify redaction event count semantics +1/-1

Clarify redaction event count semantics

• Documents that one redaction event is emitted per masked message and its redactions field sums hook counts.

audit/audit.go

sse.goClarify when SSE requests resolve credentials +3/-1

Clarify when SSE requests resolve credentials

• Documents that the stream GET uses Start’s context once, while each message POST uses its Send context. SSE transport behavior is unchanged.

backend/sse.go

auth.mdDocument SSE credential lifetime +4/-0

Document SSE credential lifetime

• Clarifies that the session opener’s credential stays on the SSE stream while later message POSTs can use rotated credentials.

docs/architectural/auth.md

embedding.mdDocument hook failures and embedded caller context +11/-1

Document hook failures and embedded caller context

• Explains per-string redaction calls and result denial on errors. Describes the context used for gateway-generated replies and SSE requests.

docs/architectural/embedding.md

inspection-pipeline.mdUpdate the redaction pipeline contract +1/-1

Update the redaction pipeline contract

• Lists the additional result fields and methods covered by redaction, the depth limit, and fail-closed behavior.

docs/architectural/inspection-pipeline.md

hooks.goSpecify the Redact hook’s result contract +5/-1

Specify the Redact hook’s result contract

• Documents the covered strings and methods, exact-key behavior, per-string invocation, and result denial on error.

inspect/hooks.go

@qodo-code-review

qodo-code-review Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Resource text can reach clients unmasked ✓ Resolved

Resolving commit: 94811bb

Resolution reason
Nested resource objects are now validated with ExactKeys against the keys the walker reads ("text"),
and any case-variant or repeated key in the resource object (and in content items) makes the walker
return errRedactKeys, withholding the result rather than forwarding unmasked text.
Description
item looks up nested resource text using only the exact "text" key, so it forwards a "Text"
value without calling the redaction hook. A Go client decoding that response into a struct tagged
json:"text" can interpret the forwarded value as resource text, including any sensitive content it
contains.


Remediation recommended

2. Null values pass despite withholding promise ✓ Resolved

Resolving commit: 8048505

Resolution reason
The README was updated to document the intended behavior: a null in any of the
result/content/text/resource positions carries no text and passes, so the documented rule now
matches the null-handling test. This is the clarification the suggested fix prompt asks for.
Description
The README says a non-object result or a field of an unexpected type is withheld, but
Redactor.Inspect allows JSON null in those positions. The new test explicitly expects
result:null, null arrays, null content entries, and null text to pass, so readers cannot rely on
the documented withholding rule for those cases.

3. Client-chosen tool names reach observer metrics ✓ Resolved

Resolving commit: 826f2e6

Resolution reason
observeRefused no longer calls inspect.RawTool on the client params; it now always passes an empty
tool label ("") for refused messages, so client-supplied tool names can no longer become observer
label values. The test was updated to expect the empty-tool label for both refusals.
Description
observeRefused passes inspect.RawTool(env.Params) straight to Observer.ObserveMessage as the
tool label, and RawTool returns the name field without checking it against any catalog. The
routing-failure branch in handleC2S now calls it for a tools/call naming a tool that does not
exist, so any string the client sends becomes an observer label. Before this PR such messages never
reached the observer, so a client can create an unbounded number of distinct tool label values on
any metrics or log backend the host builds from the observer.

4. Canceled redaction can still pass a result ✓ Resolved

Resolving commit: 94811bb

Resolution reason
Added a context check directly after the hook call in walker.str: if w.ctx.Err() != nil after
w.redact returns, it returns errRedactCanceled before the n <= 0 check, so a zero-count return on
cancellation now denies the result. Also added errRedactCanceled to the deny cause list and a test
(TestRedactDeniesWhenCanceledDuringTheLastHookCall) that cancels inside the final hook call and
expects Deny. This matches the suggested fix's core remedy, though it does not re-check in the
Inspect path or at the walker.item site separately.
Description
str checks cancellation before invoking the hook but does not check it again after the hook
returns. If the context is canceled during the final hook call and that call returns no redactions,
Inspect can allow the original result rather than withhold it.


Informational

5. Large structured results can time out and be withheld ✓ Resolved

Resolving commit: 94811bb

Resolution reason
The README now states that the hook runs once per string, in turn, that the calls share the
request's RequestTimeout with the backend call, and that a result still unmasked when it expires is
withheld. The hook godoc (inspect/hooks.go), docs/architectural/embedding.md and
inspection-pipeline.md were updated to say a canceled request and timeouts deny the result. This
addresses the suggested documentation fix (the finding's "at minimum" option) though it does not
batch or parallelize the hook calls.
Description
walker.str checks w.ctx.Err() before each hook call, and w.ctx is the POST context that
handlePost wraps in RequestTimeout (5m by default). That same budget also covers the backend
round trip. When a structuredContent result has thousands of strings and the hook makes a network
DLP call per string (the PR's 1,000×10 example means 10,000 calls), the deadline expires partway
through and a valid result is denied as "redaction canceled". The result never reaches the client.

Grey Divider

Context sources
Review mode: Auto: ⏭️ Skipped: Focused change is README.md prose only; documentation, no code.
✅ Fix-loop round: fix loop

Grey Divider

Tip of the day
💡 Did you know, you can move or hide resolved findings to focus on what still needs action

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 8048505

Results up to commit dbdf63a 🧠 Deep


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required
1. Resource text can reach clients unmasked ✓ Resolved

Resolving commit: 94811bb

Resolution reason
Nested resource objects are now validated with ExactKeys against the keys the walker reads ("text"),
and any case-variant or repeated key in the resource object (and in content items) makes the walker
return errRedactKeys, withholding the result rather than forwarding unmasked text.
Description
item looks up nested resource text using only the exact "text" key, so it forwards a "Text"
value without calling the redaction hook. A Go client decoding that response into a struct tagged
json:"text" can interpret the forwarded value as resource text, including any sensitive content it
contains.


Remediation recommended
2. Canceled redaction can still pass a result ✓ Resolved

Resolving commit: 94811bb

Resolution reason
Added a context check directly after the hook call in walker.str: if w.ctx.Err() != nil after
w.redact returns, it returns errRedactCanceled before the n <= 0 check, so a zero-count return on
cancellation now denies the result. Also added errRedactCanceled to the deny cause list and a test
(TestRedactDeniesWhenCanceledDuringTheLastHookCall) that cancels inside the final hook call and
expects Deny. This matches the suggested fix's core remedy, though it does not re-check in the
Inspect path or at the walker.item site separately.
Description
str checks cancellation before invoking the hook but does not check it again after the hook
returns. If the context is canceled during the final hook call and that call returns no redactions,
Inspect can allow the original result rather than withhold it.


Informational
3. Large structured results can time out and be withheld ✓ Resolved

Resolving commit: 94811bb

Resolution reason
The README now states that the hook runs once per string, in turn, that the calls share the
request's RequestTimeout with the backend call, and that a result still unmasked when it expires is
withheld. The hook godoc (inspect/hooks.go), docs/architectural/embedding.md and
inspection-pipeline.md were updated to say a canceled request and timeouts deny the result. This
addresses the suggested documentation fix (the finding's "at minimum" option) though it does not
batch or parallelize the hook calls.
Description
walker.str checks w.ctx.Err() before each hook call, and w.ctx is the POST context that
handlePost wraps in RequestTimeout (5m by default). That same budget also covers the backend
round trip. When a structuredContent result has thousands of strings and the hook makes a network
DLP call per string (the PR's 1,000×10 example means 10,000 calls), the deadline expires partway
through and a valid result is denied as "redaction canceled". The result never reaches the client.

Results up to commit 861b327 🚀 Fast


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Client-chosen tool names reach observer metrics ✓ Resolved

Resolving commit: 826f2e6

Resolution reason
observeRefused no longer calls inspect.RawTool on the client params; it now always passes an empty
tool label ("") for refused messages, so client-supplied tool names can no longer become observer
label values. The test was updated to expect the empty-tool label for both refusals.
Description
observeRefused passes inspect.RawTool(env.Params) straight to Observer.ObserveMessage as the
tool label, and RawTool returns the name field without checking it against any catalog. The
routing-failure branch in handleC2S now calls it for a tools/call naming a tool that does not
exist, so any string the client sends becomes an observer label. Before this PR such messages never
reached the observer, so a client can create an unbounded number of distinct tool label values on
any metrics or log backend the host builds from the observer.

Results up to commit 7d089fd ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Null values pass despite withholding promise ✓ Resolved

Resolving commit: 8048505

Resolution reason
The README was updated to document the intended behavior: a null in any of the
result/content/text/resource positions carries no text and passes, so the documented rule now
matches the null-handling test. This is the clarification the suggested fix prompt asks for.
Description
The README says a non-object result or a field of an unexpected type is withheld, but
Redactor.Inspect allows JSON null in those positions. The new test explicitly expects
result:null, null arrays, null content entries, and null text to pass, so readers cannot rely on
the documented withholding rule for those cases.

Grey Divider

Qodo Logo

Comment thread checks/redact.go Resolved
Comment thread checks/redact.go Resolved
Comment thread checks/redact.go Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 94811bb

Comment thread gateway/http.go Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 861b327

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 826f2e6

Comment thread README.md Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 7d089fd

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8048505

@luanlorenzo
luanlorenzo merged commit 5566d29 into main Nov 10, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant