From 39e8692a4ec28f65efe8d336c5347adcb2a7560c Mon Sep 17 00:00:00 2001 From: anupsv <6407789+anupsv@users.noreply.github.com> Date: Sat, 13 Jun 2026 20:34:56 -0700 Subject: [PATCH 1/5] fix(coordinator): cap plaintext inference request body MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The plaintext inference path (handleChatCompletions / handleGenericInference -> parseInferencePrelude) read the request body with an unbounded io.ReadAll(r.Body), so any API-key holder could POST a multi-GB JSON body and OOM the coordinator — the trusted TEE component. The sealed (E2E) path already caps at 16 MiB via http.MaxBytesReader (sender_encryption.go); the common plaintext path had no limit. Model-independent (the read is in the shared prelude, before routing). parseInferencePrelude now wraps r.Body in http.MaxBytesReader and maps an over-cap read to HTTP 413. The cap is 64 MiB — sized to the first-party UI's per-message image limit (MAX_IMAGES_PER_MESSAGE=4 x MAX_IMAGE_BYTES=10 MB = 40 MB raw ~= 53 MiB after base64, plus JSON/text overhead) so legitimate multimodal requests aren't rejected (a 16 MiB cap would 413 two max-size images). Regression: an oversized body (streamed, not allocated) -> 413; a small invalid-JSON body -> 400 (not 413). Verified the oversized test fails without the cap (falls through to 400). --- coordinator/api/inference_body_cap_test.go | 64 ++++++++++++++++++++++ coordinator/api/inference_preprocess.go | 22 ++++++++ 2 files changed, 86 insertions(+) create mode 100644 coordinator/api/inference_body_cap_test.go diff --git a/coordinator/api/inference_body_cap_test.go b/coordinator/api/inference_body_cap_test.go new file mode 100644 index 0000000000..cd06d42d7c --- /dev/null +++ b/coordinator/api/inference_body_cap_test.go @@ -0,0 +1,64 @@ +package api + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "testing" +) + +// Regression for OOM-M1: the plaintext inference path read the request body with +// an unbounded io.ReadAll, so any API-key holder could POST a multi-GB body and +// OOM the coordinator (the trusted TEE component). parseInferencePrelude now caps +// it with http.MaxBytesReader. These exercise the prelude directly — the size +// check returns before any auth/store access, so a zero-value Server suffices. + +// infiniteReader yields 'a' forever; used with io.LimitReader so the oversized +// test streams cap+1 bytes instead of allocating the whole over-cap body. +type infiniteReader struct{} + +func (infiniteReader) Read(p []byte) (int, error) { + for i := range p { + p[i] = 'a' + } + return len(p), nil +} + +// Load-bearing regression: without the cap, io.ReadAll consumes the whole +// oversized body and the request falls through to a 400 (invalid JSON) — this +// asserts 413, so it fails on the unpatched code. +func TestParseInferencePreludeRejectsOversizedBody(t *testing.T) { + s := &Server{} + body := io.LimitReader(infiniteReader{}, int64(maxInferenceBodyBytes)+1) + r := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", body) + w := httptest.NewRecorder() + + if _, ok := s.parseInferencePrelude(w, r); ok { + t.Fatal("expected parseInferencePrelude to reject the oversized body") + } + if w.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("oversized body: got status %d, want 413", w.Code) + } +} + +// False-trigger guard (NOT a fail-without-fix regression — an 8-byte body never +// hits the cap, so this passes with or without the fix): a small invalid-JSON +// body must fail JSON parsing (400), not the size cap (413), proving the cap +// doesn't reject normal-sized requests. +func TestParseInferencePreludeUnderCapNotSizeRejected(t *testing.T) { + s := &Server{} + r := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", + bytes.NewReader([]byte("not json"))) + w := httptest.NewRecorder() + + if _, ok := s.parseInferencePrelude(w, r); ok { + t.Fatal("expected invalid JSON to be rejected") + } + if w.Code == http.StatusRequestEntityTooLarge { + t.Fatal("under-cap body was wrongly rejected as too large (413)") + } + if w.Code != http.StatusBadRequest { + t.Fatalf("invalid JSON: got status %d, want 400", w.Code) + } +} diff --git a/coordinator/api/inference_preprocess.go b/coordinator/api/inference_preprocess.go index c3c68a069a..b357ff4bf7 100644 --- a/coordinator/api/inference_preprocess.go +++ b/coordinator/api/inference_preprocess.go @@ -13,11 +13,24 @@ package api import ( "encoding/json" + "errors" "fmt" "io" "net/http" ) +// maxInferenceBodyBytes caps the plaintext inference request body. Without it +// the common (non-sealed) path does io.ReadAll(r.Body) with no limit, so any +// API-key holder could POST a multi-GB body and OOM the coordinator (the trusted +// TEE component). +// +// Sized to the first-party UI's per-message image limit so legitimate multimodal +// requests aren't rejected: MAX_IMAGES_PER_MESSAGE (4) × MAX_IMAGE_BYTES (10 MB) +// = 40 MB raw ≈ 53 MiB after base64 inflation, plus JSON/text overhead — see +// console-ui/src/lib/image-upload.ts. (The sealed E2E path enforces its own +// 16 MiB cap in sender_encryption.go; this is the plaintext image path.) +const maxInferenceBodyBytes = 64 << 20 // 64 MiB + // inferencePrelude carries the parsed request shape produced by the shared // prelude: the (tool-schema-normalized) raw body and its parsed map, plus the // consumer-requested model name (alias or raw build id, pre-resolution). @@ -36,8 +49,17 @@ type inferencePrelude struct { func (s *Server) parseInferencePrelude(w http.ResponseWriter, r *http.Request) (inferencePrelude, bool) { // Read the raw request body so we can forward it as-is to the provider. // We only parse minimally to extract model/stream/messages for routing. + // Cap it first: io.ReadAll would otherwise buffer an unbounded body and a + // multi-GB POST would OOM the coordinator. + r.Body = http.MaxBytesReader(w, r.Body, maxInferenceBodyBytes) rawBody, err := io.ReadAll(r.Body) if err != nil { + var maxBytesErr *http.MaxBytesError + if errors.As(err, &maxBytesErr) { + writeJSON(w, http.StatusRequestEntityTooLarge, errorResponse("invalid_request_error", + fmt.Sprintf("request body exceeds the %d-byte limit", maxInferenceBodyBytes))) + return inferencePrelude{}, false + } writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "failed to read request body")) return inferencePrelude{}, false } From a618f78681aa7c8cfe9e090ea396d3e5bee8f2cb Mon Sep 17 00:00:00 2001 From: anupsv <6407789+anupsv@users.noreply.github.com> Date: Sat, 13 Jun 2026 22:01:37 -0700 Subject: [PATCH 2/5] fix(ui): bound image history in chat payloads --- console-ui/src/lib/chat-messages.test.ts | 48 ++++++++++++++++++++++-- console-ui/src/lib/chat-messages.ts | 40 ++++++++++++++++---- coordinator/api/inference_preprocess.go | 11 +++--- 3 files changed, 83 insertions(+), 16 deletions(-) diff --git a/console-ui/src/lib/chat-messages.test.ts b/console-ui/src/lib/chat-messages.test.ts index 68f7a80fa8..b977167413 100644 --- a/console-ui/src/lib/chat-messages.test.ts +++ b/console-ui/src/lib/chat-messages.test.ts @@ -2,6 +2,10 @@ import { describe, it, expect } from "vitest"; import { toApiMessages } from "./chat-messages"; import type { Message } from "./store"; +const PNG_IMAGE = "data:image/png;base64,AAA"; +const JPEG_IMAGE = "data:image/jpeg;base64,BBB"; +const OLD_ANSWER = "old answer"; + function msg(partial: Pick & Partial): Message { return { id: "x", timestamp: 0, ...partial }; } @@ -24,14 +28,14 @@ describe("toApiMessages", () => { it("inlines attached images as text-first image_url parts", () => { const out = toApiMessages([ - msg({ role: "user", content: "what is this", images: ["data:image/png;base64,AAA"] }), + msg({ role: "user", content: "what is this", images: [PNG_IMAGE] }), ]); expect(out).toEqual([ { role: "user", content: [ { type: "text", text: "what is this" }, - { type: "image_url", image_url: { url: "data:image/png;base64,AAA" } }, + { type: "image_url", image_url: { url: PNG_IMAGE } }, ], }, ]); @@ -41,13 +45,49 @@ describe("toApiMessages", () => { const out = toApiMessages([ msg({ role: "user", content: "earlier text" }), msg({ role: "assistant", content: "reply" }), - msg({ role: "user", content: "", images: ["data:image/jpeg;base64,BBB"] }), + msg({ role: "user", content: "", images: [JPEG_IMAGE] }), ]); expect(out[0]).toEqual({ role: "user", content: "earlier text" }); expect(out[1]).toEqual({ role: "assistant", content: "reply" }); expect(out[2]).toEqual({ role: "user", - content: [{ type: "image_url", image_url: { url: "data:image/jpeg;base64,BBB" } }], + content: [{ type: "image_url", image_url: { url: JPEG_IMAGE } }], }); }); + + it("keeps only the newest image-bearing turn to stay under the coordinator body cap", () => { + const out = toApiMessages([ + msg({ role: "user", content: "old image", images: [PNG_IMAGE] }), + msg({ role: "assistant", content: OLD_ANSWER }), + msg({ role: "user", content: "new image", images: [JPEG_IMAGE] }), + ]); + + expect(out).toEqual([ + { role: "user", content: "old image" }, + { role: "assistant", content: OLD_ANSWER }, + { + role: "user", + content: [ + { type: "text", text: "new image" }, + { type: "image_url", image_url: { url: JPEG_IMAGE } }, + ], + }, + ]); + }); + + it("drops older image-only turns after pruning their image data", () => { + const out = toApiMessages([ + msg({ role: "user", content: "", images: [PNG_IMAGE] }), + msg({ role: "assistant", content: OLD_ANSWER }), + msg({ role: "user", content: "", images: [JPEG_IMAGE] }), + ]); + + expect(out).toEqual([ + { role: "assistant", content: OLD_ANSWER }, + { + role: "user", + content: [{ type: "image_url", image_url: { url: JPEG_IMAGE } }], + }, + ]); + }); }); diff --git a/console-ui/src/lib/chat-messages.ts b/console-ui/src/lib/chat-messages.ts index 1ad9417c22..47c852aa2a 100644 --- a/console-ui/src/lib/chat-messages.ts +++ b/console-ui/src/lib/chat-messages.ts @@ -4,9 +4,14 @@ import { buildApiContent } from "./image-upload"; /** * Convert stored chat messages into the OpenAI/OpenRouter wire shape, inlining - * any attached images as `image_url` content parts (text-only turns stay plain - * strings). Shared by the send and retry paths so the transformation lives in - * one place. + * attached images from the most recent image-bearing turn as `image_url` + * content parts (text-only turns stay plain strings). Shared by the send and + * retry paths so the transformation lives in one place. + * + * The coordinator caps plaintext inference bodies at 64 MiB. One UI turn may + * carry four 10 MB images (~53 MiB after base64), so resending multiple image + * turns from live chat history would breach that cap. Older images remain in + * the visible chat state, but only the newest image turn is sent upstream. * * NOTE: `m.images` is undefined for turns restored from persistence (images are * stripped from localStorage to protect the quota — see store.ts `partialize`), @@ -16,8 +21,29 @@ import { buildApiContent } from "./image-upload"; export function toApiMessages( messages: Pick[] ): ChatMessage[] { - return messages.map((m) => ({ - role: m.role, - content: buildApiContent(m.content, m.images), - })); + const newestImageIndex = findNewestImageMessageIndex(messages); + + return messages.flatMap((m, i) => { + const images = i === newestImageIndex ? m.images : undefined; + if ((!images || images.length === 0) && m.content.length === 0) { + return []; + } + return [{ + role: m.role, + content: buildApiContent(m.content, images), + }]; + }); +} + +function findNewestImageMessageIndex( + messages: Pick[] +): number { + let index = messages.length; + for (const message of [...messages].reverse()) { + index -= 1; + if (message.images && message.images.length > 0) { + return index; + } + } + return -1; } diff --git a/coordinator/api/inference_preprocess.go b/coordinator/api/inference_preprocess.go index b357ff4bf7..b3ffdccb12 100644 --- a/coordinator/api/inference_preprocess.go +++ b/coordinator/api/inference_preprocess.go @@ -24,11 +24,12 @@ import ( // API-key holder could POST a multi-GB body and OOM the coordinator (the trusted // TEE component). // -// Sized to the first-party UI's per-message image limit so legitimate multimodal -// requests aren't rejected: MAX_IMAGES_PER_MESSAGE (4) × MAX_IMAGE_BYTES (10 MB) -// = 40 MB raw ≈ 53 MiB after base64 inflation, plus JSON/text overhead — see -// console-ui/src/lib/image-upload.ts. (The sealed E2E path enforces its own -// 16 MiB cap in sender_encryption.go; this is the plaintext image path.) +// Sized to one first-party UI image-bearing turn: MAX_IMAGES_PER_MESSAGE (4) × +// MAX_IMAGE_BYTES (10 MB) = 40 MB raw ≈ 53 MiB after base64 inflation, plus +// JSON/text overhead. The console preserves text history but only resends images +// from the newest image turn, so normal UI multimodal requests stay below this +// fixed DoS cap. (The sealed E2E path enforces its own 16 MiB cap in +// sender_encryption.go; this is the plaintext image path.) const maxInferenceBodyBytes = 64 << 20 // 64 MiB // inferencePrelude carries the parsed request shape produced by the shared From 8f66c2407e1c432207c8bad0a60b04b577866884 Mon Sep 17 00:00:00 2001 From: anupsv <6407789+anupsv@users.noreply.github.com> Date: Sun, 14 Jun 2026 11:58:02 -0700 Subject: [PATCH 3/5] fix(coordinator): size plaintext body cap to provider WS frame budget (16 MiB) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review (P1) caught that the 64 MiB cap exceeds what providers can receive: the coordinator sends the encrypted request as ONE WebSocket frame (base64 NaCl-box), and the Swift provider rejects frames >32 MiB by tearing down the session and cancelling every unrelated in-flight request. base64 adds x4/3, so a body over ~24 MiB produced an oversized frame — passing the prelude only to disconnect the provider instead of returning a clean 413. Lower to 16 MiB to match the provider's documented frame budget (16 MiB body -> ~21.3 MiB frame, comfortably under 32 MiB) and the sealed path. The console's image-history trim is complementary, but a single 4x10MB turn still exceeds this and is undeliverable — aligning the per-turn UI image budget with the frame cap is tracked separately. Also dedupes the infiniteReader test helper (now shared from body_cap_test.go after the global body-cap change merged) and drops a stale finding-id comment. --- coordinator/api/inference_body_cap_test.go | 22 ++++++---------------- coordinator/api/inference_preprocess.go | 22 +++++++++++++++------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/coordinator/api/inference_body_cap_test.go b/coordinator/api/inference_body_cap_test.go index cd06d42d7c..867c2c930e 100644 --- a/coordinator/api/inference_body_cap_test.go +++ b/coordinator/api/inference_body_cap_test.go @@ -8,22 +8,12 @@ import ( "testing" ) -// Regression for OOM-M1: the plaintext inference path read the request body with -// an unbounded io.ReadAll, so any API-key holder could POST a multi-GB body and -// OOM the coordinator (the trusted TEE component). parseInferencePrelude now caps -// it with http.MaxBytesReader. These exercise the prelude directly — the size -// check returns before any auth/store access, so a zero-value Server suffices. - -// infiniteReader yields 'a' forever; used with io.LimitReader so the oversized -// test streams cap+1 bytes instead of allocating the whole over-cap body. -type infiniteReader struct{} - -func (infiniteReader) Read(p []byte) (int, error) { - for i := range p { - p[i] = 'a' - } - return len(p), nil -} +// Regression for the plaintext inference body cap: the path read the request +// body with an unbounded io.ReadAll, so any API-key holder could POST a multi-GB +// body and OOM the coordinator (the trusted TEE component). parseInferencePrelude +// now caps it with http.MaxBytesReader. These exercise the prelude directly — the +// size check returns before any auth/store access, so a zero-value Server +// suffices. (infiniteReader is shared from body_cap_test.go in this package.) // Load-bearing regression: without the cap, io.ReadAll consumes the whole // oversized body and the request falls through to a 400 (invalid JSON) — this diff --git a/coordinator/api/inference_preprocess.go b/coordinator/api/inference_preprocess.go index b3ffdccb12..273fa248f2 100644 --- a/coordinator/api/inference_preprocess.go +++ b/coordinator/api/inference_preprocess.go @@ -24,13 +24,21 @@ import ( // API-key holder could POST a multi-GB body and OOM the coordinator (the trusted // TEE component). // -// Sized to one first-party UI image-bearing turn: MAX_IMAGES_PER_MESSAGE (4) × -// MAX_IMAGE_BYTES (10 MB) = 40 MB raw ≈ 53 MiB after base64 inflation, plus -// JSON/text overhead. The console preserves text history but only resends images -// from the newest image turn, so normal UI multimodal requests stay below this -// fixed DoS cap. (The sealed E2E path enforces its own 16 MiB cap in -// sender_encryption.go; this is the plaintext image path.) -const maxInferenceBodyBytes = 64 << 20 // 64 MiB +// Sized to the PROVIDER WebSocket frame budget, not just OOM-safety: the +// coordinator encrypts rawBody and sends the base64 NaCl-box as ONE WS frame +// (consumer.go), and the Swift provider rejects frames over 32 MiB by tearing +// down the whole session + cancelling every unrelated in-flight request +// (CoordinatorClient.maxInboundMessageBytes). base64 adds ×4/3, so a 16 MiB body +// → ~21.3 MiB frame, comfortably under 32 MiB — the budget that provider cap was +// sized against, and identical to the sealed path (sender_encryption.go). A +// larger cap would let a request pass here only to disconnect the provider +// instead of returning a clean 413. +// +// The console already trims image history to the newest image turn +// (chat-messages.ts), but a single 4×10 MB turn (~53 MiB) still exceeds this and +// is undeliverable to any provider — aligning the per-turn UI image budget with +// the frame cap is tracked separately. +const maxInferenceBodyBytes = 16 << 20 // 16 MiB // inferencePrelude carries the parsed request shape produced by the shared // prelude: the (tool-schema-normalized) raw body and its parsed map, plus the From 9a042c05afc8726d357bb50e69ad370d01d12b62 Mon Sep 17 00:00:00 2001 From: anupsv <6407789+anupsv@users.noreply.github.com> Date: Sun, 14 Jun 2026 12:17:43 -0700 Subject: [PATCH 4/5] fix(coordinator): bound the re-marshaled forward body, not just the read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 16 MiB read cap bounds the request as received, but the chat/generic handlers re-marshal the parsed body before sealing it (max_tokens injection, Responses->chat lowering, tool normalization). encoding/json's default Marshal HTML-escapes '<' '>' '&' into 6-byte \uXXXX forms, so a benign request that fit the read cap — e.g. a prompt with a long run of '<' — could re-marshal ~6x larger and seal into a WebSocket frame the provider rejects by tearing down its session and cancelling every unrelated in-flight request. Two-part fix: - marshalForwardBody: re-marshal with HTML escaping disabled (the body is sealed and parsed as JSON by the provider, never embedded in HTML), so the forwarded body tracks the size-capped input instead of inflating. - Re-check maxInferenceBodyBytes on the FINAL sealed body in both handlers, before the balance reservation (chat) or with a refund (generic), returning a clean 413 instead of disconnecting a provider mid-flight. Adds TestMarshalForwardBodyDoesNotHTMLEscape and refreshes the now-stale maxRequestBodyBytes comment. --- coordinator/api/consumer.go | 34 ++++++++++++++-- coordinator/api/inference_body_cap_test.go | 46 ++++++++++++++++++++++ coordinator/api/inference_preprocess.go | 28 +++++++++++++ coordinator/api/server.go | 7 ++-- 4 files changed, 109 insertions(+), 6 deletions(-) diff --git a/coordinator/api/consumer.go b/coordinator/api/consumer.go index daca3d47e9..1b6d74bf99 100644 --- a/coordinator/api/consumer.go +++ b/coordinator/api/consumer.go @@ -1403,7 +1403,7 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { // silent post-inference charge failure would hand the consumer free // inference (GitHub issue #33). if ensureMaxTokensBound(parsed, isResponsesAPI, maxOutputBound) { - rawBody, _ = json.Marshal(parsed) + rawBody, _ = marshalForwardBody(parsed) } stream, _ := parsed["stream"].(bool) @@ -1418,7 +1418,21 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", err.Error())) return } - rawBody, _ = json.Marshal(providerParsed) + rawBody, _ = marshalForwardBody(providerParsed) + } + + // Re-check the cap on the FINAL body we'll seal. The read cap bounded the + // input, but the body above was re-marshaled after mutation (max_tokens + // injection, Responses→chat lowering); the coordinator seals it and sends it + // as ONE WebSocket frame, and a body over the cap produces a frame the + // provider rejects by tearing down its session (see maxInferenceBodyBytes / + // CoordinatorClient.maxInboundMessageBytes). Fail fast with a clean 413 here — + // before the balance reservation, so there's nothing to refund — rather than + // disconnecting a provider mid-flight. + if len(rawBody) > maxInferenceBodyBytes { + writeJSON(w, http.StatusRequestEntityTooLarge, errorResponse("invalid_request_error", + fmt.Sprintf("request body exceeds the %d-byte limit", maxInferenceBodyBytes))) + return } // Per-account token rate limiting (ITPM/OTPM) — the industry-standard @@ -4198,7 +4212,21 @@ func (s *Server) handleGenericInference(w http.ResponseWriter, r *http.Request, } } - inferenceBody, _ := json.Marshal(parsed) + inferenceBody, _ := marshalForwardBody(parsed) + + // Re-check the cap on the FINAL body we'll seal (the input cap bounded the + // read; this body was re-marshaled after mutation). A body over the cap seals + // into a frame the provider rejects by tearing down its session — return a + // clean 413 instead (see maxInferenceBodyBytes). Billing is already reserved + // at this point, so refund before returning. + if len(inferenceBody) > maxInferenceBodyBytes { + cleanupPending() + refundExtra() + refundReservation() + writeJSON(w, http.StatusRequestEntityTooLarge, errorResponse("invalid_request_error", + fmt.Sprintf("request body exceeds the %d-byte limit", maxInferenceBodyBytes))) + return + } if provider.PublicKey == "" { cleanupPending() diff --git a/coordinator/api/inference_body_cap_test.go b/coordinator/api/inference_body_cap_test.go index 867c2c930e..b5f0588c11 100644 --- a/coordinator/api/inference_body_cap_test.go +++ b/coordinator/api/inference_body_cap_test.go @@ -2,9 +2,11 @@ package api import ( "bytes" + "encoding/json" "io" "net/http" "net/http/httptest" + "strings" "testing" ) @@ -52,3 +54,47 @@ func TestParseInferencePreludeUnderCapNotSizeRejected(t *testing.T) { t.Fatalf("invalid JSON: got status %d, want 400", w.Code) } } + +// Regression for the re-marshal inflation that the read cap alone didn't catch: +// the handlers re-marshal the parsed body before sealing it, and encoding/json's +// default HTML escaping turns each '<' '>' '&' into a 6-byte \uXXXX escape. A +// benign body that fit the read cap could thus re-marshal ~6× larger and produce +// a WebSocket frame the provider rejects (tearing down its session). The forward +// marshaler disables HTML escaping; this asserts the angle brackets survive raw +// and the output tracks the input size instead of exploding. +func TestMarshalForwardBodyDoesNotHTMLEscape(t *testing.T) { + const n = 1 << 20 // 1 MiB of '<' + body := map[string]any{ + "model": "m", + "messages": []any{map[string]any{"role": "user", "content": strings.Repeat("<", n)}}, + } + + got, err := marshalForwardBody(body) + if err != nil { + t.Fatalf("marshalForwardBody: %v", err) + } + // The 6-byte JSON escape for '<' is the ASCII run \ u 0 0 3 c. + escapedAngle := []byte{'\\', 'u', '0', '0', '3', 'c'} + if bytes.Contains(got, escapedAngle) { + t.Fatal(`marshalForwardBody HTML-escaped '<' to < — expected raw bytes`) + } + if !bytes.Contains(got, bytes.Repeat([]byte("<"), 8)) { + t.Fatal("marshalForwardBody dropped the raw '<' run") + } + if got[len(got)-1] == '\n' { + t.Fatal("marshalForwardBody left the encoder's trailing newline") + } + + // The unescaped body must track the input (~1 MiB + small envelope); the + // default escaping marshaler inflates the same body ~6×. Prove the gap. + escaped, err := json.Marshal(body) + if err != nil { + t.Fatalf("json.Marshal: %v", err) + } + if len(escaped) <= len(got) { + t.Fatalf("expected default Marshal (%d) larger than unescaped (%d)", len(escaped), len(got)) + } + if len(got) > n+4096 { + t.Fatalf("unescaped body unexpectedly large: %d bytes (input ~%d)", len(got), n) + } +} diff --git a/coordinator/api/inference_preprocess.go b/coordinator/api/inference_preprocess.go index 273fa248f2..04d3e87d3e 100644 --- a/coordinator/api/inference_preprocess.go +++ b/coordinator/api/inference_preprocess.go @@ -12,6 +12,7 @@ package api // caller to return via ok=false / handled=true. import ( + "bytes" "encoding/json" "errors" "fmt" @@ -38,8 +39,35 @@ import ( // (chat-messages.ts), but a single 4×10 MB turn (~53 MiB) still exceeds this and // is undeliverable to any provider — aligning the per-turn UI image budget with // the frame cap is tracked separately. +// +// This caps the body we READ. The body we actually SEAL can differ: the handlers +// re-marshal the parsed request after mutating it (max_tokens injection, tool +// normalization). The cap is therefore re-checked on that final body before +// encryption (see handleChatCompletions / handleGenericInference) using +// marshalForwardBody, which also disables HTML escaping so the re-marshal can't +// silently inflate a benign body past this limit. const maxInferenceBodyBytes = 16 << 20 // 16 MiB +// marshalForwardBody serializes a parsed request body for forwarding to a +// provider WITHOUT HTML escaping. encoding/json's default Marshal escapes the +// bytes '<', '>', and '&' into their 6-byte \uXXXX forms — a 6× per-character +// inflation that is meaningless on this path (the body is sealed and parsed as +// JSON by the provider, never embedded in HTML) yet can balloon a benign request +// — e.g. a prompt containing a long run of '<' — past the provider's +// single-frame WebSocket limit, tearing down its session. Disabling escaping +// keeps the re-marshaled body within a small constant of the (already +// size-capped) input. Mirrors NormalizeToolSchemas's own non-escaping round-trip. +func marshalForwardBody(v any) ([]byte, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + return nil, err + } + // Encoder.Encode appends a trailing newline the encrypted body shouldn't carry. + return bytes.TrimSuffix(buf.Bytes(), []byte{'\n'}), nil +} + // inferencePrelude carries the parsed request shape produced by the shared // prelude: the (tool-schema-normalized) raw body and its parsed map, plus the // consumer-requested model name (alias or raw build id, pre-resolution). diff --git a/coordinator/api/server.go b/coordinator/api/server.go index fd75aa6a74..611cca700a 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -1300,9 +1300,10 @@ func (s *Server) handleRuntimeManifest(w http.ResponseWriter, r *http.Request) { const maxMDMWebhookBodyBytes = 1 << 20 // 1 MiB // maxRequestBodyBytes is the global ceiling bodyLimitMiddleware applies to every -// request body so no endpoint can be OOM'd by an unbounded POST. It clears the -// largest legitimate body (the 64 MiB plaintext-inference image path); handlers -// needing less wrap r.Body in a tighter MaxBytesReader on top. +// request body so no endpoint can be OOM'd by an unbounded POST. It's a coarse +// outer bound that clears every legitimate body with headroom; the hot paths +// self-cap tighter on top (the plaintext-inference path at 16 MiB, sized to the +// provider WS frame budget — see maxInferenceBodyBytes). const maxRequestBodyBytes = 64 << 20 // 64 MiB // maxControlPlaneBodyBytes is the tight cap for small unauthenticated From 0b3e3d02eaa65af25a3daccdf2138a0a1fe37b1c Mon Sep 17 00:00:00 2001 From: anupsv <6407789+anupsv@users.noreply.github.com> Date: Sun, 14 Jun 2026 12:55:45 -0700 Subject: [PATCH 5/5] fix(coordinator): cover the alias-capacity fallback re-marshal + single freeze-point cap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up review found the prior commit was incomplete: the chat handler re-marshals the parsed body in five more places besides the two it fixed — alias resolution, allowlist/routing-field stripping, reasoning_parser injection, and (the live escape) the alias-capacity fallback that switches a saturated desired build to its previous build. All used the HTML-escaping json.Marshal, and the fallback's result is what gets frozen into dispatchState and sealed — so a '<'-heavy request taking the fallback could still inflate ~6x and seal an oversized frame, tearing down the provider session. - Switch every forward-marshal site in the chat path to marshalForwardBody. - Replace the mid-handler cap recheck with a single authoritative cap at the point rawBody is frozen into dispatchState — after ALL re-marshals including the fallback — so one check covers every upstream mutation. Refunds the held reservation before the 413. - Add TestAliasCapacityFallbackForwardsUnescapedBody: drives a real request through the alias-capacity fallback over the WS protocol and asserts the body the provider decrypts is unescaped. Verified it fails (\u003c detected) when any fallback marshal site regresses to json.Marshal. --- coordinator/api/consumer.go | 43 +++--- ...ference_body_remarshal_integration_test.go | 130 ++++++++++++++++++ 2 files changed, 154 insertions(+), 19 deletions(-) create mode 100644 coordinator/api/inference_body_remarshal_integration_test.go diff --git a/coordinator/api/consumer.go b/coordinator/api/consumer.go index 1b6d74bf99..03e3bb7a85 100644 --- a/coordinator/api/consumer.go +++ b/coordinator/api/consumer.go @@ -279,7 +279,7 @@ func (s *Server) resolveRequestedModel(parsed map[string]any, rawBody []byte, re return requested, requested, rawBody, true } parsed["model"] = buildID - rb, err := json.Marshal(parsed) + rb, err := marshalForwardBody(parsed) if err != nil { rb = rawBody } @@ -1332,7 +1332,7 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { return } if hasProviderAllowlist && stripProviderRoutingFields(parsed) { - rawBody, _ = json.Marshal(parsed) + rawBody, _ = marshalForwardBody(parsed) } // "Use my own machine, for free" opt-in. The signal is the @@ -1384,7 +1384,7 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { if _, hasRP := parsed["reasoning_parser"]; !hasRP && rec.RuntimeParameters != nil { if rp, ok := rec.RuntimeParameters["reasoning_parser"]; ok { parsed["reasoning_parser"] = rp - rawBody, _ = json.Marshal(parsed) + rawBody, _ = marshalForwardBody(parsed) } } // Use the registry's max_output_length as the default max_tokens @@ -1421,20 +1421,6 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { rawBody, _ = marshalForwardBody(providerParsed) } - // Re-check the cap on the FINAL body we'll seal. The read cap bounded the - // input, but the body above was re-marshaled after mutation (max_tokens - // injection, Responses→chat lowering); the coordinator seals it and sends it - // as ONE WebSocket frame, and a body over the cap produces a frame the - // provider rejects by tearing down its session (see maxInferenceBodyBytes / - // CoordinatorClient.maxInboundMessageBytes). Fail fast with a clean 413 here — - // before the balance reservation, so there's nothing to refund — rather than - // disconnecting a provider mid-flight. - if len(rawBody) > maxInferenceBodyBytes { - writeJSON(w, http.StatusRequestEntityTooLarge, errorResponse("invalid_request_error", - fmt.Sprintf("request body exceeds the %d-byte limit", maxInferenceBodyBytes))) - return - } - // Per-account token rate limiting (ITPM/OTPM) — the industry-standard // token throttle alongside RPM. Charged upfront from the input estimate // and the bounded max_tokens (OpenAI-style). Runs before the balance @@ -1529,9 +1515,9 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", err.Error())) return } - rawBody, _ = json.Marshal(providerParsed) + rawBody, _ = marshalForwardBody(providerParsed) } else { - rawBody, _ = json.Marshal(parsed) + rawBody, _ = marshalForwardBody(parsed) } candidateCount, capacityRejections, modelTooLarge = s.registry.QuickCapacityCheck(model, estimatedPromptTokens, requestedMaxTokens, registry.RequestTraits{HasTools: hasTools}, allowedProviderSerials...) } @@ -1597,6 +1583,25 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { consumerLocation := s.requestLocation(r) deadline := ttftDeadline(estimatedPromptTokens) + // Final cap on the body we'll seal. The read cap (parseInferencePrelude) + // bounded the request as received, but rawBody has since been re-marshaled at + // several points — alias resolution, allowlist/routing-field stripping, + // reasoning_parser + max_tokens injection, Responses→chat lowering, and the + // alias-capacity fallback above. The coordinator seals this body and sends it + // as ONE WebSocket frame; a body over the cap produces a frame the provider + // rejects by tearing down its session and cancelling every unrelated in-flight + // request (see maxInferenceBodyBytes / CoordinatorClient.maxInboundMessageBytes). + // This is the single point where rawBody is frozen into dispatchState, so the + // check here covers every upstream mutation; an oversized request gets a clean + // 413 instead of disconnecting a provider mid-flight. The reservation is held + // at this point, so refund before returning. + if len(rawBody) > maxInferenceBodyBytes { + refundReservation() + writeJSON(w, http.StatusRequestEntityTooLarge, errorResponse("invalid_request_error", + fmt.Sprintf("request body exceeds the %d-byte limit", maxInferenceBodyBytes))) + return + } + d := &dispatchState{ s: s, w: w, diff --git a/coordinator/api/inference_body_remarshal_integration_test.go b/coordinator/api/inference_body_remarshal_integration_test.go new file mode 100644 index 0000000000..689bfef14d --- /dev/null +++ b/coordinator/api/inference_body_remarshal_integration_test.go @@ -0,0 +1,130 @@ +package api + +// Regression guard for the forward-body re-marshal inflation gap. +// +// The chat handler re-marshals the parsed request body at several points before +// sealing it to a provider — including the alias-capacity fallback, which +// switches a saturated desired build to its previous build and re-serializes the +// body. If that re-marshal uses encoding/json's default Marshal, the bytes '<' +// '>' '&' are HTML-escaped into 6-byte \uXXXX forms (a ~6x inflation), so a +// benign request that fit the read cap can balloon past the provider's +// single-frame WebSocket limit and tear down its session. marshalForwardBody +// disables that escaping at every forward-marshal site; this test drives a real +// request through the alias-capacity fallback and asserts the body the provider +// actually receives is unescaped — failing if any fallback marshal site +// regresses to json.Marshal. + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestAliasCapacityFallbackForwardsUnescapedBody(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{AdminKey: "test-key"}) + reg := registry.New(logger) + srv := NewServer(reg, st, ServerConfig{}, logger) + // Keep the challenge ticker quiet for the test window: the saturated desired + // provider is registered with a nil conn (it never receives a dispatch) and + // shouldn't be challenged over the wire. + srv.challengeInterval = 30 * time.Second + ts := httptest.NewServer(srv.Handler()) + t.Cleanup(ts.Close) + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + + const ( + alias = "gemma-4-fallback" + desiredBuild = "build-desired-saturated" + prevBuild = "build-previous-routable" + ) + + // Desired build: a registered, trusted, SATURATED provider. The alias + // resolves to desired (structural), but QuickCapacityCheck(desired) returns + // 0 candidates / >0 rejections — the exact condition that fires + // maybeFallbackAliasCapacity. nil conn is fine: it never receives a dispatch. + registerBuildsProvider(srv, "p-desired", desiredBuild) + pd := reg.GetProvider("p-desired") + pd.Mu().Lock() + pd.BackendCapacity.Slots[0].ActiveTokenBudgetUsed = 1_000 + pd.BackendCapacity.Slots[0].ActiveTokenBudgetMax = 1_000 + pd.Mu().Unlock() + + // Previous build: a real failover provider that decrypts and captures the + // forwarded body, then serves the request so the HTTP call completes cleanly. + prev := startFailoverProvider(t, ctx, ts, reg, failoverProviderConfig{ + Name: "p-prev", Version: "0.6.4", DecodeTPS: 100, + Models: []failoverModelSpec{{ID: prevBuild}}, + Script: fullServeScript(prevBuild), + }) + + reg.SetModelAliases(map[string]registry.AliasTarget{ + alias: {Desired: desiredBuild, Previous: prevBuild}, + }) + + // Sanity: desired is saturated, previous is routable — so the request must + // take the fallback to reach a provider at all. + if c, rej, _ := reg.QuickCapacityCheck(desiredBuild, 10, 64, registry.RequestTraits{}); c != 0 || rej == 0 { + t.Fatalf("desired capacity = %d candidates / %d rejections, want 0 / >0 (saturated)", c, rej) + } + if c, _, _ := reg.QuickCapacityCheck(prevBuild, 10, 64, registry.RequestTraits{}); c == 0 { + t.Fatal("previous build has no routable capacity (candidates=0); fallback would have nothing to switch to") + } + + // A '<'-heavy prompt: each '<' is a benign 1 byte unescaped but a 6-byte + // < under default HTML escaping. The run is sized so that EVEN THE + // ESCAPED body (~6x) still fits the test WebSocket's 32 KiB default read + // limit — so on the buggy (escaping) path the body reaches the provider WITH + // < in it and the content assertion below is the clean discriminator, + // rather than a frame-too-large disconnect. (In production the provider limit + // is 32 MiB; the freeze-point cap covers genuinely oversized bodies.) + const angleRun = 2048 // 2 KiB of '<'; ~12 KiB escaped, ~16 KiB sealed frame + content := strings.Repeat("<", angleRun) + chatBody := fmt.Sprintf( + `{"model":%q,"messages":[{"role":"user","content":%q}],"stream":true,"max_tokens":64}`, + alias, content) + + status, respBody, err := postChat(ctx, ts.URL, "test-key", chatBody) + if err != nil { + t.Fatalf("chat request: %v", err) + } + if status != http.StatusOK { + t.Fatalf("status = %d, want 200 (fallback should route to the previous build); body = %s", status, respBody) + } + + // Inspect the body the provider actually received post-fallback. + var got []byte + select { + case got = <-prev.bodies: + case <-time.After(5 * time.Second): + t.Fatal("previous provider never received a dispatch — the fallback did not route here") + } + if got == nil { + t.Fatal("previous provider could not decrypt the forwarded body") + } + + // The 6-byte JSON escape for '<' is the ASCII run \ u 0 0 3 c. Its presence + // means a fallback marshal site regressed to the HTML-escaping json.Marshal. + if bytes.Contains(got, []byte{'\\', 'u', '0', '0', '3', 'c'}) { + t.Fatal("forwarded body HTML-escaped '<' to \\u003c — an alias-capacity fallback re-marshal regressed to json.Marshal") + } + if !bytes.Contains(got, bytes.Repeat([]byte("<"), 64)) { + t.Fatalf("forwarded body is missing the raw '<' run (len=%d)", len(got)) + } + // The unescaped body tracks the input; the escaped form would be ~6x larger. + if len(got) > angleRun+8192 { + t.Fatalf("forwarded body unexpectedly large: %d bytes (input ~%d) — inflation suggests escaping crept back in", len(got), angleRun) + } +}