Repository navigation
Commit filtered response heads after filtering - #7340
Conversation
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]>
rdimitrov
left a comment
There was a problem hiding this comment.
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
- Make the
docs/authz.mdbullets and the PR's before/after say where they hold. As written, "gets HTTP 500 … served asapplication/json" is what a client sees only when the writer is used without a flush. Behind the transparent proxy a client sees200and 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. - 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 letFlushAndFiltercommit once. That would make this relabel effective, and it fixes theETagand 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. - Add one test that goes through
ReverseProxy{FlushInterval: -1}rather than the bare writer. The current table passes onmainfor 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
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]>
|
Thanks @rdimitrov, you were right: the first commit changed nothing for clients behind the transparent proxy. I reproduced it: 1. Docs and PR claims matched the real path
2. Headers held back for filtered methods
3. Tests through
Found in a second review pass and fixed here
Left as follow-ups, both already on main
|
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]>
|
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
Filtered bodies kept the backend's
Tests
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. |
|
/retest |
rdimitrov
left a comment
There was a problem hiding this comment.
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 -racepasses 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 sendsETagand aContent-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-IdandWWW-Authenticateon filtered methods. - Unaffected: the legacy-SSE
POSTthat answers202 Acceptedastext/plain, and the empty202. - There were no truncated reads and no
superfluous WriteHeaderin 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-gzipandbr.
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.
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'shttputil.ReverseProxy, which is built withFlushInterval: -1and calls the writer'sFlush()after copying the body.Flush()then sent the backend's status and headers to the client, and only afterwards didFlushAndFilterdecide what to answer. As a result:result) reached the client as HTTP 200, carrying a JSON-RPC error body.Content-Type(for exampletext/plain) and entity headers such asETag, 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, andFlushAndFiltersends the status and headers once, after filtering. Unfiltered methods still send them on flush, as before.FlushAndFilterdrops 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 appliesCache-Control: private, no-store.application/jsonthrough the newrelabelAsJSON().x-gziporbr) reached the client unfiltered. A 2xx becomes a 500; a non-2xx keeps its status, so an expired-session 404 still reaches the client.rejectEncodedResponse-from-Flushworkaround and itsrejectedlatch. They only existed because headers were sent early.docs/authz.mdnow describes when a filtered method's headers are sent, and how mislabeled, undecodable, and lone-CR responses are handled.Type of change
Test plan
go test -raceon./pkg/authz/...,./pkg/transport/proxy/...,./pkg/llm/...,./pkg/mcp/....ParsingMiddleware→authz.Middleware→httputil.ReverseProxy{FlushInterval: -1}against anhttptestbackend:TestMiddlewareBehindReverseProxyCommitsFilteredHead,...FlushesUnfilteredHead, and...FilteredFraming.Flush()restored, the fail-closed cases get200andtext/plainand keep the backend'sETag. The BOM and trailer cases fail with the fixes removed.golangci-linton./pkg/authz/...reports 0 issues. The full localtask lint-fixcrashes 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
Content-Type,ETagand other entity headers.application/jsonand no backend entity headers.A mislabeled body that the filter rewrites (for example
text/plaincarrying a list)ETag.application/jsonwith no backend entity headers.When headers are sent
Backend entity headers and HTTP trailers
Content-Length,ETag,Last-Modified, digests and trailers were forwarded on a filtered method's response, describing the unfiltered body.Content-Typeis kept.Content-encoded non-2xx body
Content-Encodingintact, unfiltered.application/json.Empty 2xx body with a
Content-EncodingContent-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
sse_stream_filter.go) has its ownFlushand still streams each event.ResponseController.Flushstops at ourFlushmethod. The writer has noUnwrap, so a no-opFlushcannot be bypassed to send headers on the underlying writer.dropBackendTrailersdeletes every header that the backend'sTrailerheader names. A backend announcingTrailer: Content-Typeloses 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.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.x-gzip: behindWithoutAcceptEncoding, Go's transport decodes a body labeled exactlygzipbefore the filter sees it, so only codings the transport does not decode reach this path.decide()insse_stream_filter.go; pinned bysse_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