Repository navigation
fix(coordinator): cap plaintext inference request body #338
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
39e8692
a618f78
520a35a
8f66c24
9a042c0
0b3e3d0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<Message, "role" | "content" | "images">[] | ||
| ): 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), | ||
| }]; | ||
| }); | ||
| } | ||
|
Comment on lines
21
to
+36
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 [MEDIUM] 🧩 Complex message filtering logic could be simplified with a single pass 💡 Suggestion: Consider a single-pass approach that identifies the newest image index while building the result array, avoiding the separate findNewestImageMessageIndex function and reverse iteration 📊 Score: 3×4 = 12 · Category: over-abstraction
anupsv marked this conversation as resolved.
Resolved
anupsv marked this conversation as resolved.
Resolved
|
||
|
|
||
| function findNewestImageMessageIndex( | ||
| messages: Pick<Message, "images">[] | ||
| ): number { | ||
| let index = messages.length; | ||
| for (const message of [...messages].reverse()) { | ||
| index -= 1; | ||
| if (message.images && message.images.length > 0) { | ||
| return index; | ||
| } | ||
| } | ||
| return -1; | ||
| } | ||
|
Comment on lines
+38
to
49
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 [INFO] 🧩 Reverse iteration with manual index tracking is unnecessarily complex 💡 Suggestion: Use a simple forward loop with lastImageIndex variable: for (let i = 0; i < messages.length; i++) { if (messages[i].images?.length > 0) lastImageIndex = i; } 📊 Score: 2×3 = 6 · Category: why not simpler
anupsv marked this conversation as resolved.
Resolved
anupsv marked this conversation as resolved.
Resolved
anupsv marked this conversation as resolved.
Resolved
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "io" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| // 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 | ||
| // asserts 413, so it fails on the unpatched code. | ||
| func TestParseInferencePreludeRejectsOversizedBody(t *testing.T) { | ||
| s := &Server{} | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 [INFO] 🧩 Unnecessary variable assignment for single-use expression 💡 Suggestion: Inline the io.LimitReader call directly in httptest.NewRequest instead of assigning to body variable 📊 Score: 1×2 = 2 · Category: over-abstraction |
||
| 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) | ||
| } | ||
| } | ||
|
|
||
| // 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) | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.