Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 44 additions & 4 deletions console-ui/src/lib/chat-messages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Message, "role" | "content"> & Partial<Message>): Message {
return { id: "x", timestamp: 0, ...partial };
}
Expand All @@ -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 } },
],
},
]);
Expand All @@ -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 } }],
},
]);
});
});
40 changes: 33 additions & 7 deletions console-ui/src/lib/chat-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`),
Expand All @@ -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 thread
anupsv marked this conversation as resolved.
Resolved
}
Comment on lines 21 to +36

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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

Comment thread
anupsv marked this conversation as resolved.
Resolved
Comment thread
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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

Comment thread
anupsv marked this conversation as resolved.
Resolved
Comment thread
anupsv marked this conversation as resolved.
Resolved
Comment thread
anupsv marked this conversation as resolved.
Resolved
64 changes: 64 additions & 0 deletions coordinator/api/inference_body_cap_test.go
Original file line number Diff line number Diff line change
@@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Custom infiniteReader reimplements functionality available in stdlib

💡 Suggestion: Use strings.NewReader(strings.Repeat("a", maxInferenceBodyBytes+1)) or bytes.NewReader with a pre-allocated slice instead of custom infiniteReader type

📊 Score: 2×3 = 6 · Category: reinventing stdlib

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Custom infiniteReader when strings.Repeat could generate test data

💡 Suggestion: Replace infiniteReader with strings.Repeat('a', maxInferenceBodyBytes+1) for simpler test setup

📊 Score: 2×2 = 4 · Category: reinventing stdlib

}

// 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{}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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)
}
}
23 changes: 23 additions & 0 deletions coordinator/api/inference_preprocess.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,25 @@ 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 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
Comment thread
anupsv marked this conversation as resolved.
Resolved

// 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).
Expand All @@ -36,8 +50,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)
Comment on lines +91 to 92

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 [CRITICAL] ⚡ io.ReadAll with unbounded body could cause OOM attacks

💡 Suggestion: The fix correctly adds http.MaxBytesReader to cap the body size before io.ReadAll - this prevents attackers from sending multi-GB bodies to exhaust coordinator memory

📊 Score: 5×5 = 25 · Category: Unbounded allocations

Comment on lines +91 to 92

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 [CRITICAL] ⚡ io.ReadAll with unbounded body could cause OOM attacks

💡 Suggestion: Add http.MaxBytesReader wrapper before io.ReadAll (already implemented in this diff)

📊 Score: 5×5 = 25 · Category: Unbounded allocations

Comment thread
anupsv marked this conversation as resolved.
Resolved
Comment thread
anupsv marked this conversation as resolved.
Resolved
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
}
Expand Down
Loading