diff --git a/pkgs/mcpx/internal/mcpclient/http.go b/pkgs/mcpx/internal/mcpclient/http.go index 19d9cd1d41..4e532130b3 100644 --- a/pkgs/mcpx/internal/mcpclient/http.go +++ b/pkgs/mcpx/internal/mcpclient/http.go @@ -290,18 +290,31 @@ func (t *HTTPTransport) Send(ctx context.Context, msg []byte) error { // subscriptions/listen -- was read until the server closed it, // which for a subscription is never: the acknowledgement and every // list_changed after it sat unread, and the stream's caller hung. - head := &firstValue{} + // The fallback buffer is capped at http.bodyLimit (#4282): the tee + // must never hold a whole non-JSON reply, however large it is. + limit := int64(defaults.HTTPBodyLimit) + head := &firstValue{max: limit + 1} dec := json.NewDecoder(io.TeeReader(resp.Body, head)) var first json.RawMessage if err := dec.Decode(&first); err != nil { - // Empty, or not JSON: handed on whole as before, for push to - // judge. - rest, readErr := io.ReadAll(resp.Body) + // Empty, or not JSON: read at most one byte past the cap and + // hand a body under it on whole, as before. A body over it is + // refused, not truncated (#4282, design #4375 decision 2): a + // truncated non-JSON body would manufacture a partial message + // out of bytes that are definitionally not a protocol message. + room := limit + 1 - int64(head.buf.Len()) + if room < 0 { + room = 0 + } + rest, readErr := io.ReadAll(io.LimitReader(resp.Body, room)) _ = resp.Body.Close() if readErr != nil { return readErr } b := append(head.buf.Bytes(), rest...) + if int64(len(b)) > limit { + return fmt.Errorf("mcpclient: %s replied with a non-JSON body larger than the %d-byte limit", t.url, limit) + } if len(bytes.TrimSpace(b)) > 0 { t.push(b) } @@ -327,17 +340,25 @@ func (t *HTTPTransport) Send(ctx context.Context, msg []byte) error { // firstValue keeps the bytes read while decoding a body's first JSON value, // so a body that turns out not to be JSON can still be handed on whole, and -// stops keeping them once that value is decoded. +// stops keeping them once that value is decoded. The kept head is capped at +// max bytes (#4282): the tee must not buffer a huge non-JSON 200 reply whole. type firstValue struct { buf bytes.Buffer done bool + max int64 } func (f *firstValue) Write(p []byte) (int, error) { + n := len(p) if !f.done { - f.buf.Write(p) + if room := f.max - int64(f.buf.Len()); room > 0 { + if int64(len(p)) > room { + p = p[:room] + } + f.buf.Write(p) + } } - return len(p), nil + return n, nil } // sseState is what one SSE stream said about itself: the last event id, diff --git a/pkgs/mcpx/internal/mcpclient/http_fallback_bound_test.go b/pkgs/mcpx/internal/mcpclient/http_fallback_bound_test.go new file mode 100644 index 0000000000..6b9b8575f9 --- /dev/null +++ b/pkgs/mcpx/internal/mcpclient/http_fallback_bound_test.go @@ -0,0 +1,156 @@ +package mcpclient_test + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/defaults" + "github.com/developing-today/code/pkgs/mcpx/internal/mcpclient" +) + +// sendFrame POSTs one frame and returns the next queued reply frame, failing +// the test if none arrives. +func sendFrame(t *testing.T, tr *mcpclient.HTTPTransport, msg string) []byte { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := tr.Send(ctx, []byte(msg)); err != nil { + t.Fatalf("Send: %v", err) + } + type result struct { + b []byte + err error + } + done := make(chan result, 1) + go func() { + b, err := tr.Recv() + done <- result{b, err} + }() + select { + case r := <-done: + if r.err != nil { + t.Fatalf("Recv: %v", r.err) + } + return r.b + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the reply frame") + return nil + } +} + +func plainServer(t *testing.T, contentType, body string) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", contentType) + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, body) + })) + t.Cleanup(srv.Close) + return srv +} + +func dialTestTransport(t *testing.T, url string) *mcpclient.HTTPTransport { + t.Helper() + tr, err := mcpclient.NewHTTP(mcpclient.HTTPOptions{URL: url}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = tr.Close() }) + return tr +} + +const fallbackPing = `{"jsonrpc":"2.0","id":1,"method":"ping"}` + +// TestSendNonJSONFallbackIsBounded is the regression test for #4282: a +// non-JSON 200 body at or under the cap passes through byte-for-byte, as +// before, and one over the cap makes Send refuse it — error, nothing pushed +// (design #4375 decision 2: never truncate, never buffer whole). +func TestSendNonJSONFallbackIsBounded(t *testing.T) { + limit := int64(defaults.HTTPBodyLimit) + for _, size := range []int64{16, limit - 1, limit, limit + 1, limit*4 + 123} { + t.Run(fmt.Sprintf("bytes-%d", size), func(t *testing.T) { + body := strings.Repeat("A", int(size)) // never valid JSON + tr := dialTestTransport(t, plainServer(t, "text/html", body).URL) + if size <= limit { + if got := sendFrame(t, tr, fallbackPing); string(got) != body { + t.Fatalf("small non-JSON body changed: got %d bytes, want %d whole", len(got), len(body)) + } + return + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + err := tr.Send(ctx, []byte(fallbackPing)) + if err == nil { + t.Fatalf("oversized non-JSON body accepted: want an error naming the %d-byte limit", limit) + } + if !strings.Contains(err.Error(), "non-JSON body") || !strings.Contains(err.Error(), fmt.Sprintf("%d-byte limit", limit)) { + t.Fatalf("oversized non-JSON body error does not name the surface and the cap: %v", err) + } + select { + case got := <-recvChan(t, tr): + t.Fatalf("oversized non-JSON body pushed %d bytes after refusal (limit %d)", len(got), limit) + case <-time.After(200 * time.Millisecond): + } + }) + } +} + +// TestSendEmptyNonJSONPushesNothing covers the empty-body corner of the same +// fallback: nothing to judge, nothing queued. +func TestSendEmptyNonJSONPushesNothing(t *testing.T) { + tr := dialTestTransport(t, plainServer(t, "text/plain", "").URL) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := tr.Send(ctx, []byte(fallbackPing)); err != nil { + t.Fatalf("Send: %v", err) + } + select { + case b := <-recvChan(t, tr): + t.Fatalf("empty body queued a frame: %q", b) + case <-time.After(200 * time.Millisecond): + } +} + +func recvChan(t *testing.T, tr *mcpclient.HTTPTransport) <-chan []byte { + t.Helper() + ch := make(chan []byte, 1) + go func() { + b, err := tr.Recv() + if err == nil { + ch <- b + } + }() + return ch +} + +// TestSendValidJSONUnchanged guards the success path the bound must not +// touch: a single JSON value, including one far larger than the fallback +// limit, arrives whole. +func TestSendValidJSONUnchanged(t *testing.T) { + limit := int64(defaults.HTTPBodyLimit) + big := strings.Repeat("z", int(limit*2)) + for _, reply := range []string{ + `{"jsonrpc":"2.0","id":1,"result":{"ok":true}}`, + `{"jsonrpc":"2.0","id":1,"result":{"blob":"` + big + `"}}`, + } { + tr := dialTestTransport(t, plainServer(t, "application/json", reply).URL) + if got := sendFrame(t, tr, fallbackPing); string(got) != reply { + t.Fatalf("valid JSON changed: got %d bytes, want %d", len(got), len(reply)) + } + } +} + +// TestSendSSEUnchanged guards the SSE path the bound must not touch. +func TestSendSSEUnchanged(t *testing.T) { + payload := `{"jsonrpc":"2.0","id":1,"result":{"ok":true}}` + tr := dialTestTransport(t, plainServer(t, "text/event-stream", "data: "+payload+"\n\n").URL) + if got := sendFrame(t, tr, fallbackPing); string(got) != payload { + t.Fatalf("SSE payload changed: got %q, want %q", got, payload) + } +}