diff --git a/docs/authz.md b/docs/authz.md index 5e63170057..15bc9255ca 100644 --- a/docs/authz.md +++ b/docs/authz.md @@ -515,6 +515,8 @@ Then `tools/list` will only show the "weather" tool for that user. 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`) and the GET stream of streamable HTTP filter list answers the same way, because the middleware wraps every `GET`. Each event is filtered as it arrives, with the filter chosen from the result's shape. A result that is not a clean JSON-RPC response, carries more than one list, or is ambiguous fails closed with a JSON-RPC error that carries the request id. A `find_tool` answer is filtered; other results pass through unchanged. A 2xx response that is not `text/event-stream` is held until the handler returns, then read as one JSON-RPC message or as SSE events. A non-2xx response passes through unchanged. A body larger than 16 MiB ends the stream with one error. A filtered stream with a `Content-Encoding` other than `identity` gets `502 Bad Gateway`. A frame with no readable id is dropped, because an error without an id ends the client's session. + ##### Methods covered by a prompt or resource policy Some MCP methods do not name a capability directly but still act on one. They are diff --git a/pkg/authz/middleware.go b/pkg/authz/middleware.go index d1c5beed21..4839b2da6b 100644 --- a/pkg/authz/middleware.go +++ b/pkg/authz/middleware.go @@ -225,6 +225,18 @@ func Middleware(a authorizers.Authorizer, next http.Handler, passThroughTools ma annotationCache := NewAnnotationCache() return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // A GET opens the server-to-client event stream. Its list answers are + // 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 { + stream := newSSEStreamFilterWriter(w, a, r, annotationCache, passThroughTools) + // The filter cannot parse a content-coded body, so ask the backend for an identity body. + next.ServeHTTP(stream, mcp.WithoutAcceptEncoding(r)) + stream.finish() + return + } + // Check if we should skip authorization before checking parsed data if shouldSkipInitialAuthorization(r) { next.ServeHTTP(w, r) diff --git a/pkg/authz/response_filter.go b/pkg/authz/response_filter.go index cb654b2179..50f200fa2c 100644 --- a/pkg/authz/response_filter.go +++ b/pkg/authz/response_filter.go @@ -152,17 +152,30 @@ func (rfw *ResponseFilteringWriter) FlushAndFilter() error { // result, process it exactly as if it had been labeled correctly // (which filters clean frames and fails closed on dirty ones). Only a // body carrying no result under either shape passes through. - if carriesResult(rawResponse) { + action := classifyUnlabeledBody(rawResponse) + switch action { + case sniffFilterJSON, sniffRejectJSON: slog.Warn("response with unrecognized media type carries a JSON-RPC result; filtering as JSON", "method", rfw.method, "contentType", contentType) rfw.ResponseWriter.Header().Del("Content-Length") return rfw.processJSONResponse(rawResponse) - } - if sseCarriesResult(rawResponse) { + case sniffFilterSSE: slog.Warn("response with unrecognized media type carries a JSON-RPC result; filtering as SSE", "method", rfw.method, "contentType", contentType) rfw.ResponseWriter.Header().Del("Content-Length") return rfw.processSSEResponse(rawResponse) + case sniffRejectNamed: + slog.Warn("response with unrecognized media type names a result that could not be decoded; dropping", + "method", rfw.method, "contentType", contentType) + // Answer with the request id. If none is on the request, use the body's own id. + id := rfw.requestID() + if id == (jsonrpc2.ID{}) { + id = topLevelID(rawResponse) + } + return rfw.writeErrorResponse(id, + errors.New("dropped a frame carrying a result outside a clean Response")) + case sniffPassThrough: + // Falls through to the unchanged write below. } // The leading BOM was removed above, so the backend's Content-Length // is now three bytes too large even though this fallback doesn't filter @@ -270,7 +283,9 @@ func (rfw *ResponseFilteringWriter) processJSONResponse(rawResponse []byte) erro // transport-independent, so apply the same check here as on the SSE // path: if a non-Response, undecodable, or batch frame still carries a // result, fail closed rather than passing the smuggled list through. - if carriesResult(rawResponse) { + // mayCarryResult also catches a result nested past encoding/json's depth cap, + // which carriesResult cannot see. The GET stream fails the same case closed. + if mayCarryResult(rawResponse, [][]byte{rawResponse}, err) { slog.Warn("JSON response carried a result outside a clean Response frame; dropping as a protocol violation", "method", rfw.method) // A batch is replaced wholesale by this single error envelope @@ -280,7 +295,11 @@ func (rfw *ResponseFilteringWriter) processJSONResponse(rawResponse []byte) erro // already rejects batch requests outright (see #5745), so a // batch response on this path is already off-spec traffic. // Fail-closed is the right side to err on regardless. - return rfw.writeErrorResponse(rfw.requestID(), + id := rfw.requestID() + if id == (jsonrpc2.ID{}) { + id = topLevelID(rawResponse) + } + return rfw.writeErrorResponse(id, errors.New("dropped a frame carrying a result outside a clean Response")) } rfw.ResponseWriter.WriteHeader(rfw.statusCode) @@ -323,21 +342,11 @@ type sseLine struct { // single payload, and a blank line is structural — it dispatches the event // rather than being emittable content in its own right. // -// Lines are split on LF only, matching the client that actually consumes -// these streams (github.com/modelcontextprotocol/go-sdk's mcp/event.go, -// which ReadBytes('\n')s and never treats a lone CR as a line terminator) -- -// not the WHATWG EventSource grammar, which additionally splits on a bare CR. -// The two disagree on a body containing an interior "\r" (e.g. inside a -// data: payload): WHATWG would cut the line there, but the client reads it as -// one line and parses through. Following the WHATWG grammar here decoded a -// SUPERSET of what the client would treat as one line, letting the shorter, -// wrongly-split pieces slip past filtering undetected -- a real regression, -// not a hypothetical one. Splitting on LF only means we parse a superset of -// what a stricter reader would call one line, so we decode and filter *more* -// than before, never less: worst case for a client that does honor a lone CR -// (e.g. a browser EventSource) is a payload it mis-frames identically to how -// it would mis-frame the backend's raw bytes directly, since output stays -// byte-preserving -- denial, never disclosure. +// Lines are split on LF only, matching the go-sdk client (mcp/event.go), which +// never treats a lone CR as a line terminator. A client that honours a lone CR +// (WHATWG) can read data this split cannot see, so an event with a lone CR whose +// data carries a result, read that way, fails closed (eventHasLoneCR). Splitting +// on CR too caused an earlier regression with the go-sdk client. // // Every line is re-emitted with the same terminator it was scanned with, so // the output is structurally identical to the input (minus a leading UTF-8 @@ -359,38 +368,10 @@ func (rfw *ResponseFilteringWriter) processSSEResponse(rawResponse []byte) error // unfiltered. rawResponse = bytes.TrimPrefix(rawResponse, mcpparser.UTF8BOM) - var outputLines []sseLine - var event []sseLine - for len(rawResponse) > 0 { - idx := bytes.IndexByte(rawResponse, '\n') - var line, term []byte - if idx == -1 { - line, term, rawResponse = rawResponse, nil, nil - } else { - line, term, rawResponse = rawResponse[:idx], rawResponse[idx:idx+1], rawResponse[idx+1:] - } - - // A line is structurally blank once its trailing CR (left over from - // a "\r\n" terminator the LF-only split doesn't consume) is ignored; - // without this a CRLF-terminated blank line would scan as the - // single byte "\r" and never be recognised as the event separator. - // The blank line's own bytes (that "\r", if present) are preserved - // in the output below rather than dropped, so structure stays - // byte-identical to the input. - if len(bytes.TrimRight(line, "\r")) == 0 { - outputLines = append(outputLines, rfw.resolveSSEEvent(event)...) - outputLines = append(outputLines, sseLine{text: line, term: term}) - event = nil - continue - } - event = append(event, sseLine{text: line, term: term}) - } - // A trailing event with no closing blank line: the go-sdk client (see - // mcp/event.go's yieldEvent, called once more after its read loop hits - // EOF) does still dispatch whatever is buffered at that point, so this - // is filtered like any other event, not dropped. We write these bytes - // (filtered) without fabricating a terminator the backend didn't send. - outputLines = append(outputLines, rfw.resolveSSEEvent(event)...) + // A trailing event with no closing blank line is filtered like any other: + // processSSELines resolves it too. Its bytes are written without a + // terminator the backend did not send. + outputLines := processSSELines(parseSSELines(rawResponse), rfw.resolveSSEEvent) for _, l := range outputLines { if _, err := rfw.ResponseWriter.Write(l.text); err != nil { @@ -412,21 +393,40 @@ func (rfw *ResponseFilteringWriter) resolveSSEEvent(event []sseLine) []sseLine { if len(event) == 0 { return nil } - - dataValues := eventDataValues(event) - if len(dataValues) == 0 { + dataValues, assembled, loneCR := assembleSSEEvent(event) + if loneCR { + body := rfw.errorResponseBody(rfw.requestID(), errors.New("event carries a bare CR line break that the filter cannot split")) + return errorEventLines(body) + } + if len(assembled) == 0 { + // No data field, or an empty data buffer: a client never dispatches an empty + // data buffer, so there is nothing to classify or fail closed on. return event } + return rfw.resolveAssembled(event, dataValues, assembled) +} +// assembleSSEEvent joins the data: values of one SSE event. loneCR reports an +// event with a bare CR line break, which a client that honours CR would split, +// so the filter cannot read it as written. assembled is empty when the event has +// no data: field or an empty payload. +func assembleSSEEvent(event []sseLine) (dataValues [][]byte, assembled []byte, loneCR bool) { + if eventHasLoneCR(event) { + return nil, nil, true + } + dataValues = eventDataValues(event) + if len(dataValues) == 0 { + return nil, nil, false + } // No whole-buffer trim needed here: the per-value trim in eventDataValues // already leaves nothing but JSON-significant bytes at either edge of the join. - assembled := bytes.Join(dataValues, []byte("\n")) - if len(assembled) == 0 { - // A client never dispatches an empty data buffer, so there's nothing - // to classify or fail closed on. - return event - } + return dataValues, bytes.Join(dataValues, []byte("\n")), false +} +// resolveAssembled filters an event whose lone-CR check and data join were already +// done by the caller. dataValues and assembled are that join: assembled is non-empty. +// The GET stream's filterEvent calls it directly, so those checks run once per event. +func (rfw *ResponseFilteringWriter) resolveAssembled(event []sseLine, dataValues [][]byte, assembled []byte) []sseLine { replacement, failedClosed := rfw.filterSSEEventData(assembled) if replacement == nil { replacement, failedClosed = rfw.probeValuesForSmuggledResult(dataValues) @@ -437,6 +437,78 @@ func (rfw *ResponseFilteringWriter) resolveSSEEvent(event []sseLine) []sseLine { return rebuildEventWithPayload(event, replacement, failedClosed) } +// errorEventLines replaces a whole event with one `data:` line carrying body. It is +// used when the event's data cannot be located line by line, as with a lone CR. +func errorEventLines(body []byte) []sseLine { + return []sseLine{{text: append([]byte("data: "), body...), term: []byte("\n")}} +} + +// eventHasLoneCR reports whether an event has a bare CR that a spec client reads +// as a line break, and whose data, read that way, carries a result. The LF-only +// split cannot see such data, so the caller fails the event closed. A CR at the +// end of a line is the first half of a CRLF terminator and is not lone. The LF +// split stays as it is: splitting on CR too caused an earlier regression with the +// go-sdk client. +func eventHasLoneCR(event []sseLine) bool { + var raw []byte + lone := false + for _, l := range event { + if i := bytes.IndexByte(l.text, '\r'); i != -1 && i != len(l.text)-1 { + lone = true + } + raw = append(raw, l.text...) + raw = append(raw, l.term...) + } + if !lone { + return false + } + // Read the event as a CR-honouring client does: CRLF, CR and LF all end a line. + view := bytes.ReplaceAll(bytes.ReplaceAll(raw, []byte("\r\n"), []byte("\n")), []byte("\r"), []byte("\n")) + // A CR-honouring client also ends an event at a blank line inside this LF event, + // so each such event is checked on its own. Joining across them would let a + // junk event hide a result in the next one. + for _, ev := range splitOnBlankLines(parseSSELines(view)) { + var evRaw []byte + for _, l := range ev { + evRaw = append(evRaw, l.text...) + evRaw = append(evRaw, l.term...) + } + values := eventDataValues(ev) + joined := bytes.Join(values, []byte("\n")) + // mayCarryResult also catches a result nested past the depth cap in this piece. + _, decodeErr := jsonrpc2.DecodeMessage(joined) + if mayCarryResult(joined, values, decodeErr) || sseCarriesResult(evRaw) { + return true + } + } + return false +} + +// splitOnBlankLines groups lines into events, each ending at a blank line. +func splitOnBlankLines(lines []sseLine) [][]sseLine { + var events [][]sseLine + var cur []sseLine + for _, l := range lines { + if len(bytes.TrimRight(l.text, "\r")) == 0 { + if len(cur) > 0 { + events = append(events, cur) + } + cur = nil + continue + } + cur = append(cur, l) + } + if len(cur) > 0 { + events = append(events, cur) + } + return events +} + +// hasDataLine reports whether body has at least one SSE data field. +func hasDataLine(body []byte) bool { + return len(eventDataValues(parseSSELines(body))) > 0 +} + // eventDataValues extracts one event's `data:` field values, in order, each // trimmed exactly as the client trims it. func eventDataValues(event []sseLine) [][]byte { @@ -584,9 +656,16 @@ func (rfw *ResponseFilteringWriter) filterSSEEventData(data []byte) (replacement "method", rfw.method) return rfw.errorResponseBody(rfw.requestID(), errors.New("dropped a frame carrying a result outside a clean Response")), true + case decodeErr != nil && namesResultKey(data): + // Undecodable, but it names "result": a result nested past the JSON depth cap is + // invisible to carriesResult, so it is failed closed like a smuggled one. + slog.Warn("SSE event named a result but could not be decoded; failing closed", + "method", rfw.method) + return rfw.errorResponseBody(rfw.requestID(), + errors.New("dropped a frame carrying a result outside a clean Response")), true case decodeErr != nil: // Genuinely undecodable and no smuggled result. Pass through unfiltered. - slog.Warn("SSE event data could not be decoded as JSON-RPC; passing through unfiltered", + slog.Debug("SSE event data could not be decoded as JSON-RPC; passing through unfiltered", "method", rfw.method, "error", decodeErr) return nil, false default: @@ -718,6 +797,31 @@ func sseCarriesResult(rawResponse []byte) bool { return false } +// bodyShape is the framing a body with an unrecognized media type carries a +// JSON-RPC result in. +type bodyShape int + +const ( + bodyShapeNone bodyShape = iota + bodyShapeJSON + bodyShapeSSE +) + +// sniffBodyShape reports which framing body carries a JSON-RPC result in. JSON is +// checked first, then SSE. A body carrying no result in either is bodyShapeNone. +// Both the buffered FlushAndFilter path and the SSE stream writer call it, so the +// rules for mislabeled bodies live in one place. body must have its BOM removed. +func sniffBodyShape(body []byte) bodyShape { + switch { + case carriesResult(body): + return bodyShapeJSON + case sseCarriesResult(body): + return bodyShapeSSE + default: + return bodyShapeNone + } +} + // objectCarriesResult reports whether a trimmed JSON object value has a // "result" key present, including an explicit `"result":null` — RawMessage's // UnmarshalJSON runs even for a JSON null, so probe.Result is non-nil (the @@ -730,6 +834,78 @@ func objectCarriesResult(trimmedObject json.RawMessage) bool { return json.Unmarshal(trimmedObject, &probe) == nil && probe.Result != nil } +// noShapeAction is what to do with a sniffed body that has no JSON-RPC or SSE result shape. +type noShapeAction int + +const ( + // noShapePassThrough writes the body unchanged. + noShapePassThrough noShapeAction = iota + // noShapeFilterSSE filters the body per event, because it has data lines. + noShapeFilterSSE + // noShapeReject answers the body with an error that carries the request id. + noShapeReject +) + +// decideNoShapeBody is the one place that decides a body with no recognised shape. +// Both the POST path and the GET stream call it. A body with data lines is filtered per +// event, so a result split across data lines is still seen. Any other body that names +// "result" is rejected when rejectNamed is set. The POST path sets it only when the body +// does not decode, because a clean Response with a null result is still answered as is. +func decideNoShapeBody(body []byte, rejectNamed bool) noShapeAction { + if hasDataLine(body) { + return noShapeFilterSSE + } + if rejectNamed && namesResultKey(body) { + return noShapeReject + } + return noShapePassThrough +} + +// sniffAction is the decision for a 2xx body whose media type is neither +// application/json nor text/event-stream. classifyUnlabeledBody makes it once, for +// both the POST path and the GET stream. Each caller then acts on it with its own +// writer and request id. +type sniffAction int + +const ( + // sniffFilterJSON: a clean JSON-RPC Response, filtered as one. + sniffFilterJSON sniffAction = iota + // sniffRejectJSON: a JSON body carries a result that is not a clean Response. + sniffRejectJSON + // sniffFilterSSE: the body is filtered per event. + sniffFilterSSE + // sniffRejectNamed: the body names a result that cannot be decoded. + sniffRejectNamed + // sniffPassThrough: no result in either shape, so the body is written unchanged. + sniffPassThrough +) + +// classifyUnlabeledBody picks the action for such a body. It checks the shape first, +// in the order the POST path always used. +func classifyUnlabeledBody(body []byte) sniffAction { + switch sniffBodyShape(body) { + case bodyShapeJSON: + message, _ := jsonrpc2.DecodeMessage(body) + if _, ok := message.(*jsonrpc2.Response); ok { + return sniffFilterJSON + } + return sniffRejectJSON + case bodyShapeSSE: + return sniffFilterSSE + case bodyShapeNone: + } + _, derr := jsonrpc2.DecodeMessage(body) + switch decideNoShapeBody(body, derr != nil) { + case noShapeFilterSSE: + return sniffFilterSSE + case noShapeReject: + return sniffRejectNamed + case noShapePassThrough: + return sniffPassThrough + } + return sniffPassThrough +} + // filterListResponse filters the list response based on authorization policies func (rfw *ResponseFilteringWriter) filterListResponse(response *jsonrpc2.Response) (*jsonrpc2.Response, error) { if response.Error != nil { @@ -1694,3 +1870,162 @@ func (carrier *findToolOutputCarrier) withFilteredToolIndexes(indexes []int) ([] map[string]json.RawMessage{"tools": mcpparser.EncodeJSONArrayValues(nil, filteredTools)}, ) } + +// processSSELines is the one place that splits lines into events. It hands each +// event's lines to resolve and keeps the blank separators. A line is blank once +// its trailing CR is ignored, so a CRLF blank line still separates events. +// Both the GET stream and the POST path use it. +func processSSELines(lines []sseLine, resolve func([]sseLine) []sseLine) []sseLine { + var out []sseLine + var event []sseLine + for _, l := range lines { + if len(bytes.TrimRight(l.text, "\r")) == 0 { + out = append(out, resolve(event)...) + out = append(out, l) + event = nil + continue + } + event = append(event, l) + } + // A trailing event with no closing blank line is still dispatched by the + // go-sdk client (see mcp/event.go's yieldEvent, called once more after its + // read loop hits EOF), so it is resolved too. + return append(out, resolve(event)...) +} + +// mayCarryResult reports whether a payload that is not a clean Response may still +// carry a result. carriesResult reads JSON values with encoding/json, which stops at +// its nesting cap, so a result nested deeper is invisible to it. An undecodable +// payload that names "result" anywhere is therefore treated as carrying one. +func mayCarryResult(payload []byte, dataValues [][]byte, decodeErr error) bool { + if carriesResult(payload) || anyValueCarriesResult(dataValues) { + return true + } + return decodeErr != nil && namesResultKey(payload) +} + +// namesResultKey reports whether an object key in payload is "result" in any spelling, +// including JSON escapes such as "result". It reads keys without parsing values, so +// it still works on a payload the JSON decoder cannot read, such as one nested past its +// depth cap. +func namesResultKey(payload []byte) bool { + for i := 0; i < len(payload); i++ { + if payload[i] != '"' { + continue + } + end := closingQuote(payload, i) + if end < 0 { + return false + } + if key, ok := decodedKey(payload[i : end+1]); ok && strings.EqualFold(key, "result") && + bytes.HasPrefix(bytes.TrimLeft(payload[end+1:], " \t\r\n"), []byte(":")) { + return true + } + i = end + } + return false +} + +// decodedKey returns the text of a JSON string token, with its escapes decoded. +func decodedKey(token []byte) (string, bool) { + var s string + if json.Unmarshal(token, &s) != nil { + return "", false + } + return s, true +} + +// anyValueCarriesResult reports whether any single data value carries a result. +func anyValueCarriesResult(dataValues [][]byte) bool { + for _, v := range dataValues { + if carriesResult(v) { + return true + } + } + return false +} + +// parseSSELines splits raw on LF, keeping each line's terminator. +func parseSSELines(raw []byte) []sseLine { + var lines []sseLine + for len(raw) > 0 { + idx := bytes.IndexByte(raw, '\n') + if idx == -1 { + lines = append(lines, sseLine{text: raw}) + break + } + lines = append(lines, sseLine{text: raw[:idx], term: raw[idx : idx+1]}) + raw = raw[idx+1:] + } + return lines +} + +// topLevelID reads the "id" member of the top-level JSON object in payload, for a frame +// that encoding/json cannot decode (for example one nested past its depth cap). It skips +// nested values and strings without parsing them, and returns an empty id when no scalar +// id is found. +func topLevelID(payload []byte) jsonrpc2.ID { + depth := 0 + for i := 0; i < len(payload); i++ { + switch payload[i] { + case '{', '[': + depth++ + case '}', ']': + depth-- + case '"': + end := closingQuote(payload, i) + if end < 0 { + return jsonrpc2.ID{} + } + if key, ok := decodedKey(payload[i : end+1]); ok && depth == 1 && key == "id" { + if id, ok := idValue(payload[end+1:]); ok { + return id + } + } + i = end + } + } + return jsonrpc2.ID{} +} + +// closingQuote returns the index of the quote that closes the string opened at start, or -1. +func closingQuote(b []byte, start int) int { + for i := start + 1; i < len(b); i++ { + switch b[i] { + case '\\': + i++ + case '"': + return i + } + } + return -1 +} + +// idValue parses the scalar id that follows an "id" key: a colon, then a string or number. +func idValue(rest []byte) (jsonrpc2.ID, bool) { + rest = bytes.TrimLeft(rest, " \t\r\n") + if len(rest) == 0 || rest[0] != ':' { + return jsonrpc2.ID{}, false + } + value := bytes.TrimLeft(rest[1:], " \t\r\n") + if len(value) == 0 || (value[0] != '"' && value[0] != '-' && (value[0] < '0' || value[0] > '9')) { + return jsonrpc2.ID{}, false + } + var raw json.RawMessage + if json.NewDecoder(bytes.NewReader(value)).Decode(&raw) != nil { + return jsonrpc2.ID{}, false + } + // jsonrpc2.ID has no exported fields, so build it from the decoded scalar. + if value[0] == '"' { + var s string + if json.Unmarshal(raw, &s) != nil { + return jsonrpc2.ID{}, false + } + return jsonrpc2.StringID(s), true + } + var n int64 + if json.Unmarshal(raw, &n) != nil { + return jsonrpc2.ID{}, false + } + return jsonrpc2.Int64ID(n), true +} diff --git a/pkg/authz/response_filter_split_test.go b/pkg/authz/response_filter_split_test.go new file mode 100644 index 0000000000..e0baf04ab2 --- /dev/null +++ b/pkg/authz/response_filter_split_test.go @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authz + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPOSTFiltersSplitResultInMislabeledBody(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + body := "data: {\"jsonrpc\":\"2.0\",\"id\":33,\ndata: \"result\":{\"tools\":[{\"name\":\"secret\",\"inputSchema\":{\"type\":\"object\"}}]}}\n\n" + req := httptest.NewRequest(http.MethodPost, "/mcp", nil) + rr := httptest.NewRecorder() + rfw := NewResponseFilteringWriter(rr, authorizer, req, "tools/list", nil, nil) + rfw.ResponseWriter.Header().Set("Content-Type", "text/plain") + _, err := rfw.Write([]byte(body)) + require.NoError(t, err) + require.NoError(t, rfw.FlushAndFilter()) + + assert.False(t, strings.Contains(rr.Body.String(), "secret"), "a split result in a mislabeled POST body must not leak") + assert.Contains(t, rr.Body.String(), `"id":33`, "the split result must be filtered and answered, not dropped") +} + +// TestPOSTFiltersNestedPastDepthCapInUndecodableBody pins the POST path to the GET +// stream's rule: a result nested past encoding/json's depth cap is failed closed, not +// written raw, under both a JSON and a mislabeled media type. +func TestPOSTFiltersNestedPastDepthCapInUndecodableBody(t *testing.T) { + t.Parallel() + + deep := strings.Repeat("[", 10001) + strings.Repeat("]", 10001) + body := `{"jsonrpc":"2.0","id":7,"result":{"tools":[{"name":"secret","inputSchema":{"x":` + deep + `}}]}}` + + for _, contentType := range []string{"application/json", "text/plain"} { + t.Run(contentType, func(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + req := httptest.NewRequest(http.MethodPost, "/mcp", nil) + rr := httptest.NewRecorder() + rfw := NewResponseFilteringWriter(rr, authorizer, req, "tools/list", nil, nil) + rfw.ResponseWriter.Header().Set("Content-Type", contentType) + _, err := rfw.Write([]byte(body)) + require.NoError(t, err) + require.NoError(t, rfw.FlushAndFilter()) + + assert.False(t, strings.Contains(rr.Body.String(), "secret"), "a deep result must not leak") + assert.Contains(t, rr.Body.String(), `"id":7`, "the deep result must be answered with its id") + }) + } +} diff --git a/pkg/authz/sse_stream_filter.go b/pkg/authz/sse_stream_filter.go new file mode 100644 index 0000000000..1e6a7b14af --- /dev/null +++ b/pkg/authz/sse_stream_filter.go @@ -0,0 +1,769 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authz + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "fmt" + "log/slog" + "mime" + "net" + "net/http" + "strings" + + "golang.org/x/exp/jsonrpc2" + + "github.com/stacklok/toolhive-core/mcpcompat/mcp" + "github.com/stacklok/toolhive/pkg/authz/authorizers" + mcpparser "github.com/stacklok/toolhive/pkg/mcp" + "github.com/stacklok/toolhive/pkg/vmcp/session/optimizerdec" +) + +// maxSSEEventBytes bounds how much unterminated data the filter buffers while it +// waits for the blank line that ends an event. An event still open past this +// size fails the stream closed. An event is filtered once its terminating blank +// line has arrived, so an event complete within one write is filtered at any size. +// The filter splits events on LF only, so a stream whose lines end in a bare CR +// never completes an event. It is held until this cap or the end of the stream, +// then fails closed. A client that splits on bare CR still sees a complete event, +// so this is a stall, not a bypass. +const maxSSEEventBytes = 16 << 20 + +// errSSEEncodedBody closes a filtered stream whose body is content-coded. +var errSSEEncodedBody = errors.New("filtered event stream is content-coded and cannot be parsed") + +// maxSniffedBodyBytes bounds a held 2xx body with a non-event-stream media type. Such a +// body is read only once the handler returns, so it is held whole until then. +const maxSniffedBodyBytes = 16 << 20 + +// errSSEEventTooLarge closes the stream when an unterminated event exceeds maxSSEEventBytes. +var errSSEEventTooLarge = errors.New("SSE event exceeds the filter's size limit") + +// errSSEBodyTooLarge closes a held 2xx body that exceeds maxSniffedBodyBytes. +var errSSEBodyTooLarge = errors.New("held 2xx body exceeds the filter's size limit") + +// errSSEBareCR is logged when an SSE event carries a lone CR line break the filter cannot split. +var errSSEBareCR = errors.New("event carries a bare CR line break that the filter cannot split") + +// errSSEUnrecognizedMediaType is logged when a successful response with a +// Content-Type other than text/event-stream carries neither a JSON-RPC response +// nor an SSE result. Such a body is rejected with an error carrying its id where +// that id is readable, and dropped otherwise. +var errSSEUnrecognizedMediaType = errors.New( + "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{ + "tools": string(mcp.MethodToolsList), + "prompts": string(mcp.MethodPromptsList), + "resources": string(mcp.MethodResourcesList), + "resourceTemplates": string(mcp.MethodResourcesTemplatesList), + "skills": "skills/list", +} + +// sseStreamFilterWriter filters a long-lived GET text/event-stream. Unlike +// ResponseFilteringWriter, which buffers the whole response until the handler +// returns, this writer forwards each event as soon as it is complete: on the +// GET stream the handler only returns when the client disconnects. +// +// Each event is classified by the shape of its result, not by request method: +// a result carrying tools, prompts, resources, resourceTemplates or skills is +// filtered with the matching filter. A frame that is not a clean Response but +// still carries a result fails closed. Everything else, including a body with +// no result, passes through unchanged. +type sseStreamFilterWriter struct { + http.ResponseWriter + authorizer authorizers.Authorizer + request *http.Request + annotationCache *AnnotationCache + passThroughTools map[string]struct{} + + buffer []byte + decided bool + passThrough bool + started bool + failed bool + failErr error + // sniff marks a successful body with another media type. The whole body is + // buffered and read as JSON-RPC or SSE once complete (see writeSniffed). + sniff bool + // scanLine is the start of the line being read and scanFrom is where the next + // search for a line end begins. Both index the buffer (see nextEventEnd). + scanLine, scanFrom int + // encoded marks a filtered stream whose body is content-coded, which cannot be parsed. + encoded bool + // committed records that the status line has been written. + committed bool +} + +// newSSEStreamFilterWriter wraps w for a GET stream served on behalf of r. +func newSSEStreamFilterWriter( + w http.ResponseWriter, a authorizers.Authorizer, r *http.Request, + annotationCache *AnnotationCache, passThroughTools map[string]struct{}, +) *sseStreamFilterWriter { + return &sseStreamFilterWriter{ + ResponseWriter: w, + authorizer: a, + request: r, + annotationCache: annotationCache, + passThroughTools: passThroughTools, + } +} + +// Unwrap exposes the underlying writer, so http.ResponseController can reach +// deadlines on the real connection. +func (w *sseStreamFilterWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +// Hijack refuses a connection takeover on a filtered stream. A hijacked connection +// would carry backend bytes past the filter in both directions. A pass-through +// response (a non-2xx, non-event-stream answer) is not filtered, so its takeover is +// allowed. Hijack is refused until the mode is decided. ReverseProxy hijacks a 101 +// upgrade before it writes the status, so an upgrade through it is refused here. +func (w *sseStreamFilterWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + hj, ok := w.ResponseWriter.(http.Hijacker) + if !w.decided || !w.passThrough || !ok { + return nil, nil, http.ErrNotSupported + } + return hj.Hijack() +} + +// WriteHeader forwards the status immediately, since the stream may stay open +// for a long time. Filtered modes strip Content-Length in markFiltered, because +// filtering can change the body size; a passed-through body keeps it. +func (w *sseStreamFilterWriter) WriteHeader(statusCode int) { + if statusCode >= 100 && statusCode < 200 && statusCode != http.StatusSwitchingProtocols { + // An informational response (e.g. 103 Early Hints) precedes the final status. + // Forward it without deciding the mode, so the final response still decides. + w.ResponseWriter.WriteHeader(statusCode) + return + } + w.decide(statusCode) + if w.encoded { + w.refuseEncoded() + return + } + w.committed = true + w.ResponseWriter.WriteHeader(statusCode) +} + +// refuseEncoded answers a content-coded filtered stream with 502, once. The body +// cannot be filtered, and forwarding it unfiltered would leak list answers. +func (w *sseStreamFilterWriter) refuseEncoded() { + if !w.encoded || w.committed { + return + } + w.committed = true + // The backend's coding and body headers describe a body that is not sent. + h := w.Header() + h.Del("Content-Encoding") + h.Del("Content-Type") + h.Del("Content-Length") + w.ResponseWriter.WriteHeader(http.StatusBadGateway) +} + +// Write buffers the body and forwards every complete event. It returns the length +// of data as given, even when a leading byte order mark is stripped. +func (w *sseStreamFilterWriter) Write(data []byte) (int, error) { + w.decide(http.StatusOK) + if w.passThrough { + return w.ResponseWriter.Write(data) + } + if w.failed { + w.refuseEncoded() + return 0, w.failErr + } + n := len(data) + w.buffer = append(w.buffer, data...) + if !w.started { + // A byte order mark can open the stream, and a backend may split it across + // writes. Hold back a partial BOM until it is complete, then strip it once. + if len(w.buffer) < len(mcpparser.UTF8BOM) && bytes.HasPrefix(mcpparser.UTF8BOM, w.buffer) { + return n, nil + } + w.started = true + w.buffer = bytes.TrimPrefix(w.buffer, mcpparser.UTF8BOM) + // A Flush may have scanned the partial BOM as line text. Restart the scan + // at the trimmed buffer's start, so it cannot index past the new end. + w.scanLine, w.scanFrom = 0, 0 + } + if w.sniff { + if len(w.buffer) > maxSniffedBodyBytes { + return 0, w.failSniffed() + } + return n, nil + } + if err := w.drainCompleteEvents(); err != nil { + return 0, err + } + return n, nil +} + +// Flush forwards every complete event, then flushes the transport. An event +// still missing its terminating blank line stays buffered for a later call. +func (w *sseStreamFilterWriter) Flush() { + // Decide before flushing: a flush commits the headers, and the mode decides + // whether Cache-Control: private, no-store must be among them. + w.decide(http.StatusOK) + if w.failed { + w.refuseEncoded() + return + } + if w.sniff { + // A sniffed body is decided only once it is complete, so flush the transport only. + if flusher, ok := w.ResponseWriter.(http.Flusher); ok { + flusher.Flush() + } + return + } + if err := w.drainCompleteEvents(); err != nil { + // Usually the client has gone away. That is routine on a long-lived stream. + slog.Debug("stopped writing filtered SSE stream", "error", err) + return + } + if flusher, ok := w.ResponseWriter.(http.Flusher); ok { + flusher.Flush() + } +} + +// finish runs once the wrapped handler has returned. No more data is coming, +// so any trailing partial event is filtered and written too. +func (w *sseStreamFilterWriter) finish() { + if w.passThrough || w.failed || len(w.buffer) == 0 { + return + } + if w.sniff { + body := w.buffer + w.buffer = nil + w.writeSniffed(body) + return + } + if err := w.drainCompleteEvents(); err != nil { + slog.Debug("stopped writing filtered SSE stream", "error", err) + return + } + trailing := w.buffer + w.buffer = nil + if len(trailing) == 0 { + return + } + if err := w.writeLines(w.processLines(parseSSELines(trailing))); err != nil { + slog.Debug("stopped writing filtered SSE stream", "error", err) + } +} + +// decide picks the mode once, from the Content-Type the handler set and the +// status it is answering with. An event stream is parsed and filtered as it +// arrives. A non-2xx body (an error) is passed through unchanged. A successful +// body with any other media type is sniffed (writeSniffed): it is held until the +// handler returns, then read as JSON-RPC or SSE, or dropped. A client that ignores +// Content-Type could read it as events, so it is never passed through unfiltered. +// Held bodies are buffered up to maxSniffedBodyBytes, so a long-lived mislabeled +// stream reaches the client only when it ends or hits that cap. Filtered modes +// carry caller-specific list answers, so they are marked uncacheable before +// their headers are committed, the same as the POST path. +func (w *sseStreamFilterWriter) decide(status int) { + if w.decided { + return + } + w.decided = true + // A non-2xx answer is an error. It passes through unchanged whatever its media type, + // so an error sent as text/event-stream is not filtered as a stream. + if status < 200 || status >= 300 { + w.passThrough = true + return + } + mediaType, _, _ := mime.ParseMediaType(w.ResponseWriter.Header().Get("Content-Type")) + if mediaType == "text/event-stream" { + w.markFiltered() + return + } + // Sniff it: a client may read it as events, so it is filtered like one or dropped. + w.sniff = true + w.markFiltered() +} + +// markFiltered prepares the headers of a filtered mode. Filtering changes the body +// size, so Content-Length must go, and the response must not be cached. Both run +// before headers are committed, which happens on WriteHeader, Write or Flush. +func (w *sseStreamFilterWriter) markFiltered() { + w.ResponseWriter.Header().Del("Content-Length") + w.ResponseWriter.Header().Set("Cache-Control", "private, no-store") + for _, value := range w.ResponseWriter.Header().Values("Content-Encoding") { + for _, coding := range strings.Split(value, ",") { + if c := strings.TrimSpace(coding); c != "" && !strings.EqualFold(c, "identity") { + w.encoded = true + w.failed = true + w.failErr = errSSEEncodedBody + } + } + } +} + +// writeSniffed handles a complete 2xx body whose media type is not an event +// stream. The body is read as one JSON-RPC response when it parses as one, and +// as SSE when its framing carries a result (sniffBodyShape decides). A clean +// 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) { + if hasAmbiguousResultKey(body) { + w.writeRejection(body, "rejected a 2xx body whose result key is duplicated or differs in case") + return + } + message, _ := jsonrpc2.DecodeMessage(body) + response, isResponse := message.(*jsonrpc2.Response) + if !isResponse { + // The shared classifier decides for a body that is not a clean Response. + action := classifyUnlabeledBody(body) + switch action { + case sniffRejectJSON: + w.writeRejection(body, "rejected a 2xx JSON body carrying a result that is not a single JSON-RPC response") + return + case sniffRejectNamed: + w.writeRejection(body, "dropped a 2xx body naming a result that could not be read") + return + case sniffPassThrough: + if _, err := w.ResponseWriter.Write(body); err != nil { + slog.Debug("stopped writing filtered SSE stream", "error", err) + } + return + case sniffFilterSSE, sniffFilterJSON: + // Filtered per event below. + } + if err := w.writeLines(w.processLines(parseSSELines(body))); err != nil { + slog.Debug("stopped writing filtered SSE stream", "error", err) + } + return + } + method, err := resultMethod(response.Result) + if err != nil { + slog.Warn("rejected a 2xx JSON-RPC response whose result names lists in conflict", "error", err) + // Answer with an error that carries the request id, so the client does not wait for a timeout. + // A failed write means the client has gone, so the error is not retried. + _, _ = w.ResponseWriter.Write(encodeErrorBody(response.ID)) + return + } + out := body + if method != "" { + filtered, ferr := w.newFilter(method).filterAndEncode(response) + if ferr != nil { + slog.Warn("answering a 2xx JSON-RPC response that failed to filter with an error", "error", ferr) + out = encodeErrorBody(response.ID) + } else { + out = filtered + } + } + if _, err := w.ResponseWriter.Write(out); err != nil { + slog.Debug("stopped writing filtered SSE stream", "error", err) + } +} + +// drainCompleteEvents writes every event that is complete in the buffer and +// keeps the rest. +func (w *sseStreamFilterWriter) drainCompleteEvents() error { + for { + end := w.nextEventEnd() + if end == 0 { + break + } + chunk := w.buffer[:end] + w.buffer = w.buffer[end:] + w.scanLine, w.scanFrom = 0, 0 + if err := w.writeLines(w.processLines(parseSSELines(chunk))); err != nil { + return err + } + } + if len(w.buffer) > maxSSEEventBytes { + // An unterminated event has grown past the cap. Nothing buffered is written out: + // the client gets one error for it instead. + return w.failWithEnvelope(errSSEEventTooLarge) + } + return nil +} + +// failSniffed ends a held body that outgrew maxSniffedBodyBytes. +func (w *sseStreamFilterWriter) failSniffed() error { + return w.failWithEnvelope(errSSEBodyTooLarge) +} + +// failWithEnvelope stops the stream for good. It writes one JSON-RPC error that carries +// the id read from the held bytes, when one can be read, and drops the held bytes. The +// error is written as an event when the held bytes are event-stream framed. +func (w *sseStreamFilterWriter) failWithEnvelope(cause error) error { + held := w.buffer + w.buffer = nil + w.failed = true + w.failErr = cause + slog.Warn("ending a filtered event stream with an error", "error", cause) + framed := hasDataLine(held) + payload := held + if framed { + payload = bytes.Join(eventDataValues(parseSSELines(held)), []byte("\n")) + } + id := topLevelID(payload) + if id == (jsonrpc2.ID{}) { + // An error with no id ends the client's session, so none is written. + return cause + } + body := encodeErrorBody(id) + if framed { + _ = w.writeLines(errorEventLines(body)) + _, _ = w.ResponseWriter.Write([]byte("\n")) + return cause + } + // Write errors are ignored: a failed write means the client has gone, and the + // stream has already failed with cause. + _, _ = w.ResponseWriter.Write(body) + return cause +} + +// writeLines writes each line with the terminator it was read with. +func (w *sseStreamFilterWriter) writeLines(lines []sseLine) error { + for _, l := range lines { + if _, err := w.ResponseWriter.Write(l.text); err != nil { + return err + } + if _, err := w.ResponseWriter.Write(l.term); err != nil { + return err + } + } + return nil +} + +// processLines filters each event in lines, choosing the filter from the shape of +// its result. Blank lines separate events and are kept as they are. +func (w *sseStreamFilterWriter) processLines(lines []sseLine) []sseLine { + return processSSELines(lines, w.filterEvent) +} + +// filterEvent filters one event's lines, choosing the filter from the shape of +// its result. +func (w *sseStreamFilterWriter) filterEvent(event []sseLine) []sseLine { + if len(event) == 0 { + return nil + } + dataValues, payload, loneCR := assembleSSEEvent(event) + if loneCR { + // The event's data cannot be assembled, so it is replaced whole with an error + // that carries the frame's id. With no readable id it is dropped: an id-less error + // would end the client's session. + id := frameID(event) + if id == (jsonrpc2.ID{}) { + slog.Warn("dropped an SSE event with no readable id", "error", errSSEBareCR) + return nil + } + slog.Warn("rejected an SSE event with a bare CR line break", "error", errSSEBareCR) + return errorEventLines(encodeErrorBody(id)) + } + if len(payload) == 0 { + return event + } + // A duplicated or case-variant result key is rejected before decoding: the + // client's decoder may pick a different key than this filter would, so the + // body cannot be trusted to show the same list the client sees. + if hasAmbiguousResultKey(payload) { + return failClosed(event, frameID(event), "result key is duplicated or differs in case") + } + + message, decodeErr := jsonrpc2.DecodeMessage(payload) + response, isResponse := message.(*jsonrpc2.Response) + if !isResponse { + // Fail closed with the frame's own id, so the client's pending call is answered. + // The shared handler below would answer with the empty request id of this GET. + if mayCarryResult(payload, dataValues, decodeErr) { + return failClosed(event, frameID(event), "dropped a frame carrying a result outside a clean Response") + } + // Frames that are not a clean Response and carry no result (e.g. notifications) + // pass through the shared handling unchanged. + return w.newFilter("").resolveAssembled(event, dataValues, payload) + } + + method, err := resultMethod(response.Result) + if err != nil { + return failClosed(event, response.ID, err.Error()) + } + if method == "" { + // Not a list result (e.g. a tools/call answer): pass through. + return event + } + return w.newFilter(method).resolveAssembled(event, dataValues, payload) +} + +// newFilter returns a filter for one event, sharing this stream's authorizer and +// annotation cache. method is "" for an error-only writer. +func (w *sseStreamFilterWriter) newFilter(method string) *ResponseFilteringWriter { + return NewResponseFilteringWriter(nil, w.authorizer, w.request, method, w.annotationCache, w.passThroughTools) +} + +// failClosed replaces an event with a JSON-RPC error envelope. The reason is logged +// once here at Warn, and the envelope is encoded without a second log line. id is +// the request id when the frame was a clean Response, and empty otherwise. An +// event whose reason has no id is dropped. +func failClosed(event []sseLine, id jsonrpc2.ID, reason string) []sseLine { + if id == (jsonrpc2.ID{}) { + // No request id can be read: a notification or an off-spec frame. An error with + // no id is one the go-sdk client rejects, and it ends the session. The event is + // dropped instead, since no call is waiting on it. + slog.Warn("dropped an SSE event with no readable id", "error", errors.New(reason)) + return nil + } + slog.Warn("failing closed on an SSE event", "error", errors.New(reason)) + return rebuildEventWithPayload(event, encodeErrorBody(id), true) +} + +// resultMethod returns the response filter for a result: a list method, the find_tool +// filter for a find_tool answer, or "" when neither applies. A result that names +// tools but is not a valid find_tool answer is an error, so it fails closed. A +// result with no content or structuredContent member is not a find_tool answer +// and passes through. +func resultMethod(result json.RawMessage) (string, error) { + method, err := listMethodForResult(result) + if err != nil || method != "" { + return method, err + } + if !mentionsToolsMember(result) || !hasFindToolEnvelope(result) { + return "", nil + } + callResult, err := decodeFindToolCallResult(result) + if err != nil { + return "", fmt.Errorf("result names tools but is not a valid find_tool answer: %w", err) + } + if callResult.structuredContent == nil && len(callResult.outputs) == 0 { + return "", nil + } + return optimizerdec.FindToolName, nil +} + +// maxToolsSniffDepth bounds how many times a string is re-parsed as JSON while +// looking for a tools member. Each level is one encoding of the find_tool text. +const maxToolsSniffDepth = 32 + +// mentionsToolsMember reports whether a result names tools anywhere a client could +// read it: as an object key, or inside a string that is itself JSON, at any depth. +// It decodes before matching, so an escaped spelling such as "tools" is seen. +func mentionsToolsMember(result json.RawMessage) bool { + var v any + if json.Unmarshal(result, &v) != nil { + return false + } + return mentionsToolsValue(v, 0) +} + +func mentionsToolsValue(v any, depth int) bool { + switch t := v.(type) { + case map[string]any: + for k, val := range t { + // A tools value fails closed unless it is a list naming no tool, such as [] + // or ["hammer"]. A string or object holding tools (including a string of + // JSON) counts. + // listNamesNoTool defines which list shapes pass. + if (strings.EqualFold(k, "tools") && !listNamesNoTool(val)) || mentionsToolsValue(val, depth) { + return true + } + } + case []any: + for _, val := range t { + if mentionsToolsValue(val, depth) { + return true + } + } + case string: + // Plain text that merely mentions tools (such as "Found 3 tools") names no member, + // so only a JSON-encoded tools key in the text counts, checked below. + trimmed := strings.TrimSpace(t) + if depth < maxToolsSniffDepth && (strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[")) { + var inner any + if json.Unmarshal([]byte(trimmed), &inner) == nil { + return mentionsToolsValue(inner, depth+1) + } + } + } + return false +} + +// hasFindToolEnvelope reports whether a result has a content or structuredContent +// member, the two members a find_tool answer carries. A result with neither, such as an +// initialize answer that only mentions tools in its capabilities, is not a find_tool answer. +func hasFindToolEnvelope(result json.RawMessage) bool { + members, err := mcpparser.DecodeJSONObjectMembers(result) + if err != nil { + return false + } + for _, m := range members { + if strings.EqualFold(m.Name, "content") || strings.EqualFold(m.Name, "structuredContent") { + return true + } + } + return false +} + +// listMethodForResult returns the list method whose filter applies to a result. +// It returns "" when the result carries no list member. A result with more +// than one list member is an error: filtering one member would leave the +// others visible. A member whose name differs from a list name only in case is +// also an error, because a client that matches keys case-insensitively would +// read it as that list. +func listMethodForResult(result json.RawMessage) (string, error) { + var members map[string]json.RawMessage + if err := json.Unmarshal(result, &members); err != nil { + return "", nil + } + var method string + var matches int + for member := range members { + for name := range listMembers { + if member != name && strings.EqualFold(member, name) { + return "", errors.New("result carried a list member name that differs only in case") + } + } + if m, ok := listMembers[member]; ok { + method = m + matches++ + } + } + if matches > 1 { + return "", errors.New("result carried more than one list member") + } + return method, nil +} + +// nextEventEnd returns the length of the prefix of the buffer that ends with the +// blank line closing its first complete event, or 0 if no event is complete yet. +// It resumes where the previous call stopped, so each byte is searched once even +// when an event grows across many writes. drainCompleteEvents resets the scan +// after it consumes an event. +func (w *sseStreamFilterWriter) nextEventEnd() int { + for { + idx := bytes.IndexByte(w.buffer[w.scanFrom:], '\n') + if idx == -1 { + w.scanFrom = len(w.buffer) + return 0 + } + nl := w.scanFrom + idx + line := w.buffer[w.scanLine:nl] + w.scanFrom = nl + 1 + w.scanLine = nl + 1 + if len(bytes.TrimRight(line, "\r")) == 0 { + return nl + 1 + } + } +} + +// hasAmbiguousResultKey reports whether a JSON object payload has a top-level key +// that is "result" in some other spelling, or "result" more than once. Go's decoder +// matches keys case-insensitively and keeps the last duplicate, while a client may +// read the exact "result" key. Such a payload cannot be filtered reliably, so the +// caller fails closed. +func hasAmbiguousResultKey(payload []byte) bool { + dec := json.NewDecoder(bytes.NewReader(payload)) + if tok, err := dec.Token(); err != nil || tok != json.Delim('{') { + return false + } + resultKeys := 0 + for dec.More() { + // Malformed JSON is not a result a client can read, so it is not ambiguous here. + tok, err := dec.Token() + if err != nil { + return false + } + key, ok := tok.(string) + if !ok { + return false + } + if strings.EqualFold(key, "result") { + if key != "result" { + return true + } + resultKeys++ + if resultKeys > 1 { + return true + } + } + var skip json.RawMessage + if err := dec.Decode(&skip); err != nil { + return false + } + } + return false +} + +// frameID returns the JSON-RPC id of an event's payload, read the way a client +// reads it (CR as a line break too), or an empty id when none can be read. +func frameID(event []sseLine) jsonrpc2.ID { + var raw []byte + for _, l := range event { + raw = append(raw, l.text...) + raw = append(raw, l.term...) + } + view := bytes.ReplaceAll(bytes.ReplaceAll(raw, []byte("\r\n"), []byte("\n")), []byte("\r"), []byte("\n")) + payload := bytes.Join(eventDataValues(parseSSELines(view)), []byte("\n")) + message, err := jsonrpc2.DecodeMessage(payload) + if err != nil { + return topLevelID(payload) + } + switch m := message.(type) { + case *jsonrpc2.Response: + return m.ID + case *jsonrpc2.Request: + return m.ID + } + return jsonrpc2.ID{} +} + +// bodyID reads the id a client reads from a JSON-RPC body: the decoded message's id, +// the way encoding/json matches keys, so a duplicate or case-variant "id" resolves to the +// same value the client sees. It falls back to topLevelID when the body cannot be decoded. +func bodyID(body []byte) jsonrpc2.ID { + if message, err := jsonrpc2.DecodeMessage(body); err == nil { + switch m := message.(type) { + case *jsonrpc2.Response: + return m.ID + case *jsonrpc2.Request: + return m.ID + } + } + return topLevelID(body) +} + +// writeRejection answers a rejected 2xx body with an error that carries its id. When no +// id can be read, nothing is written: an error with no id ends the go-sdk client's session. +func (w *sseStreamFilterWriter) writeRejection(body []byte, reason string) { + id := bodyID(body) + if id == (jsonrpc2.ID{}) { + // One log line per rejection: the reason, and that no id could be read. + slog.Warn(reason, "error", errSSEUnrecognizedMediaType, "dropped", "no readable id") + return + } + slog.Warn(reason, "error", errSSEUnrecognizedMediaType) + // A failed write means the client has gone; the rejection is already logged. + _, _ = w.ResponseWriter.Write(encodeErrorBody(id)) +} + +// listNamesNoTool reports whether v is a list in which no entry is an object with a +// name key, compared case-insensitively (encoding/json matches keys this way, so a +// client reading "Name" sees a tool). Only such a list cannot leak a tool, so any +// other tools value, including a string, must fail closed. +func listNamesNoTool(v any) bool { + list, ok := v.([]any) + if !ok { + return false + } + for _, item := range list { + obj, ok := item.(map[string]any) + if !ok { + continue + } + for k := range obj { + if strings.EqualFold(k, "name") { + return false + } + } + } + return true +} diff --git a/pkg/authz/sse_stream_filter_test.go b/pkg/authz/sse_stream_filter_test.go new file mode 100644 index 0000000000..47143aec07 --- /dev/null +++ b/pkg/authz/sse_stream_filter_test.go @@ -0,0 +1,1004 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authz + +import ( + "bufio" + "encoding/json" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive-core/mcpcompat/mcp" + mcpparser "github.com/stacklok/toolhive/pkg/mcp" +) + +// sseRequest returns a GET that asks for an event stream, as the MCP stream GET does. +func sseRequest() *http.Request { + r := httptest.NewRequest(http.MethodGet, "/sse", nil) + r.Header.Set("Accept", "text/event-stream") + return r +} + +// runSSEStream serves a GET event stream through the authz middleware. The +// handler writes each chunk in order, so a test can split an event across writes. +func runSSEStream(t *testing.T, authorizer *mockAuthorizer, contentType string, chunks ...string) *httptest.ResponseRecorder { + t.Helper() + return runSSEStreamWithStatus(t, authorizer, http.StatusOK, contentType, chunks...) +} + +func runSSEStreamWithStatus( + t *testing.T, authorizer *mockAuthorizer, status int, contentType string, chunks ...string, +) *httptest.ResponseRecorder { + t.Helper() + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", contentType) + w.WriteHeader(status) + for _, c := range chunks { + _, _ = io.WriteString(w, c) + } + }) + handler := Middleware(authorizer, next, nil) + req := sseRequest() + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + return rr +} + +// TestSSEStreamWriterUnwrapsToUnderlyingWriter pins Unwrap, which lets +// http.ResponseController reach the connection's deadlines through this writer. +func TestSSEStreamWriterUnwrapsToUnderlyingWriter(t *testing.T) { + t.Parallel() + + underlying := httptest.NewRecorder() + w := newSSEStreamFilterWriter(underlying, nil, sseRequest(), nil, nil) + assert.Same(t, underlying, w.Unwrap()) +} + +// TestSSEStreamFilterRejectionIDMatchesClientDecode pins the id on a rejected 2xx body +// with a duplicate "id" key. encoding/json keeps the last duplicate, so the client +// reads id 2 and the rejection must answer id 2, not the first id. +func TestSSEStreamFilterRejectionIDMatchesClientDecode(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + body := `{"jsonrpc":"2.0","id":1,"ID":2,"result":{"tools":[{"name":"secret"}]},"Result":{"tools":[{"name":"secret"}]}}` + rr := runSSEStream(t, authorizer, "application/json", body) + + assert.NotContains(t, rr.Body.String(), "secret") + assert.Contains(t, rr.Body.String(), `"id":2`) + assert.NotContains(t, rr.Body.String(), `"id":1`) +} +func sseStreamEvent(data string) string { + return "event: message\ndata: " + data + "\n\n" +} + +func TestSSEStreamFiltersEachListShape(t *testing.T) { + t.Parallel() + + testCases := []struct { + name string + result string + }{ + {name: "tools", result: `{"tools":[{"name":"weather","inputSchema":{"type":"object"}},{"name":"secret","inputSchema":{"type":"object"}}]}`}, + {name: "prompts", result: `{"prompts":[{"name":"weather"},{"name":"secret"}]}`}, + {name: "resources", result: `{"resources":[{"uri":"weather","name":"weather"},{"uri":"secret","name":"secret"}]}`}, + {name: "resourceTemplates", result: `{"resourceTemplates":[{"uriTemplate":"weather","name":"weather"},{"uriTemplate":"secret","name":"secret"}]}`}, + {name: "skills", result: `{"skills":[{"uri":"weather","name":"weather"},{"uri":"secret","name":"secret"}]}`}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "weather": {authorized: true}, + "secret": {authorized: false}, + }} + body := sseStreamEvent(`{"jsonrpc":"2.0","id":1,"result":` + tc.result + `}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "an unauthorized entry must be removed from the stream") + assert.Contains(t, rr.Body.String(), "weather") + }) + } +} + +func TestSSEStreamPassesNonListResultsUnchanged(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + body := sseStreamEvent(`{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"ok"}],"isError":false}}`) + + sseStreamEvent(`{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info"}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.Equal(t, body, rr.Body.String()) +} + +func TestSSEStreamHoldsPartialEventUntilComplete(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "weather": {authorized: true}, + "secret": {authorized: false}, + }} + event := sseStreamEvent(`{"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"weather","inputSchema":{"type":"object"}},{"name":"secret","inputSchema":{"type":"object"}}]}}`) + half := len(event) / 2 + rr := runSSEStream(t, authorizer, "text/event-stream", event[:half], event[half:]) + + assert.NotContains(t, rr.Body.String(), "secret") + assert.Contains(t, rr.Body.String(), "weather") +} + +func TestSSEStreamFailsClosedOnSmuggledResult(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // A request frame (has a method) that also carries a tools result. + body := sseStreamEvent(`{"jsonrpc":"2.0","id":3,"method":"tools/list","result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a smuggled list must not reach the client") + assert.Contains(t, rr.Body.String(), `"error"`) + assert.Contains(t, rr.Body.String(), `"id":3`, "the fail-closed error must answer the frame's own id") +} + +func TestSSEStreamFailsClosedOnResultNestedPastDecoderDepth(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // Nested past encoding/json's depth cap, so the frame does not decode and carriesResult + // cannot see the result. It must still fail closed, not pass through. + deep := strings.Repeat("[", 10001) + strings.Repeat("]", 10001) + body := sseStreamEvent(`{"jsonrpc":"2.0","id":42,"result":{"tools":[{"name":"secret","inputSchema":` + deep + `}]}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a result nested past the depth cap must not leak") + assert.Contains(t, rr.Body.String(), `"error"`) + assert.Contains(t, rr.Body.String(), `"id":42`, "the id is read from the frame even though it cannot be decoded") +} + +func TestSSEStreamFailsClosedOnResultBehindCRBoundary(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // The first event is junk. A CR-honouring client ends it at the CR CR, then reads the + // result in the second event, which the LF-only split still holds in one event. + body := "data: garbage\r\rdata: {\"jsonrpc\":\"2.0\",\"id\":43,\rdata: \"result\":{\"tools\":[{\"name\":\"secret\",\"inputSchema\":{\"type\":\"object\"}}]}}\n\n" + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a result behind a CR boundary must not leak") + assert.Contains(t, rr.Body.String(), `"error"`) +} + +func TestSSEStreamFailsClosedOnAmbiguousResult(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "weather": {authorized: true}, + "secret": {authorized: false}, + }} + // Two list members in one result: filtering one would leave the other visible. + body := sseStreamEvent(`{"jsonrpc":"2.0","id":4,"result":{"tools":[{"name":"weather","inputSchema":{"type":"object"}}],"prompts":[{"name":"secret"}]}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret") + assert.Contains(t, rr.Body.String(), `"error"`) +} + +func TestSSEStreamNonEventStreamBodies(t *testing.T) { + t.Parallel() + + const toolsList = `{"jsonrpc":"2.0","id":5,"result":{"tools":[{"name":"weather","inputSchema":{"type":"object"}},{"name":"secret","inputSchema":{"type":"object"}}]}}` + const plainResult = `{"jsonrpc":"2.0","id":6,"result":{"content":[{"type":"text","text":"ok"}]}}` + testCases := []struct { + name string + status int + body string + wantContains string + wantAbsent string + wantExact string + }{ + // A 2xx JSON-RPC list answer is sniffed and filtered, never sent raw. + {name: "2xx sniffed list is filtered", status: http.StatusOK, body: toolsList, wantContains: "weather", wantAbsent: "secret"}, + // A 2xx JSON-RPC answer with no list member is sent unchanged. + {name: "2xx non-list result passes through", status: http.StatusOK, body: plainResult, wantExact: plainResult}, + // A 2xx body with no JSON-RPC result passes through, as the buffered path does. + {name: "2xx body with no result passes through", status: http.StatusOK, body: "tools: secret", wantExact: "tools: secret"}, + // An error body is passed through unchanged. + {name: "non-2xx other media type passes through", status: http.StatusNotFound, body: toolsList, wantExact: toolsList}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + "weather": {authorized: true}, + }} + rr := runSSEStreamWithStatus(t, authorizer, tc.status, "application/json", tc.body) + + require.Equal(t, tc.status, rr.Code) + if tc.wantExact != "" { + assert.Equal(t, tc.wantExact, rr.Body.String()) + } + if tc.wantContains != "" { + assert.Contains(t, rr.Body.String(), tc.wantContains) + } + if tc.wantAbsent != "" { + assert.NotContains(t, rr.Body.String(), tc.wantAbsent) + } + }) + } +} + +func TestSSEStreamFailsClosedOnCaseAliasMember(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // "Tools" is not the canonical "tools", so the filter cannot tell it apart from a + // list a case-insensitive client would read. + body := sseStreamEvent(`{"jsonrpc":"2.0","id":11,"result":{"Tools":[{"name":"secret","inputSchema":{"type":"object"}}]}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a case alias of a list member must not reach the client") + assert.Contains(t, rr.Body.String(), `"error"`) +} + +func TestSSEStreamErrorCarriesRequestID(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // Two list members: the envelope must echo the request id so the client's + // pending call is answered instead of hanging until its timeout. + body := sseStreamEvent(`{"jsonrpc":"2.0","id":9,"result":{"tools":[],"prompts":[]}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.Contains(t, rr.Body.String(), `"id":9`, "the fail-closed error must carry the request id") +} + +func TestSSEStreamStripsLeadingBOM(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // A byte order mark in front of the first event must not hide its data field + // from the filter. + body := "\uFEFF" + sseStreamEvent(`{"jsonrpc":"2.0","id":12,"result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a list behind a leading BOM must still be filtered") + assert.Contains(t, rr.Body.String(), `"id":12`, "the filtered list must still be sent") +} + +func TestSSEStreamFailsClosedOnUnterminatedOversizedEvent(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // An event that never ends is buffered until the size limit. Its held bytes are not + // written. This event has no readable id, so no error is written either: an + // id-less error would end the client's session. + huge := "data: " + strings.Repeat("a", maxSSEEventBytes+1024) + rr := runSSEStream(t, authorizer, "text/event-stream", huge) + + assert.NotContains(t, rr.Body.String(), "aaaa", "held bytes must not be written through") + assert.NotContains(t, rr.Body.String(), `"error"`, "an error with no id must not be written") + assert.Less(t, rr.Body.Len(), 1024) +} +func TestSSEStreamFlushBeforeWriteSetsNoStore(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // The handler flushes before writing anything. The flush commits the headers, + // so the uncacheable marking must already be in place. + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.(http.Flusher).Flush() + }) + handler := Middleware(authorizer, next, nil) + req := sseRequest() + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + assert.Equal(t, "private, no-store", rr.Header().Get("Cache-Control")) +} + +func TestSSEStreamDropsMalformedThenResult(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // The first data line is undecodable, so only a per-value probe finds the result on the second. + body := "data: {bad\ndata: " + + `{"jsonrpc":"2.0","id":8,"result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]}}` + + "\n\n" + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a result split across data lines must not reach the client") + assert.NotContains(t, rr.Body.String(), `"error"`, "an event with no readable id is dropped, not answered with an id-less error") +} + +func TestSSEStreamFiltersCRLFFraming(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "weather": {authorized: true}, + "secret": {authorized: false}, + }} + body := "event: message\r\ndata: " + + `{"jsonrpc":"2.0","id":9,"result":{"tools":[{"name":"weather","inputSchema":{"type":"object"}},{"name":"secret","inputSchema":{"type":"object"}}]}}` + + "\r\n\r\n" + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "CRLF framing must not hide a denied tool") + assert.Contains(t, rr.Body.String(), "weather") +} + +func TestSSEStreamPassesKeepAliveAndEndpointEvents(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + body := ": keep-alive\n\nevent: endpoint\ndata: /messages?session=1\n\n" + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.Equal(t, body, rr.Body.String(), "comments and endpoint events are not list answers") +} + +func TestSSEStreamFlushBetweenPartialChunks(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "weather": {authorized: true}, + "secret": {authorized: false}, + }} + // The handler flushes while an event is still incomplete. The flush must not + // write the partial event, and the completed event must still be filtered. + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, "data: "+`{"jsonrpc":"2.0","id":10,"result":{"tools":[{"name":"weather","inputSchema":{"type":"object"}},`) + w.(http.Flusher).Flush() + _, _ = io.WriteString(w, `{"name":"secret","inputSchema":{"type":"object"}}]}}`+"\n\n") + w.(http.Flusher).Flush() + }) + handler := Middleware(authorizer, next, nil) + req := sseRequest() + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + assert.NotContains(t, rr.Body.String(), "secret", "a list split across a flush must still be filtered") + assert.Contains(t, rr.Body.String(), "weather") +} + +func TestSSEStreamFlushesCompleteEventWhileHandlerRuns(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "weather": {authorized: true}, + "secret": {authorized: false}, + }} + // ServeHTTP runs the handler on this goroutine, so the outer recorder can be + // read inside the handler. A complete event must already be on the wire after a flush. + rr := httptest.NewRecorder() + var midStream string + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, sseStreamEvent(`{"jsonrpc":"2.0","id":11,"result":{"tools":[{"name":"weather","inputSchema":{"type":"object"}},{"name":"secret","inputSchema":{"type":"object"}}]}}`)) + w.(http.Flusher).Flush() + midStream = rr.Body.String() + }) + Middleware(authorizer, next, nil).ServeHTTP(rr, sseRequest()) + + require.NotEmpty(t, midStream, "a complete event must be written before the handler returns") + assert.Contains(t, midStream, "weather") + assert.NotContains(t, midStream, "secret", "the event flushed mid-stream must already be filtered") +} + +func TestSSEStreamStripsBOMSplitAcrossWrites(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // The BOM arrives one byte at a time with flushes between, so the first write + // alone does not hold the whole BOM. + // No event: line, so the BOM sits directly in front of the data field. + event := "data: " + `{"jsonrpc":"2.0","id":13,"result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]}}` + "\n\n" + bom := string(mcpparser.UTF8BOM) + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + for i := range len(bom) { + _, _ = io.WriteString(w, bom[i:i+1]) + w.(http.Flusher).Flush() + } + _, _ = io.WriteString(w, event) + }) + handler := Middleware(authorizer, next, nil) + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, sseRequest()) + + assert.NotContains(t, rr.Body.String(), "secret", "a BOM split across writes must not hide the list") + assert.Contains(t, rr.Body.String(), `"id":13`, "the filtered list must still be sent") +} + +func TestSSEStreamSniffsSSEFramedBodyWithWrongContentType(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "weather": {authorized: true}, + "secret": {authorized: false}, + }} + // SSE framing under a non-event-stream type: the body is read as SSE, so the + // denied tool is removed rather than dropping the whole body. + body := sseStreamEvent(`{"jsonrpc":"2.0","id":14,"result":{"tools":[{"name":"weather","inputSchema":{"type":"object"}},{"name":"secret","inputSchema":{"type":"object"}}]}}`) + rr := runSSEStream(t, authorizer, "application/octet-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret") + assert.Contains(t, rr.Body.String(), "weather") +} + +func TestSSEStreamInformationalStatusDoesNotDecideMode(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // A 103 before the final 200 must not latch the mode, or the list passes unfiltered. + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusEarlyHints) + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, sseStreamEvent(`{"jsonrpc":"2.0","id":15,"result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]}}`)) + }) + rr := httptest.NewRecorder() + Middleware(authorizer, next, nil).ServeHTTP(rr, sseRequest()) + + assert.NotContains(t, rr.Body.String(), "secret", "a 1xx response must not stop the list from being filtered") +} + +func TestSSEStreamFiltersCompleteEventOverTheCap(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // A complete list event larger than the cap is filtered like any other, and the + // stream carries on past it. Only an unterminated event is cut off at the cap. + pad := strings.Repeat("a", maxSSEEventBytes+1024) + list := sseStreamEvent(`{"jsonrpc":"2.0","id":40,"result":{"tools":[{"name":"secret","description":"` + pad + + `","inputSchema":{"type":"object"}}]}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", list, ": after\n\n") + + assert.NotContains(t, rr.Body.String(), "secret", "the oversized list must be filtered") + assert.Contains(t, rr.Body.String(), ": after", "the stream must continue past the oversized event") +} + +func TestSSEStreamAllowsManySmallEventsInOneWrite(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // Many small complete events in one write total more than the cap, but each is under + // it. The stream must pass through, since the cap is per event. + event := ": " + strings.Repeat("x", 10*1024) + "\n\n" + body := strings.Repeat(event, 200) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.Equal(t, body, rr.Body.String()) +} + +func TestSSEStreamStripsContentLengthOnImplicitOK(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // The handler sets Content-Length and writes without calling WriteHeader, so the + // 200 is implicit. Filtering changes the size, so the header must still go. + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Content-Length", "9999") + _, _ = io.WriteString(w, ": keep-alive\n\n") + }) + rr := httptest.NewRecorder() + Middleware(authorizer, next, nil).ServeHTTP(rr, sseRequest()) + + assert.Empty(t, rr.Header().Get("Content-Length"), "a filtered stream must not keep Content-Length") +} + +func TestSSEStreamFailsClosedOnAmbiguousResultKey(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // Go reads "Result" last and sees no list, while a client reads the exact "result" + // key and sees the denied tool. The event must fail closed. + body := sseStreamEvent(`{"jsonrpc":"2.0","id":17,"result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]},"Result":{"ok":true}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a case-variant result key must not leak the list") + assert.Contains(t, rr.Body.String(), `"id":17`, "the fail-closed error must answer the request") +} + +func TestSSEStreamFailsClosedOnDuplicateResultKey(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + body := sseStreamEvent(`{"jsonrpc":"2.0","id":18,"result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]},"result":{"ok":true}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a duplicated result key must not leak the list") + assert.Contains(t, rr.Body.String(), `"id":18`, "the fail-closed error must answer the request") +} + +func TestSSEStreamRefusesContentEncodedBody(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Content-Encoding", "gzip") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, sseStreamEvent(`{"jsonrpc":"2.0","id":19,"result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]}}`)) + }) + rr := httptest.NewRecorder() + Middleware(authorizer, next, nil).ServeHTTP(rr, sseRequest()) + + assert.Equal(t, http.StatusBadGateway, rr.Code, "a content-coded list stream cannot be filtered and must be refused") + assert.NotContains(t, rr.Body.String(), "secret") +} + +func TestSSEStreamSniffedAmbiguousListAnswersWithError(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // Two list members in one result are ambiguous. The client must get an error that + // carries the request id, not an empty 200 it waits on. + body := `{"jsonrpc":"2.0","id":16,"result":{"tools":[],"prompts":[]}}` + rr := runSSEStream(t, authorizer, "text/plain", body) + + assert.Contains(t, rr.Body.String(), `"id":16`, "the error must answer the request") + assert.Contains(t, rr.Body.String(), `"error"`) +} + +func TestSSEStreamSniffedRejectionsAnswerWithRequestID(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + body string + }{ + { + name: "ambiguous result key", + body: `{"jsonrpc":"2.0","id":44,"Result":{"tools":[]},"result":{"tools":[]}}`, + }, + { + name: "result that is not a clean response", + body: `{"jsonrpc":"2.0","id":45,"result":{"tools":[]},"error":{"code":-1,"message":"x"}}`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + rr := runSSEStream(t, authorizer, "text/plain", tt.body) + + // A silent drop leaves the client waiting for its pending request. The + // rejection must be answered with an error that carries the id. + assert.Contains(t, rr.Body.String(), `"error"`, "the rejection must be answered") + assert.Contains(t, rr.Body.String(), `"id":`, "the answer must carry the request id") + }) + } +} + +func TestListMembersMapToListFilters(t *testing.T) { + t.Parallel() + + // Pins listMembers to the list methods of responseFilterForMethod in both + // directions. Every list member maps to a list method, and every list method + // has a member. The expected table is the one place a new list kind must be added. + want := map[string]string{ + "tools": string(mcp.MethodToolsList), + "prompts": string(mcp.MethodPromptsList), + "resources": string(mcp.MethodResourcesList), + "resourceTemplates": string(mcp.MethodResourcesTemplatesList), + "skills": "skills/list", + } + assert.Equal(t, want, listMembers, "listMembers must match the expected list kinds") + + listMethods := []string{ + string(mcp.MethodToolsList), + string(mcp.MethodPromptsList), + string(mcp.MethodResourcesList), + string(mcp.MethodResourcesTemplatesList), + "skills/list", + } + covered := make(map[string]bool, len(listMethods)) + for member, method := range listMembers { + assert.NotEqual(t, responseFilterNone, responseFilterForMethod(method), + "list member %q maps to %q, which has no filter", member, method) + covered[method] = true + } + for _, method := range listMethods { + assert.True(t, covered[method], "list method %q has no list member in listMembers", method) + assert.NotEqual(t, responseFilterNone, responseFilterForMethod(method), + "list method %q has no response filter", method) + } +} + +func TestSSEStreamFailsClosedOnLoneCRLineBreak(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // A spec client splits on the lone CR and reads the data line. The LF-only split + // sees one comment line, so the event must fail closed. + body := ": x\rdata: " + + `{"jsonrpc":"2.0","id":20,"result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]}}` + + "\n\n" + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a lone CR must not hide a list from the filter") + assert.Contains(t, rr.Body.String(), `"error"`) +} + +// TestSSEStreamDropsLoneCREventWithNoID checks that a lone CR event with no readable +// id is dropped rather than answered with an id-less error, which would end the session. +func TestSSEStreamDropsLoneCREventWithNoID(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + body := "data: {\"result\":{\"tools\":[{\"name\":\"secret\"}]}}\r: x\n\n" + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret") + assert.NotContains(t, rr.Body.String(), `"error"`, "an error with no id must not be written") +} + +func TestSSEStreamFiltersResultSplitAcrossDataLines(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // Each data line alone is not a result, but a client joins them into one. The + // event is filtered, not dropped: its id is still answered. + body := "data: {\"jsonrpc\":\"2.0\",\"id\":21,\ndata: \"result\":{\"tools\":[{\"name\":\"secret\",\"inputSchema\":{\"type\":\"object\"}}]}}\n\n" + rr := runSSEStream(t, authorizer, "application/octet-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret") + assert.Contains(t, rr.Body.String(), `"id":21`) +} + +func TestSSEStreamPassesResultFreeBodyThrough(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // A non-MCP 2xx body with no result is not a list answer, so it passes through. + body := `{"status":"ok"}` + rr := runSSEStream(t, authorizer, "application/json", body) + + assert.Equal(t, body, rr.Body.String()) +} + +// hijackRecorder is a recorder whose underlying writer does support Hijack. If the +// filter let http.ResponseController unwrap to it, the hijack would succeed. +type hijackRecorder struct { + *httptest.ResponseRecorder + hijacked bool +} + +func (h *hijackRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { + h.hijacked = true + return nil, nil, nil +} + +func TestSSEStreamRefusesHijackOnFilteredStream(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // A takeover of a filtered stream must be refused before the underlying writer is + // reached, so no backend bytes can skip the filter. + var hijackErr error + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _, hijackErr = http.NewResponseController(w).Hijack() + }) + hr := &hijackRecorder{ResponseRecorder: httptest.NewRecorder()} + Middleware(authorizer, next, nil).ServeHTTP(hr, sseRequest()) + + require.ErrorIs(t, hijackErr, http.ErrNotSupported) + assert.False(t, hr.hijacked, "the underlying writer must not be hijacked") +} + +func TestSSEStreamAllowsHijackOfPassThroughResponse(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // A 101 upgrade is not a filtered body, so its takeover reaches the underlying writer. + var hijackErr error + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusSwitchingProtocols) + _, _, hijackErr = http.NewResponseController(w).Hijack() + }) + hr := &hijackRecorder{ResponseRecorder: httptest.NewRecorder()} + Middleware(authorizer, next, nil).ServeHTTP(hr, sseRequest()) + + require.NoError(t, hijackErr) + assert.True(t, hr.hijacked, "a pass-through upgrade must reach the underlying writer") +} + +func TestSSEStreamFailsClosedOnLoneCRSplitAcrossDataLines(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // Read with CR line breaks, the two data lines join into one result. The LF-only + // split sees a comment and no data, so the event must fail closed. + body := ": c\rdata: {\"jsonrpc\":\"2.0\",\"id\":30,\rdata: \"result\":{\"tools\":[{\"name\":\"secret\",\"inputSchema\":{\"type\":\"object\"}}]}}\n\n" + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a result split across CR-separated data lines must not leak") + assert.Contains(t, rr.Body.String(), `"error"`, "the event must be answered with a fail-closed error") +} + +func TestSSEStreamSniffedResultAfterUndecodableEvent(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // The first event is not JSON. The split result in the second event must still be filtered. + body := "data: x\n\n" + + "data: {\"jsonrpc\":\"2.0\",\"id\":31,\n" + + "data: \"result\":{\"tools\":[{\"name\":\"secret\",\"inputSchema\":{\"type\":\"object\"}}]}}\n\n" + rr := runSSEStream(t, authorizer, "application/octet-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a result after an undecodable event must still be filtered") +} + +func TestSSEStreamRefusesRepeatedContentEncodingHeader(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Add("Content-Encoding", "identity") + w.Header().Add("Content-Encoding", "gzip") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, sseStreamEvent(`{"jsonrpc":"2.0","id":32,"result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]}}`)) + }) + rr := httptest.NewRecorder() + Middleware(authorizer, next, nil).ServeHTTP(rr, sseRequest()) + + assert.Equal(t, http.StatusBadGateway, rr.Code, "a gzip coding in a second header line must be refused") + assert.NotContains(t, rr.Body.String(), "secret") +} + +func TestSSEStreamRequestDropsAcceptEncoding(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // The backend must not be asked for a coded body, which the filter cannot parse. + var got string + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got = r.Header.Get("Accept-Encoding") + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + }) + req := sseRequest() + req.Header.Set("Accept-Encoding", "gzip") + Middleware(authorizer, next, nil).ServeHTTP(httptest.NewRecorder(), req) + + assert.Empty(t, got, "Accept-Encoding must be removed before the backend sees the request") +} + +func TestSSEStreamFiltersFindToolAnswer(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "weather": {authorized: true}, + "secret": {authorized: false}, + }} + // A find_tool answer comes back on the stream when the call was made over the POST + // channel. Its shape alone must select the find_tool filter. + const output = `{"tools":[` + + `{"name":"weather","description":"Get weather","annotations":{"readOnlyHint":true}},` + + `{"name":"secret","description":"restricted","annotations":{"readOnlyHint":true}}],` + + `"token_metrics":{"baseline_tokens":20,"returned_tokens":10,"savings_percent":50}}` + escaped, err := json.Marshal(output) + require.NoError(t, err) + result := `{"content":[{"type":"text","text":` + string(escaped) + `}],"structuredContent":` + output + `}` + rr := runSSEStream(t, authorizer, "text/event-stream", sseStreamEvent(`{"jsonrpc":"2.0","id":61,"result":`+result+`}`)) + + assert.NotContains(t, rr.Body.String(), "secret", "an unauthorized find_tool entry must be removed") + assert.Contains(t, rr.Body.String(), "weather") + assert.Contains(t, rr.Body.String(), `"id":61`) +} + +func TestSSEStreamFiltersFindToolAnswerWithEscapedToolsKey(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // The text carries the tools key with a JSON escape, so the raw bytes never spell + // "tools". A client that decodes the text still reads the key as tools. + const output = `{"tools":[{"name":"secret","description":"restricted","annotations":{"readOnlyHint":true}}]}` + escaped, err := json.Marshal(output) + require.NoError(t, err) + result := `{"content":[{"type":"text","text":` + string(escaped) + `}]}` + rr := runSSEStream(t, authorizer, "text/event-stream", sseStreamEvent(`{"jsonrpc":"2.0","id":62,"result":`+result+`}`)) + + assert.NotContains(t, rr.Body.String(), "secret", "an escaped tools key must not bypass the find_tool filter") + assert.Contains(t, rr.Body.String(), `"id":62`) +} + +func TestSSEStreamFailsClosedOnDeepResultBehindLoneCR(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // A lone CR splits the event into two pieces for a CR-honouring client. The second + // piece nests its result past encoding/json's depth cap, so only per-piece checks see it. + deep := strings.Repeat("[", 10001) + strings.Repeat("]", 10001) + payload := `{"jsonrpc":"2.0","id":63,"result":{"tools":[{"name":"secret","inputSchema":{"x":` + deep + `}}]}}` + rr := runSSEStream(t, authorizer, "text/event-stream", "data: x\r\rdata: "+payload+"\n\n") + + assert.NotContains(t, rr.Body.String(), "secret", "a deep result behind a lone CR must not pass through") +} + +func TestSSEStreamPassesPlainToolsCallAnswerUnchanged(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // A tools/call answer whose text merely mentions tools is not a find_tool answer. + // It must pass through, not fail closed with an error. + event := `{"jsonrpc":"2.0","id":7,"result":{"content":[{"type":"text","text":"Found 3 tools"}],"structuredContent":{"count":3}}}` + rr := runSSEStream(t, authorizer, "text/event-stream", sseStreamEvent(event)) + + assert.Contains(t, rr.Body.String(), `"count":3`, "a plain tools/call answer must pass through unchanged") + assert.NotContains(t, rr.Body.String(), `"error"`, "a plain tools/call answer must not fail closed") +} + +func TestSSEStreamFailsClosedOnMalformedFindToolAnswer(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // Names tools but is not a valid find_tool answer: it must fail closed, not pass through. + result := `{"content":[],"structuredContent":{"tools":"secret"}}` + rr := runSSEStream(t, authorizer, "text/event-stream", sseStreamEvent(`{"jsonrpc":"2.0","id":62,"result":`+result+`}`)) + + assert.NotContains(t, rr.Body.String(), "secret") + assert.Contains(t, rr.Body.String(), `"id":62`) + assert.Contains(t, rr.Body.String(), `"error"`) +} + +func TestSSEStreamFailsClosedOnToolsStringHoldingJSONList(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // The tools value is a string that holds a named tool list as JSON, so it must fail closed. + result := `{"content":[],"structuredContent":{"tools":"[{\"name\":\"secret\"}]"}}` + rr := runSSEStream(t, authorizer, "text/event-stream", sseStreamEvent(`{"jsonrpc":"2.0","id":63,"result":`+result+`}`)) + + assert.NotContains(t, rr.Body.String(), "secret") + assert.Contains(t, rr.Body.String(), `"id":63`) +} + +func TestSSEStreamAnswersOversizedHeldBodyWithID(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // A held 2xx body past the cap ends the stream with one error that carries its id. + pad := strings.Repeat("a", maxSniffedBodyBytes+1024) + body := `{"jsonrpc":"2.0","id":50,"result":{"x":"` + pad + `"}}` + rr := runSSEStream(t, authorizer, "application/json", body) + + assert.Contains(t, rr.Body.String(), `"id":50`, "the error must answer the request") + assert.Contains(t, rr.Body.String(), `"error"`) + assert.Less(t, rr.Body.Len(), 1024, "nothing past the error may be written") +} + +func TestSSEStreamFailsClosedOnEscapedResultKeyPastDepthCap(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + // The result key is spelled with a JSON escape and a sibling nests past the depth cap, + // so the frame does not decode. The key must still be recognised. + deep := strings.Repeat("[", 10001) + strings.Repeat("]", 10001) + body := sseStreamEvent(`{"jsonrpc":"2.0","id":63,"r\u0065sult":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]},"x":` + deep + `}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.NotContains(t, rr.Body.String(), "secret", "an escaped result key must not leak the list") + assert.Contains(t, rr.Body.String(), `"id":63`) +} + +func TestSSEStreamFailsClosedOnDeepResultInHeldBody(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "secret": {authorized: false}, + }} + deep := strings.Repeat("[", 10001) + strings.Repeat("]", 10001) + body := `{"jsonrpc":"2.0","id":64,"result":{"tools":[{"name":"secret","inputSchema":{"type":"object"}}]},"x":` + deep + `}` + rr := runSSEStream(t, authorizer, "application/json", body) + + assert.NotContains(t, rr.Body.String(), "secret", "a held body past the depth cap must not pass through") + assert.Contains(t, rr.Body.String(), `"id":64`) + assert.Contains(t, rr.Body.String(), `"error"`) +} + +func TestSSEStreamFiltersListEventOverCapWhenChunked(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{ + "weather": {authorized: true}, + "secret": {authorized: false}, + }} + // A 2 MiB list event arrives in 32 KiB writes, as a reverse proxy delivers it. Its + // blank line comes last, so it must be filtered, not cut off at the cap. + pad := strings.Repeat("a", 2<<20) + event := sseStreamEvent(`{"jsonrpc":"2.0","id":65,"result":{"tools":[{"name":"weather","description":"` + pad + + `","inputSchema":{"type":"object"}},{"name":"secret","inputSchema":{"type":"object"}}]}}`) + var chunks []string + for rest := event; len(rest) > 0; { + n := min(32<<10, len(rest)) + chunks = append(chunks, rest[:n]) + rest = rest[n:] + } + rr := runSSEStream(t, authorizer, "text/event-stream", chunks...) + + assert.NotContains(t, rr.Body.String(), "secret", "a chunked oversized list must be filtered") + assert.Contains(t, rr.Body.String(), "weather", "the allowed tool must still be sent") + assert.Contains(t, rr.Body.String(), `"id":65`) +} + +func TestSSEStreamPassesInitializeCapabilitiesThrough(t *testing.T) { + t.Parallel() + + authorizer := &mockAuthorizer{results: map[string]mockResult{}} + // An initialize answer mentions tools only in its capabilities. It is not a find_tool + // answer and must pass unchanged, or every session with a tools-capable backend breaks. + body := sseStreamEvent(`{"jsonrpc":"2.0","id":66,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{"listChanged":true}}}}`) + rr := runSSEStream(t, authorizer, "text/event-stream", body) + + assert.Equal(t, body, rr.Body.String()) +} diff --git a/pkg/transport/proxy/httpsse/tool_list_authz_test.go b/pkg/transport/proxy/httpsse/tool_list_authz_test.go new file mode 100644 index 0000000000..34942c6847 --- /dev/null +++ b/pkg/transport/proxy/httpsse/tool_list_authz_test.go @@ -0,0 +1,247 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package httpsse_test + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/exp/jsonrpc2" + + "github.com/stacklok/toolhive/pkg/auth" + "github.com/stacklok/toolhive/pkg/authz" + "github.com/stacklok/toolhive/pkg/authz/authorizers/cedar" + "github.com/stacklok/toolhive/pkg/mcp" + "github.com/stacklok/toolhive/pkg/transport/proxy/httpsse" + "github.com/stacklok/toolhive/pkg/transport/types" +) + +// TestSSEToolsListIsFilteredByAuthz reproduces #6926 on the httpsse proxy: a tools/list +// answer that arrives on the GET /sse stream must be filtered by tool:read, the same way +// a streamable-HTTP answer is. Only "weather" is permitted, so "secret" must not appear. +func TestSSEToolsListIsFilteredByAuthz(t *testing.T) { + t.Parallel() + + authenticate := types.NamedMiddleware{Name: "authenticate", Function: func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + caller := &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{Subject: "owner", Claims: map[string]any{"iss": "issuer", "sub": "owner"}}, + Token: "owner", + } + next.ServeHTTP(w, r.WithContext(auth.WithIdentity(r.Context(), caller))) + }) + }} + + authorizer, err := cedar.NewCedarAuthorizer(cedar.ConfigOptions{ + Policies: []string{`permit(principal, action == Action::"call_tool", resource == Tool::"weather");`}, + EntitiesJSON: `[]`, + }, "") + require.NoError(t, err) + authzMW := types.NamedMiddleware{Name: "authz", Function: func(next http.Handler) http.Handler { + return mcp.ParsingMiddleware(authz.Middleware(authorizer, next, nil)) + }} + + port := freePort(t) + proxy := httpsse.NewHTTPSSEProxy("127.0.0.1", port, false, nil, []types.NamedMiddleware{authenticate, authzMW}) + require.NoError(t, proxy.Start(t.Context())) + t.Cleanup(func() { require.NoError(t, proxy.Stop(context.Background())) }) + base := fmt.Sprintf("http://127.0.0.1:%d", port) + client := &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{DisableKeepAlives: true}} + + // Open the SSE stream and learn the session id from the endpoint event. + streamReq, err := http.NewRequestWithContext(t.Context(), http.MethodGet, base+"/sse", nil) + require.NoError(t, err) + streamReq.Header.Set("Authorization", "owner") + stream, err := client.Do(streamReq) + require.NoError(t, err) + t.Cleanup(func() { _ = stream.Body.Close() }) + + events := readSSEEvents(stream.Body) + endpoint := nextEvent(t, events) + require.Equal(t, "endpoint", endpoint.name) + sessionID := endpoint.data[strings.Index(endpoint.data, "session_id=")+len("session_id="):] + + // Send tools/list. The backend's answer is delivered on the stream, not here. + body := `{"jsonrpc":"2.0","id":1,"method":"tools/list"}` + postReq, err := http.NewRequestWithContext(t.Context(), http.MethodPost, + base+"/messages?session_id="+sessionID, strings.NewReader(body)) + require.NoError(t, err) + postReq.Header.Set("Authorization", "owner") + postReq.Header.Set("Content-Type", "application/json") + post, err := client.Do(postReq) + require.NoError(t, err) + _ = post.Body.Close() + require.Equal(t, http.StatusAccepted, post.StatusCode) + + // Play the backend: answer the forwarded request with two tools. + forwarded := nextForwarded(t, proxy.GetMessageChannel()) + result, err := json.Marshal(map[string]any{"tools": []map[string]string{{"name": "weather"}, {"name": "secret"}}}) + require.NoError(t, err) + require.NoError(t, proxy.ForwardResponseToClients(t.Context(), &jsonrpc2.Response{ + ID: forwarded.(*jsonrpc2.Request).ID, + Result: result, + })) + + // The filtered list must be the only message on the stream that mentions tools. + var listed sseEvent + select { + case listed = <-events: + case <-time.After(5 * time.Second): + t.Fatal("no tools/list answer arrived on the SSE stream") + } + assert.Contains(t, listed.data, "weather") + assert.NotContains(t, listed.data, "secret", "a tool the caller cannot read must not be listed") +} + +// TestSSEPromptsListIsFilteredByAuthz is the prompts counterpart of +// TestSSEToolsListIsFilteredByAuthz. Prompt visibility is decided by get_prompt +// (see pkg/authz/response_filter.go), so the policy permits only that action on +// Prompt::"public_summary". "internal_audit" must not appear in the stream. +func TestSSEPromptsListIsFilteredByAuthz(t *testing.T) { + t.Parallel() + + authenticate := types.NamedMiddleware{Name: "authenticate", Function: func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + caller := &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{Subject: "owner", Claims: map[string]any{"iss": "issuer", "sub": "owner"}}, + Token: "owner", + } + next.ServeHTTP(w, r.WithContext(auth.WithIdentity(r.Context(), caller))) + }) + }} + + authorizer, err := cedar.NewCedarAuthorizer(cedar.ConfigOptions{ + Policies: []string{`permit(principal, action == Action::"get_prompt", resource == Prompt::"public_summary");`}, + EntitiesJSON: `[]`, + }, "") + require.NoError(t, err) + authzMW := types.NamedMiddleware{Name: "authz", Function: func(next http.Handler) http.Handler { + return mcp.ParsingMiddleware(authz.Middleware(authorizer, next, nil)) + }} + + port := freePort(t) + proxy := httpsse.NewHTTPSSEProxy("127.0.0.1", port, false, nil, []types.NamedMiddleware{authenticate, authzMW}) + require.NoError(t, proxy.Start(t.Context())) + t.Cleanup(func() { require.NoError(t, proxy.Stop(context.Background())) }) + base := fmt.Sprintf("http://127.0.0.1:%d", port) + client := &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{DisableKeepAlives: true}} + + streamReq, err := http.NewRequestWithContext(t.Context(), http.MethodGet, base+"/sse", nil) + require.NoError(t, err) + streamReq.Header.Set("Authorization", "owner") + stream, err := client.Do(streamReq) + require.NoError(t, err) + t.Cleanup(func() { _ = stream.Body.Close() }) + + events := readSSEEvents(stream.Body) + endpoint := nextEvent(t, events) + require.Equal(t, "endpoint", endpoint.name) + sessionID := endpoint.data[strings.Index(endpoint.data, "session_id=")+len("session_id="):] + + body := `{"jsonrpc":"2.0","id":1,"method":"prompts/list"}` + postReq, err := http.NewRequestWithContext(t.Context(), http.MethodPost, + base+"/messages?session_id="+sessionID, strings.NewReader(body)) + require.NoError(t, err) + postReq.Header.Set("Authorization", "owner") + postReq.Header.Set("Content-Type", "application/json") + post, err := client.Do(postReq) + require.NoError(t, err) + _ = post.Body.Close() + require.Equal(t, http.StatusAccepted, post.StatusCode) + + // Play the backend: answer the forwarded prompts/list with two prompts. + forwarded := nextForwarded(t, proxy.GetMessageChannel()) + result, err := json.Marshal(map[string]any{"prompts": []map[string]string{{"name": "public_summary"}, {"name": "internal_audit"}}}) + require.NoError(t, err) + require.NoError(t, proxy.ForwardResponseToClients(t.Context(), &jsonrpc2.Response{ + ID: forwarded.(*jsonrpc2.Request).ID, + Result: result, + })) + + var listed sseEvent + select { + case listed = <-events: + case <-time.After(5 * time.Second): + t.Fatal("no prompts/list answer arrived on the SSE stream") + } + assert.Contains(t, listed.data, "public_summary") + assert.NotContains(t, listed.data, "internal_audit", "a prompt the caller cannot get must not be listed") +} + +type sseEvent struct { + name string + data string +} + +// nextEvent waits for the next SSE event, failing the test instead of hanging when the +// stream stays silent. +func nextEvent(t *testing.T, events <-chan sseEvent) sseEvent { + t.Helper() + select { + case ev, ok := <-events: + require.True(t, ok, "the SSE stream ended before the expected event") + return ev + case <-time.After(5 * time.Second): + require.FailNow(t, "timed out waiting for an SSE event") + return sseEvent{} + } +} + +// readSSEEvents parses an SSE stream into events. It stops when the stream ends. +func readSSEEvents(body io.Reader) <-chan sseEvent { + out := make(chan sseEvent, 16) + go func() { + defer close(out) + scanner := bufio.NewScanner(body) + var ev sseEvent + for scanner.Scan() { + line := strings.TrimRight(scanner.Text(), "\r") + switch { + case line == "": + if ev.name != "" || ev.data != "" { + out <- ev + } + ev = sseEvent{} + case strings.HasPrefix(line, "event:"): + ev.name = strings.TrimSpace(strings.TrimPrefix(line, "event:")) + case strings.HasPrefix(line, "data:"): + ev.data = strings.TrimSpace(strings.TrimPrefix(line, "data:")) + } + } + }() + return out +} + +// freePort asks the OS for an unused TCP port. +func freePort(t *testing.T) int { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + port := l.Addr().(*net.TCPAddr).Port + require.NoError(t, l.Close()) + return port +} + +// nextForwarded waits for the message the proxy forwards to the backend. The +// wait is bounded so a missing forward fails the test instead of hanging it. +func nextForwarded(t *testing.T, ch chan jsonrpc2.Message) jsonrpc2.Message { + t.Helper() + select { + case msg := <-ch: + return msg + case <-time.After(10 * time.Second): + require.FailNow(t, "timed out waiting for the forwarded request") + return nil + } +} diff --git a/pkg/transport/proxy/transparent/sse_list_filter_test.go b/pkg/transport/proxy/transparent/sse_list_filter_test.go new file mode 100644 index 0000000000..a250aacad2 --- /dev/null +++ b/pkg/transport/proxy/transparent/sse_list_filter_test.go @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package transparent_test + +import ( + "context" + "io" + "net" + "net/http" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/authz" + "github.com/stacklok/toolhive/pkg/authz/authorizers" + "github.com/stacklok/toolhive/pkg/transport/proxy/transparent" + "github.com/stacklok/toolhive/pkg/transport/types" +) + +// startBackend serves handler on a plain http.Server. httptest.Server.Close +// calls CloseIdleConnections on http.DefaultTransport, which breaks requests +// that parallel tests in this package have in flight on that shared transport. +func startBackend(t *testing.T, handler http.Handler) string { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + srv := &http.Server{Handler: handler, ReadHeaderTimeout: 5 * time.Second} + go func() { _ = srv.Serve(l) }() + t.Cleanup(func() { _ = srv.Close() }) + return "http://" + l.Addr().String() +} + +// denyNamedTool authorizes every tool except the one named deniedTool. +type denyNamedTool struct { + deniedTool string +} + +func (d denyNamedTool) AuthorizeWithJWTClaims( + _ context.Context, + _ authorizers.MCPFeature, + _ authorizers.MCPOperation, + resourceID string, + _ map[string]interface{}, +) (bool, error) { + return resourceID != d.deniedTool, nil +} + +func TestSSEStreamListAnswerIsFilteredThroughProxy(t *testing.T) { + t.Parallel() + + const toolsList = `{"jsonrpc":"2.0","id":1,"result":{"tools":[` + + `{"name":"weather","inputSchema":{"type":"object"}},` + + `{"name":"secret","inputSchema":{"type":"object"}}]}}` + const toolsCall = `{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"ok"}],"isError":false}}` + + testCases := []struct { + name string + event string + wantContains string + wantAbsent string + }{ + {name: "tools list drops the denied tool", event: toolsList, wantContains: "weather", wantAbsent: "secret"}, + {name: "tool call result passes through", event: toolsCall, wantContains: `"content"`}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + backendURL := startBackend(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, "event: message\ndata: "+tc.event+"\n\n") + })) + + authzMiddleware := types.NamedMiddleware{ + Name: "authz", + Function: func(next http.Handler) http.Handler { + return authz.Middleware(denyNamedTool{deniedTool: "secret"}, next, nil) + }, + } + // Port 0 lets the OS pick the port at bind time, so no other process can take it first. + p := transparent.NewTransparentProxy("127.0.0.1", 0, backendURL, nil, nil, nil, false, false, "sse", nil, nil, "", false, authzMiddleware) + require.NoError(t, p.Start(t.Context())) + t.Cleanup(func() { _ = p.Stop(context.Background()) }) + + // A dedicated transport keeps this request off http.DefaultTransport, + // which other parallel tests in the package share. + client := &http.Client{Transport: &http.Transport{}} + t.Cleanup(client.CloseIdleConnections) + resp, err := client.Get("http://" + p.ListenerAddr() + "/sse") + require.NoError(t, err) + t.Cleanup(func() { _ = resp.Body.Close() }) + body, err := io.ReadAll(resp.Body) + require.NoError(t, err) + + assert.Contains(t, string(body), tc.wantContains) + if tc.wantAbsent != "" { + assert.False(t, strings.Contains(string(body), tc.wantAbsent), + "the denied tool must not reach the client through the proxy") + } + }) + } +}