Skip to content

Commit filtered response heads after filtering - #7340

Merged
ChrisJBurns merged 3 commits into
mainfrom
ChrisJBurns/l6ci8
Nov 26, 2026
Merged

ChrisJBurns merged 3 commits into
mainfrom
ChrisJBurns/l6ci8

Conversation

@ChrisJBurns

@ChrisJBurns ChrisJBurns commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Why: Behind the transparent proxy, a filtered POST response (tools/list, prompts/list, resources/list, resources/templates/list, skills/list, find_tool) had its status and headers sent before the authz filter ran. The cause is the proxy's httputil.ReverseProxy, which is built with FlushInterval: -1 and calls the writer's Flush() after copying the body. Flush() then sent the backend's status and headers to the client, and only afterwards did FlushAndFilter decide what to answer. As a result:

  • A fail-closed answer (a result past the decoder's depth cap, a smuggled result, a mislabeled body naming a result) reached the client as HTTP 200, carrying a JSON-RPC error body.
  • A filtered or error body kept the backend's Content-Type (for example text/plain) and entity headers such as ETag, which describe bytes that were never sent.

Write() already buffers the whole body of a filtered method, so sending the headers early streamed nothing to the client. It only locked in headers that the filter later needed to change. This also covers the two Codex findings on #7211, whose code landed through #6949.

What:

  • Flush() is now a no-op for filtered methods, and FlushAndFilter sends the status and headers once, after filtering. Unfiltered methods still send them on flush, as before.
  • Before sending, FlushAndFilter drops the backend's entity headers (Content-Length, ETag, Last-Modified, digests, Content-Encoding) and HTTP trailers for every filtered method, since the body may be rewritten. It then applies Cache-Control: private, no-store.
  • JSON written in place of the backend's body (filtered JSON on a sniffed route, or a fail-closed error) is served as application/json through the new relabelAsJSON().
  • A content-encoded body to a filtered method is replaced with the generic JSON-RPC error at any status. Before, a non-2xx encoded body was forwarded untouched, so a list compressed with a coding Go's transport does not decode (for example x-gzip or br) reached the client unfiltered. A 2xx becomes a 500; a non-2xx keeps its status, so an expired-session 404 still reaches the client.
  • Removed the rejectEncodedResponse-from-Flush workaround and its rejected latch. They only existed because headers were sent early.
  • docs/authz.md now describes when a filtered method's headers are sent, and how mislabeled, undecodable, and lone-CR responses are handled.

Type of change

  • Bug fix

Test plan

  • Unit tests: go test -race on ./pkg/authz/..., ./pkg/transport/proxy/..., ./pkg/llm/..., ./pkg/mcp/....
    • New real-chain tests run ParsingMiddleware → authz.Middleware → httputil.ReverseProxy{FlushInterval: -1} against an httptest backend: TestMiddlewareBehindReverseProxyCommitsFilteredHead, ...FlushesUnfilteredHead, and ...FilteredFraming.
    • They cover mislabeled and labeled fail-closed responses, a mislabeled clean list, SSE lists, an unfiltered method that still flushes early, a BOM-only body, an empty gzip body, and announced and unannounced trailers.
    • With the old Flush() restored, the fail-closed cases get 200 and text/plain and keep the backend's ETag. The BOM and trailer cases fail with the fixes removed.
  • Linting: golangci-lint on ./pkg/authz/... reports 0 issues. The full local task lint-fix crashes inside the linter on an unrelated package (util) because of a local toolchain mismatch, so CI lint is the full check.

Does this introduce a user-facing change?

Yes, for a filtered method's POST response behind the transparent proxy or the LLM proxy:

Fail-closed answers that replace the whole body

  • Before: HTTP 200 with the backend's Content-Type, ETag and other entity headers.
  • After: HTTP 500 with application/json and no backend entity headers.

A mislabeled body that the filter rewrites (for example text/plain carrying a list)

  • Before: kept the backend's media type and ETag.
  • After: application/json with no backend entity headers.

When headers are sent

  • Before: as soon as the proxy flushed.
  • After: once the whole response has been filtered. The body was already held until then, so the client receives data no later than before, but a client with a strict wait-for-headers timeout now waits for the full response.

Backend entity headers and HTTP trailers

  • Before: Content-Length, ETag, Last-Modified, digests and trailers were forwarded on a filtered method's response, describing the unfiltered body.
  • After: none of them are forwarded on a filtered method's response, including a correctly labeled filtered 200 and a pass-through body. Content-Type is kept.

Content-encoded non-2xx body

  • Before: forwarded with its status, body and Content-Encoding intact, unfiltered.
  • After: the status is kept and the body is replaced with a generic JSON-RPC error carrying the request id, as application/json.

Empty 2xx body with a Content-Encoding

  • Before: behind the proxy, it could become a 500, depending on whether the proxy's flush timer fired first.
  • After: passes through empty and without Content-Encoding, as it already did without the proxy apart from the header. An empty body holds no list.

Unfiltered methods are unchanged.

Special notes for reviewers

  • This is a deliberate deviation from the unfiltered path, which still sends headers on flush. The GET event-stream writer (sse_stream_filter.go) has its own Flush and still streams each event.
  • ResponseController.Flush stops at our Flush method. The writer has no Unwrap, so a no-op Flush cannot be bypassed to send headers on the underlying writer.
  • dropBackendTrailers deletes every header that the backend's Trailer header names. A backend announcing Trailer: Content-Type loses its label, and its body goes down the sniff path, which still filters or fails closed. The cache policy is applied after the trailer drop, so a trailer cannot remove it.
  • An encoded non-2xx keeps the backend's status, while the other fail-closed paths (writeErrorResponse, such as a smuggled result in a non-2xx JSON body) still answer 500 whatever the backend status. I left those as they are.
  • The real-chain encoded tests use x-gzip: behind WithoutAcceptEncoding, Go's transport decodes a body labeled exactly gzip before the filter sees it, so only codings the transport does not decode reach this path.
  • Known gap, out of scope: the GET event-stream writer passes every non-2xx body through unfiltered, encoded or not (decide() in sse_stream_filter.go; pinned by sse_stream_filter_test.go "non-2xx other media type passes through"). The POST path filters non-2xx result bodies, so the two paths disagree. That needs its own change.

🤖 Generated with Claude Code

When a filtered POST response carries an unrecognized media type and
the filter answers with JSON in its place, the backend's Content-Length
and Content-Type were left on the head. The stale length truncated the
shorter replacement, and the media type mislabeled it. Clear the
backend's entity headers and set application/json on those routes, and
document the POST path's handling of mislabeled and undecodable bodies.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@github-actions github-actions Bot added the size/XS Extra small PR: < 100 lines changed label Nov 26, 2026

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The helper is correct and safe. It never writes backend bytes under the relabeled head: every route that relabels ends in either a filtered Response or a generated error. My concern is that the PR's user-facing claim and the new docs bullet do not hold on the path ToolHive actually runs.

Finding: on the transparent proxy the relabel never takes effect.
pkg/transport/proxy/transparent/transparent_proxy.go builds its ReverseProxy with FlushInterval: -1, and pkg/llm/proxy does the same. Those are the only production consumers of this writer, through the middleware factory. I drove the real chain (ParsingMiddleware → authz.Middleware → ReverseProxy{FlushInterval: -1}) against a backend that answers Content-Type: text/plain with a Content-Length and an ETag:

Backend body Client sees
clean list with one denied tool filtered correctly, but 200, Content-Type: text/plain, backend ETag kept
result nested past the depth cap (sniffRejectNamed) 200, text/plain, body is the JSON-RPC internal error
{"result":null} 200, text/plain, body is the JSON-RPC internal error

The output is identical on main and on this branch. Flush() commits the status and headers before FlushAndFilter runs, and the log shows http: superfluous response.WriteHeader from processJSONResponse and writeErrorResponse. The encoded-body route already deals with this: rejectEncodedResponse is called from Flush() because it needs only the headers. The sniffed routes need the body, so they cannot be decided there.

The PR notes the Flush() limitation, but only as a branch limitation. The stale Content-Length truncation is also already prevented there, because Flush() drops it, and I saw no truncated reads. So on the main path this PR changes nothing for clients, and the part that is still wrong (text/plain label, retained ETag, and status 200 rather than 500 for the error cases) is untouched.

What I would change

  1. Make the docs/authz.md bullets and the PR's before/after say where they hold. As written, "gets HTTP 500 … served as application/json" is what a client sees only when the writer is used without a flush. Behind the transparent proxy a client sees 200 and the backend's media type. Your CLAUDE.md asks for observable behavior to be documented in the same PR, and a docs claim that is false on the main path is worse than none.
  2. Either narrow the claim to the non-streaming case, or decide whether the sniffed routes should hold back the header commit. Because the writer buffers the whole body for filtered methods, Flush() could skip the header commit for a filtered POST and let FlushAndFilter commit once. That would make this relabel effective, and it fixes the ETag and the status on those routes. It is a behavior change on the streaming path, so a follow-up PR with its own transparent-proxy test is the right home for it. I am not asking for it in this PR.
  3. Add one test that goes through ReverseProxy{FlushInterval: -1} rather than the bare writer. The current table passes on main for the wrong reason at the proxy level: it asserts the head on a writer that nothing in production reaches unflushed. With such a test, whichever direction you pick is pinned.

Existing users. If it takes effect for a non-flushing wiring, clients that parsed the old backend media type on a sniffed-JSON body now get application/json. That is the intended outcome and I see no compatibility risk. The same-path ETag retention on correctly labeled application/json is already called out as a follow-up in the PR body, and I agree it can wait.

Tests pass locally for ./pkg/authz/..., ./pkg/transport/proxy/... and ./pkg/mcp/....

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.46%. Comparing base (9300f3f) to head (79ae12c).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7340      +/-   ##
==========================================
+ Coverage   82.40%   82.46%   +0.05%     
==========================================
  Files         937      937              
  Lines       95821    95872      +51     
==========================================
+ Hits        78962    79060      +98     
+ Misses      16854    16807      -47     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Behind httputil.ReverseProxy with FlushInterval -1, Flush sent the
status and headers before FlushAndFilter ran, so a fail-closed error
reached the client as a 200 with the backend's Content-Type and ETag,
and relabelAsJSON had no effect. Write already buffers the whole body
of a filtered method, so the early commit streamed nothing.

Flush is now a no-op for filtered methods and FlushAndFilter commits the
head once. It drops the backend's Content-Length and trailers, which
describe bytes that are not sent, and error answers are relabeled as
JSON. The Flush-time encoded-body workaround and its latch are removed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@ChrisJBurns ChrisJBurns changed the title Relabel JSON written for a mislabeled POST body Commit filtered response heads after filtering Nov 26, 2026
@github-actions github-actions Bot removed the size/XS Extra small PR: < 100 lines changed label Nov 26, 2026
@ChrisJBurns

Copy link
Copy Markdown
Collaborator Author

Thanks @rdimitrov, you were right: the first commit changed nothing for clients behind the transparent proxy. I reproduced it: Flush() sent the status and headers before FlushAndFilter ran, so relabelAsJSON() and the fail-closed 500 came too late. I've taken your option 2 in this PR rather than a follow-up, because without it the PR has no effect. The fix is in c9b5c7c.

1. Docs and PR claims matched the real path

  • The docs/authz.md bullets and the PR's before/after now describe what a client sees behind the proxy. The PR body is rewritten.
  • The docs now also say when a filtered method's headers are sent.

2. Headers held back for filtered methods

  • Flush() is now a no-op when requiresResponseFiltering(method) is true, so FlushAndFilter sends the status and headers once, after filtering.
  • Write() already buffered the whole body, so the early send streamed nothing to the client; it only locked in headers we later needed to change.
  • Fail-closed answers that replace the whole body now arrive as 500 with application/json, for both mislabeled and correctly labeled bodies. Mislabeled bodies that we rewrite are relabeled as JSON and lose the backend's ETag and other entity headers.
  • The rejectEncodedResponse-from-Flush workaround and its rejected latch are removed, since they only existed because of the early send.
  • Unfiltered methods still send their headers on flush, and the GET stream writer is untouched.

3. Tests through ReverseProxy{FlushInterval: -1}

  • New tests in response_filter_status_commit_test.go run ParsingMiddleware → authz.Middleware → httputil.ReverseProxy{FlushInterval: -1} against an httptest backend.
  • They cover your three cases, plus a correctly labeled smuggled result, an SSE list, and an unfiltered method that must still send its headers before the backend finishes.
  • With the old Flush() restored they fail the way your table describes: 200, text/plain, and the backend's ETag kept.

Found in a second review pass and fixed here

  • BOM-only body: once Flush() stopped deleting Content-Length, a body that was only a BOM went out with the backend's stale length, and the client hit unexpected EOF. FlushAndFilter now drops Content-Length once for every filtered method.
  • Backend trailers: with the trailer-time flush now a no-op, ReverseProxy copied trailer values into the still-unsent headers. They are dropped now, since they describe bytes we don't send. Cache-Control: private, no-store is applied after the drop.
  • Real-chain test coverage: added cases for both of the above and for an empty gzip body. The content-encoding real-chain test now asserts the 500 and application/json.

Left as follow-ups, both already on main

  • The ETag on a correctly labeled, successfully filtered 200 JSON body.
  • A gzipped non-2xx body that bypasses the filter, because shouldRejectEncoded exempts non-2xx.

@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Nov 26, 2026
A content-encoded non-2xx body to a filtered method skipped the filter:
the status check exempted it, and the encoded bytes then failed every
decode and sniff, so a list a client could decode passed through. Every
encoded body is now replaced with the generic JSON-RPC error. A non-2xx
keeps its status, so an expired-session 404 still reaches the client.

A filtered body was also written with the backend's ETag, Last-Modified,
and digests, which describe the unfiltered bytes. FlushAndFilter now
drops the backend's entity headers once for every filtered method.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@ChrisJBurns

Copy link
Copy Markdown
Collaborator Author

Two more fixes in 79ae12c. Both were problems already on main that I'd first listed as follow-ups; they are now fixed in this PR.

Encoded non-2xx bodies bypassed the filter

  • shouldRejectEncoded only rejected a compressed body when the status was 2xx. An encoded 500 or 404 then failed every decode and sniff check and was forwarded unfiltered.
  • That is exploitable with a coding Go's transport doesn't decode itself, such as x-gzip or br.
  • Now every non-empty encoded body to a filtered method is replaced with the generic JSON-RPC error, served as application/json. A 2xx becomes a 500. A non-2xx keeps its status, so an expired-session 404 still reaches the client.

Filtered bodies kept the backend's ETag, Last-Modified and digests

  • FlushAndFilter now drops the backend's entity headers once for every filtered method, before any path sends the headers.
  • relabelAsJSON() now only sets Content-Type.

Tests

  • The real-chain table now has a backend that sends ETag, Last-Modified and Repr-Digest.
  • Every case checks that those headers and Content-Encoding are gone.
  • Added cases for a correctly labeled filtered 200, an encoded 2xx, an encoded 500 and an encoded 404.
  • Against the previous code, the encoded 500/404 cases leak admin_tool, and the filtered cases keep ETag, Last-Modified and Repr-Digest.

Found while doing this, left out of scope: the GET event-stream writer passes every non-2xx body through unfiltered, encoded or not. A test pins that behaviour on purpose, but it disagrees with the POST path, which filters non-2xx result bodies. It's noted in the PR body and needs its own change.

@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Nov 26, 2026
@ChrisJBurns

Copy link
Copy Markdown
Collaborator Author

/retest

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving. The two follow-up commits fix what I raised, and the PR now does what its description says on the production path.

Re-verified on 79ae12c

  • go test -race passes for ./pkg/authz/..., ./pkg/transport/..., ./pkg/llm/... and ./pkg/mcp/....
  • I replayed my own probe through ParsingMiddleware → authz.Middleware → ReverseProxy{FlushInterval: -1} against a backend that sends ETag and a Content-Length:
Backend response What the client now gets
text/plain list with one denied tool filtered, 200, application/json, no ETag
result nested past the depth cap 500, application/json, generic JSON-RPC error
correctly labeled application/json list filtered, ETag gone, Cache-Control: private, no-store
br 200 and x-gzip 404 list br becomes 500, the 404 keeps its status; the body is a generic error, with no Content-Encoding and no leak
  • Preserved: Mcp-Session-Id and WWW-Authenticate on filtered methods.
  • Unaffected: the legacy-SSE POST that answers 202 Accepted as text/plain, and the empty 202.
  • There were no truncated reads and no superfluous WriteHeader in any case.

Existing-user impact, all of which the PR body states

  • A fail-closed answer is now HTTP 500 instead of 200 carrying a JSON-RPC error. Clients that treated the old 200 as a protocol-level reply will see a transport error for these rare cases. That is the correct signal, and the docs say so.
  • Headers for filtered methods now arrive only after the whole response is filtered. Body delivery time is the same as before, because Write() already buffered everything. Only a client with a strict header-wait timeout on a very large list would notice.
  • Encoded non-2xx bodies are no longer forwarded unfiltered. That closes a real bypass for codings Go's transport does not decode, such as x-gzip and br.

Follow-up worth its own issue. The GET event-stream writer still passes every non-2xx body through unfiltered, and the POST path now filters them. You already note this as out of scope, and I agree. I would file it now so it does not get lost, because the encoded case on that path is the same bypass this PR just closed on POST.

@ChrisJBurns
ChrisJBurns merged commit c36c185 into main Nov 26, 2026
78 of 79 checks passed
@ChrisJBurns
ChrisJBurns deleted the ChrisJBurns/l6ci8 branch November 26, 2026 19:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large PR: 600-999 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants