Repository navigation
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
f4289c8 to
17c0685
Compare
aponcedeleonch
left a comment
There was a problem hiding this comment.
Thanks for this, @rkb32. It follows the direction from #6926 closely: it's modeled on toolFilterWriter, covers all five list types, reuses the shared per-type filters so the semantics match the POST path, and the transparent-proxy test is there. I also appreciate how candid the description is about the limitations.
The main thing to fix is that the stream path re-implements the head of resolveSSEEvent instead of reusing it, and in doing so it drops some of the POST path's fail-closed checks. Two of them can leak an unfiltered list from a hostile backend. Details are inline, and each fix should be small.
| } | ||
| chunk := w.buffer[:end] | ||
| w.buffer = w.buffer[end:] | ||
| return w.writeLines(w.processLines(parseSSELines(chunk))) |
There was a problem hiding this comment.
The UTF-8 BOM only gets stripped in finish(), on the trailing remainder. If the backend's first bytes are a BOM followed by data: {tools list}, the data: prefix doesn't match and the event passes through, while a client strips the BOM and dispatches it. This matters on the transparent proxy, where the backend owns the first bytes. processSSEResponse and toolFilterWriter both strip it up front. Stripping it once on the first buffered bytes, with a started flag, should cover it.
There was a problem hiding this comment.
Fixed. The BOM is stripped on the first write, once per stream, using a started flag. Test: TestSSEStreamStripsLeadingBOM.
There was a problem hiding this comment.
Thanks for the fix. There's one gap left: started gets set on the first Write, even when that write carries only part of the BOM. On the transparent proxy the backend controls how the bytes are chunked. So it can send 0xEF, flush, and then send 0xBB 0xBF followed by data: {...}\n\n. ReverseProxy forwards each read as its own Write, so the BOM is never stripped. The first line doesn't match data:, and the event passes through unfiltered, while a client strips the BOM and reads the list.
I'd strip it from w.buffer instead of data. Then only set started once the buffer holds at least three bytes or no longer looks like the start of a BOM. A test that writes the BOM one byte at a time, flushing in between, would cover it.
| } | ||
| w.decided = true | ||
| mediaType, _, _ := mime.ParseMediaType(w.ResponseWriter.Header().Get("Content-Type")) | ||
| w.passThrough = mediaType != "text/event-stream" |
There was a problem hiding this comment.
Anything that isn't text/event-stream passes through untouched. Both precedents sniff a 2xx body with an unrecognized media type and filter or fail closed (the default branch in FlushAndFilter and toolFilterWriter.processUnrecognizedMimeType). Some Go clients don't check Content-Type, so I'd treat a 2xx GET body with a missing or odd Content-Type as an event stream.
There was a problem hiding this comment.
Fixed, with a different choice. A 2xx body with a non-text/event-stream type now fails closed rather than being sniffed and filtered, because a client that ignores Content-Type could read it as events. Non-2xx bodies pass through. Test: TestSSEStreamNonEventStreamBodies. I can switch to sniff-and-filter if you prefer.
There was a problem hiding this comment.
Fixed in 5e1fab1. A 2xx body with a non-text/event-stream type is read as one JSON-RPC message, as you suggested. A list answer is filtered and sent, other JSON-RPC answers pass unchanged, and anything that is not JSON-RPC is dropped. The body is buffered up to 1 MiB. Test: TestSSEStreamNonEventStreamBodies.
| ) | ||
|
|
||
| // runSSEStream serves a GET event stream through the authz middleware. The | ||
| // handler writes each chunk in order, calling Flush after each one when |
There was a problem hiding this comment.
Small one: this doc mentions a flush parameter that doesn't exist. Every test returns from the handler, so finish() covers them and they'd also pass with full buffering. Cases I'd add: case-folded alias, BOM, malformed plus result in one event, CRLF framing, keep-alive comment and endpoint event pass-through, the Cache-Control header, Flush between partial chunks, and a mislabeled Content-Type.
There was a problem hiding this comment.
Fixed. Added the missing cases: malformed-then-result, CRLF framing, comment and endpoint pass-through, and a flush between partial chunks. The doc comment no longer mentions a parameter that does not exist.
|
|
||
| A filtered list depends on the caller's permissions, so `tools/list`, `prompts/list`, and `resources/list` responses carry the HTTP header `Cache-Control: private, no-store`, and a `cacheScope` or `ttlMs` member the backend sent in the result is replaced with `"private"` or `0`. The proxy does not add either member when the backend omitted it, so a list from a backend on an MCP revision that predates these members reaches the client without them. A result that repeats `cacheScope` or `ttlMs`, or spells one with a case-insensitive alias, fails closed with a generic internal JSON-RPC error. `resources/templates/list` responses carry the same header, and their result always includes `cacheScope: "private"` and `ttlMs: 0`. | ||
|
|
||
| The SSE transport (`--transport sse`) filters list answers the same way. Before this change, an SSE client received the unfiltered `tools/list`, `prompts/list`, `resources/list`, `resources/templates/list` and `skills/list` answers, so a tool, prompt, resource or skill it was not permitted to use could appear in the list. Now the proxy filters each event on the `GET` event stream as it arrives. It picks the filter from the shape of the result (`tools`, `prompts`, `resources`, `resourceTemplates` or `skills`), not from the request method. A result that carries more than one of these members, or a frame that is not a JSON-RPC response but still carries a result, fails closed with a JSON-RPC error. Other results, such as `tools/call` answers, pass through unchanged. A non-stream response on that path is passed through unchanged, because it is not parsed as an event stream. |
There was a problem hiding this comment.
Docs should describe current behavior, so I'd drop the "Before this change" part. It's also worth saying the filter runs on streamable-HTTP GET streams too.
There was a problem hiding this comment.
Fixed: removed the "Before this change" wording and corrected the 2xx sentence. Not added: the streamable-HTTP GET note, because I have not verified that path yet.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #6949 +/- ##
=========================================
+ Coverage 0 81.42% +81.42%
=========================================
Files 0 891 +891
Lines 0 90983 +90983
=========================================
+ Hits 0 74084 +74084
- Misses 0 16894 +16894
- Partials 0 5 +5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
17c0685 to
27113bf
Compare
| // Any other clean response is sent unchanged. Anything else (not JSON-RPC, or | ||
| // a result outside a clean response) is dropped, so nothing unfiltered reaches | ||
| // the client. | ||
| func (w *sseStreamFilterWriter) writeSniffed(body []byte) { |
There was a problem hiding this comment.
Thanks for switching to sniffing. My only concern is that the body is only ever read as JSON. So a 2xx body that's SSE-framed but has a missing or wrong Content-Type gets dropped entirely.
FlushAndFilter's default branch already handles both shapes. It filters a body as JSON or as SSE, whichever carries a result, and passes it through when neither does. Rather than reimplementing that here, I'd pull the decision out into a small helper that both paths call. For example, something that takes the raw body and returns which shape it carries a result in: JSON, SSE, or none. That way the rules for mislabeled bodies live in one place and the two paths can't drift apart. In the stream writer it would run on the buffered body in finish(), same as today.
One trade-off stays either way. The body is held until the handler returns, so a mislabeled long-lived stream reaches the client only when it ends or hits 1 MiB. I think that's acceptable for a misbehaving backend, but I'd call it out in the PR body.
Also, the doc comments on errSSEUnrecognizedMediaType and decide still describe the earlier version ("is not parsed", "fails closed"). The note in the PR body that says this was done as I suggested needs an update too, since the suggestion was to treat these bodies as an event stream.
| assert.Equal(t, body, rr.Body.String(), "comments and endpoint events are not list answers") | ||
| } | ||
|
|
||
| func TestSSEStreamFlushBetweenPartialChunks(t *testing.T) { |
There was a problem hiding this comment.
Thanks for adding these, the coverage is much better now. That said, the point from the first round still applies. Every test returns from the handler before it asserts, so finish() writes everything out, and the tests would also pass if the writer buffered the whole body until the end.
I'd add a check that a complete event reaches the client while the handler is still running. For example, the handler writes one complete list event, flushes, and then asserts on rr.Body before it returns. The assertion should check that the allowed tool is there and the denied one isn't. ServeHTTP runs the handler on the test's goroutine, so reading the recorder there is race-free. This test is a natural place for it, since it already flushes mid-stream.
5c86827 to
0702a94
Compare
aponcedeleonch
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround, @rkb32. Almost everything from the last two rounds is in. The split BOM, the SSE-framed mislabeled body and the mid-stream test all look good, and sniffBodyShape is a step in the right direction.
The main thing left is the reuse point. The per-event filtering is shared now, but the framing loop, the head of resolveSSEEvent, the mislabeled-body decision and the list mapping are still written twice, and one of them has already drifted. Details inline.
Two things that don't fit on a line:
- The PR body is out of date. It still says a mislabeled 2xx is "read as one JSON-RPC message, as the reviewer suggested" and that anything that isn't JSON-RPC is dropped, but a body with no result now passes through. The trade-off that a mislabeled body is held until the handler returns should be in there too, plus the POST path changes (see inline).
- The non-test change is around 680 lines, over the 400-line guideline. Moving the POST path fixes to their own PR would bring it closer and make both easier to review. Also, the test plan should use
task testrather thango test.
| "successful response has a Content-Type other than text/event-stream and no readable JSON-RPC result") | ||
|
|
||
| // listMembers maps each list member of a result to the method whose filter applies. | ||
| var listMembers = map[string]string{ |
There was a problem hiding this comment.
This is a second copy of the method-to-filter mapping in responseFilterForMethod, and nothing ties the two together. If someone adds a list type there and forgets this map, the GET stream passes that list through unfiltered and no test fails. I'd either derive one from the other, or add a test that pins every list kind in responseFilterForMethod (other than find_tool) to a member here.
| // JSON-RPC response with a list member is filtered and sent; any other clean | ||
| // response is sent unchanged. A body carrying no result in either shape is | ||
| // dropped, so nothing unfiltered reaches the client. | ||
| func (w *sseStreamFilterWriter) writeSniffed(body []byte) { |
There was a problem hiding this comment.
Thanks for adding sniffBodyShape. That said, the decision around it is still written twice. writeSniffed reimplements processJSONResponse and the default branch of FlushAndFilter, and the new hasDataLine fallback now lives in both places.
One way to fold it: have sniffBodyShape return bodyShapeSSE when the body has a data line, so the fallback is in one place. Then run the sniffed body through the same JSON and SSE processing the POST path uses, writing to the underlying writer. Once the shared filter can pick its method from the result shape (see the comment on filterEvent), I think this function mostly goes away.
| switch sniffBodyShape(body) { | ||
| case bodyShapeSSE: | ||
| case bodyShapeJSON: | ||
| slog.Warn("dropped a 2xx JSON body carrying a result that is not a single JSON-RPC response", |
There was a problem hiding this comment.
This has already drifted from the POST path. There, processJSONResponse answers the same body (a JSON value that carries a result but isn't a clean Response) with a JSON-RPC error that carries the request id. Here it's dropped silently, so the client waits on its pending request until it times out, which is the #6037 problem. I'd write an error envelope here like the other fail-closed branches do. Reusing the POST logic, as in the comment above, would fix this for free.
|
|
||
| // processLines filters each event in lines. Blank lines separate events and | ||
| // are kept as they are. | ||
| func (w *sseStreamFilterWriter) processLines(lines []sseLine) []sseLine { |
There was a problem hiding this comment.
processSSEResponse still has its own inline LF-split loop that does the same thing as parseSSELines plus processLines. I'd have processSSEResponse call these two as well, with processLines taking the per-event resolver as a function. Then there's one place that decides what a line and an event are, which is exactly where the CR and CRLF bugs have shown up before.
| if len(event) == 0 { | ||
| return nil | ||
| } | ||
| if eventHasLoneCR(event) { |
There was a problem hiding this comment.
This repeats the start of resolveSSEEvent: the lone-CR check, the data-value join and the empty check. resolveSSEEvent then runs them all again, so a list event gets parsed three or four times.
I'd move the shape lookup into the shared filter instead. For example, when ResponseFilteringWriter has no method, filterSSEEventData could pick the filter with listMethodForResult. Then this function shrinks to the ambiguous-key check plus a call to resolveSSEEvent. The lone-CR branch would still want the frame id, so resolveSSEEvent could fall back to frameID when requestID() is empty.
| return lines | ||
| } | ||
|
|
||
| // hasAmbiguousResultKey reports whether a JSON object payload has a top-level key |
There was a problem hiding this comment.
The POST path doesn't have this check, and I think that's correct. There the method is known, so a list is always filtered and re-encoded with a single lowercase result. Here the filter is picked from the shape, and a non-list event passes through raw, so {"result":{"tools":[...]},"Result":{"content":[]}} could reach a client that reads the exact key. A sentence saying why only this path needs it would save the next reader from wondering whether POST is missing it.
| // filtered per event as they arrive, by the shape of each result. Every GET | ||
| // is wrapped, because the legacy SSE client may not send Accept: | ||
| // text/event-stream, so the Accept header cannot mark the stream. | ||
| if r.Method == http.MethodGet { |
There was a problem hiding this comment.
This wraps every GET that reaches the authz middleware, not only event streams. On the transparent proxy that includes any non-MCP GET to the backend. All of them now lose Accept-Encoding, get Cache-Control: private, no-store on a 2xx and can't upgrade. A non-SSE 2xx body is also held until the handler returns and dropped if it's over 1 MiB.
Most of this follows from not trusting Content-Type, so I'm fine with the behavior. It's broader than what the PR body and the docs describe, though, so I'd call it out in the user-facing section as a change for any GET behind authz.
| if len(event) == 0 { | ||
| return nil | ||
| } | ||
| if eventHasLoneCR(event) { |
There was a problem hiding this comment.
These look like real fixes. A WHATWG client does split on a lone CR, so the comment this replaces was wrong about "denial, never disclosure". Same for the hasDataLine fallback in FlushAndFilter and the Warn to Debug change below.
My concern is scope. They change what POST and streamable responses do, and the PR body doesn't mention the POST path at all. I'd move them to their own PR, with TestPOSTFailsClosedOnSplitResultInMislabeledBody. If you'd rather keep them here, please add them to the user-facing section as before and after.
|
|
||
| A filtered list depends on the caller's permissions, so `tools/list`, `prompts/list`, and `resources/list` responses carry the HTTP header `Cache-Control: private, no-store`, and a `cacheScope` or `ttlMs` member the backend sent in the result is replaced with `"private"` or `0`. The proxy does not add either member when the backend omitted it, so a list from a backend on an MCP revision that predates these members reaches the client without them. A result that repeats `cacheScope` or `ttlMs`, or spells one with a case-insensitive alias, fails closed with a generic internal JSON-RPC error. `resources/templates/list` responses carry the same header, and their result always includes `cacheScope: "private"` and `ttlMs: 0`. | ||
|
|
||
| The SSE transport (`--transport sse`) filters list answers the same way. Each event on the `GET` event stream is filtered as it arrives, so `tools/list`, `prompts/list`, `resources/list`, `resources/templates/list` and `skills/list` answers are checked before a client sees them. Visibility is decided by the caller's permissions when the stream connects, not by fresh claims on each event. It picks the filter from the shape of the result (`tools`, `prompts`, `resources`, `resourceTemplates` or `skills`), not from the request method. A result that carries more than one of these members, or a frame that is not a JSON-RPC response but still carries a result, fails closed with a JSON-RPC error. Other results, such as `tools/call` answers, pass through unchanged. A successful (2xx) response on that path whose `Content-Type` is not `text/event-stream` is held until the handler returns, then read by its shape: as one JSON-RPC message, or as SSE events when its framing carries a result. A list answer is filtered and sent; other results are sent unchanged. A clean JSON-RPC response without a list, including an error, is sent unchanged. A body with no JSON-RPC result passes through unchanged, as the buffered `POST` path does. A body with `data:` lines is filtered event by event, so a result split across the data lines of one event is still filtered. A JSON-RPC batch carrying a result is dropped. Informational `1xx` responses, such as `103 Early Hints`, are forwarded as they arrive and do not decide the mode. Because the body is held, a mislabeled long-lived stream reaches the client only when it ends, and a body larger than 1 MiB stops the stream: nothing more is written, and the client gets no further data. A non-2xx response is passed through unchanged, because it is an error body and is not parsed as an event stream. An event with a bare CR line break whose data, read with CR as a line break, carries a result is refused, since a client that honours CR would read data the filter cannot see. The same holds on the `POST` path. An event or sniffed body whose top-level `result` key is duplicated or spelled in another case is refused, because a client may read a different list than the filter sees. A connection takeover on a filtered stream, such as a `101` upgrade, is refused, since its bytes would skip the filter. A filtered stream with a `Content-Encoding` other than `identity` is answered with `502 Bad Gateway`, since its body cannot be filtered. A sniffed body whose list answer is ambiguous or fails to filter is answered with a JSON-RPC error that carries the request id. An event larger than 1 MiB fails the stream closed. |
There was a problem hiding this comment.
Following up on the first round: the middleware wraps every GET, so this also runs on the streamable-HTTP GET stream, vMCP's included. The unit tests already go through Middleware without any transport-specific setup. I'd say so here instead of scoping it to --transport sse.
|
|
||
| A filtered list depends on the caller's permissions, so `tools/list`, `prompts/list`, and `resources/list` responses carry the HTTP header `Cache-Control: private, no-store`, and a `cacheScope` or `ttlMs` member the backend sent in the result is replaced with `"private"` or `0`. The proxy does not add either member when the backend omitted it, so a list from a backend on an MCP revision that predates these members reaches the client without them. A result that repeats `cacheScope` or `ttlMs`, or spells one with a case-insensitive alias, fails closed with a generic internal JSON-RPC error. `resources/templates/list` responses carry the same header, and their result always includes `cacheScope: "private"` and `ttlMs: 0`. | ||
|
|
||
| The SSE transport (`--transport sse`) filters list answers the same way. Each event on the `GET` event stream is filtered as it arrives, so `tools/list`, `prompts/list`, `resources/list`, `resources/templates/list` and `skills/list` answers are checked before a client sees them. Visibility is decided by the caller's permissions when the stream connects, not by fresh claims on each event. It picks the filter from the shape of the result (`tools`, `prompts`, `resources`, `resourceTemplates` or `skills`), not from the request method. A result that carries more than one of these members, or a frame that is not a JSON-RPC response but still carries a result, fails closed with a JSON-RPC error. Other results, such as `tools/call` answers, pass through unchanged. A successful (2xx) response on that path whose `Content-Type` is not `text/event-stream` is held until the handler returns, then read by its shape: as one JSON-RPC message, or as SSE events when its framing carries a result. A list answer is filtered and sent; other results are sent unchanged. A clean JSON-RPC response without a list, including an error, is sent unchanged. A body with no JSON-RPC result passes through unchanged, as the buffered `POST` path does. A body with `data:` lines is filtered event by event, so a result split across the data lines of one event is still filtered. A JSON-RPC batch carrying a result is dropped. Informational `1xx` responses, such as `103 Early Hints`, are forwarded as they arrive and do not decide the mode. Because the body is held, a mislabeled long-lived stream reaches the client only when it ends, and a body larger than 1 MiB stops the stream: nothing more is written, and the client gets no further data. A non-2xx response is passed through unchanged, because it is an error body and is not parsed as an event stream. An event with a bare CR line break whose data, read with CR as a line break, carries a result is refused, since a client that honours CR would read data the filter cannot see. The same holds on the `POST` path. An event or sniffed body whose top-level `result` key is duplicated or spelled in another case is refused, because a client may read a different list than the filter sees. A connection takeover on a filtered stream, such as a `101` upgrade, is refused, since its bytes would skip the filter. A filtered stream with a `Content-Encoding` other than `identity` is answered with `502 Bad Gateway`, since its body cannot be filtered. A sniffed body whose list answer is ambiguous or fails to filter is answered with a JSON-RPC error that carries the request id. An event larger than 1 MiB fails the stream closed. |
There was a problem hiding this comment.
Nit: I'd go easier on the docs here. This paragraph reads more like a list of every edge case the code handles than something an operator needs. I'd keep the parts a user can observe:
- list answers on the GET stream are filtered per event, by the shape of the result
- permissions are taken when the stream connects
- a mislabeled 2xx is held until the handler returns and capped at 1 MiB
- a content-coded stream gets a 502
- malformed or ambiguous frames fail closed with a JSON-RPC error
The bare CR, duplicate result key, 1xx, hijack and batch details fit better as code comments, and most of those already exist. Splitting what's left into a short intro and a list would help too. There's also a stray extra blank line after the paragraph.
A POST body that carries a result past encoding/json's depth cap was written unfiltered. Reject it instead, answering with the request id, as the GET stream does. Also filter a result split across lone CR line breaks, and share the no-shape decision between the POST path and the GET stream so the two cannot drift apart.
|
@aponcedeleonch Thanks for the reviews. Two things before I reply to each thread: Correction: my earlier reply said the cap is 1 MiB. It's 16 MiB, matching the default in pkg/mcp/tool_filter.go. The docs and PR body say so. |
0702a94 to
375410e
Compare
b719112 to
42163f0
Compare
6497a3b to
1c6f188
Compare
The GET event stream carried list answers unfiltered. Filter each event as it arrives, choosing the filter from the shape of its result, with the same per-entry authorization as the streamable path. Answer rejected frames with a JSON-RPC error that carries the request id, so the client does not wait for a timeout. Document the limits: a 16 MiB cap on an open event, a held body sniffed before it is filtered, and a 101 upgrade through ReverseProxy, which is refused.
The POST path and the GET stream each decided how to handle a 2xx body with an unrecognised media type, in different orders. Move that decision into one classifier. Each caller still writes its own rejection and chooses its own request id, so no response changes.
A tools value that is a string or object, including a string of JSON naming a tool, passed the filter unchanged on the GET event stream. Fail closed on any tools value except a list naming no tool. Drop an id-less malformed event instead of answering it with an error that has no id, which would end the client session.
1c6f188 to
c214582
Compare
Fixes #6926.
Summary
Why: Over SSE, list answers (tools, prompts, resources, resource templates, skills) reached the client on the GET event stream, which was not filtered.
What: Each GET event is now filtered as it arrives, with the same per-entry authorization as the streamable path. The filter is picked from the shape of each result.
Does this introduce a user-facing change?
text/event-stream. Before: body passed through. After: a list answer is filtered and sent; other JSON-RPC answers are sent unchanged; anything that is not JSON-RPC is dropped. Non-2xx bodies still pass through unchanged.Special notes for reviewers
find_toolon the SSE path, prompt/resource deadline behaviour, stdio transport.Test plan
go testforpkg/authz/...,pkg/transport/proxy/httpsse,pkg/transport/proxy/transparent(run locally, not viatask)🤖 Generated with Claude Code