From e8e164c7c499883eabc46774d7d364eb8913b952 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Thu, 1 Oct 2026 07:07:25 -0700 Subject: [PATCH] fix(console): reject oversized composed chat requests before send --- CHANGELOG.md | 4 + .../useChatStream.request-budget.test.ts | 106 +++++++++ console-ui/src/lib/chat-messages.ts | 8 +- .../src/lib/chat/request-budget.test.ts | 34 +++ console-ui/src/lib/chat/request-budget.ts | 26 ++ console-ui/src/lib/chat/stream-budget.test.ts | 222 ++++++++++++++++++ console-ui/src/lib/chat/stream.ts | 13 +- .../api/sender_encryption_budget_test.go | 68 ++++++ docs/architecture/security/encryption.md | 3 +- docs/consumer/quickstart.md | 3 +- docs/reference/api-contracts.md | 1 + 11 files changed, 480 insertions(+), 8 deletions(-) create mode 100644 console-ui/src/hooks/useChatStream.request-budget.test.ts create mode 100644 console-ui/src/lib/chat/request-budget.test.ts create mode 100644 console-ui/src/lib/chat/request-budget.ts create mode 100644 console-ui/src/lib/chat/stream-budget.test.ts create mode 100644 coordinator/api/sender_encryption_budget_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index a586030e5d..ff12b2a604 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased — console chat request budget + +- Refuse oversized chat requests locally with guidance to reduce images or conversation length. Check the full UTF-8 request and optional encrypted envelope before sending, retain the user's message and images, and apply the same check on retry. Existing per-file and image-count limits remain unchanged. + ## Release candidate v0.9.15 — automatic MiMo calibration (not shipped) - Calibrate idle native MiMo engines after model loading and refresh stale phase evidence with uncached built-in prompts. Measure short and 4k text plus affordable batches within the existing concurrency cap; retain the production MTP and memory configuration. diff --git a/console-ui/src/hooks/useChatStream.request-budget.test.ts b/console-ui/src/hooks/useChatStream.request-budget.test.ts new file mode 100644 index 0000000000..cbcecf3701 --- /dev/null +++ b/console-ui/src/hooks/useChatStream.request-budget.test.ts @@ -0,0 +1,106 @@ +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { useChatStream } from "./useChatStream"; +import { useStore } from "@/lib/store"; +import { useToastStore } from "./useToast"; +import { setEncryptionEnabled } from "@/lib/encryption"; + +vi.mock("@/lib/google-analytics", () => ({ trackEvent: vi.fn() })); + +beforeEach(() => { + localStorage.clear(); + setEncryptionEnabled(false); + useStore.setState({ chats: [], activeChatId: null, selectedModel: "fixture-vision-model", models: [], useMyMachine: false }); + useToastStore.setState({ toasts: [] }); + vi.stubGlobal("fetch", vi.fn(async () => new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }))); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + useStore.setState({ chats: [], activeChatId: null }); + useToastStore.setState({ toasts: [] }); +}); + +describe("chat send and retry budget lifecycle", () => { + it("retains user images and text when send and retry are refused locally", async () => { + const data = `data:image/jpeg;base64,${Buffer.alloc(7 * 1024 * 1024).toString("base64")}`; + const images = [data, data]; + const text = "describe my images"; + const { result } = renderHook(() => useChatStream()); + await act(async () => { await result.current.handleSend(text, images); }); + const messages = useStore.getState().chats[0].messages; + expect(messages[0].content).toBe(text); + expect(messages[0].images).toEqual(images); + expect(messages[1].error).toBe(true); + expect(messages[1].streaming).toBe(false); + expect(messages[1].content).toMatch(/too large/i); + expect(result.current.isStreaming).toBe(false); + expect(fetch).not.toHaveBeenCalled(); + expect(useToastStore.getState().toasts).toHaveLength(1); + + act(() => result.current.handleRetry(messages[1].id)); + await waitFor(() => expect(result.current.isStreaming).toBe(false)); + const retried = useStore.getState().chats[0].messages; + expect(retried).toHaveLength(2); + expect(retried[0].content).toBe(text); + expect(retried[0].images).toEqual(images); + expect(retried[1].error).toBe(true); + expect(retried[1].streaming).toBe(false); + expect(retried[1].content).toMatch(/too large/i); + expect(useToastStore.getState().toasts).toHaveLength(2); + expect(fetch).not.toHaveBeenCalled(); + }); + + it("keeps newest-image history pruning and permits a valid send", async () => { + const chatId = useStore.getState().createChat(); + const oldImage = `data:image/jpeg;base64,${Buffer.alloc(10 * 1024 * 1024).toString("base64")}`; + useStore.getState().addMessage(chatId, { id: "old", role: "user", content: "old image", images: [oldImage], timestamp: 0 }); + const currentImage = "data:image/png;base64,AQID"; + const { result } = renderHook(() => useChatStream()); + await act(async () => { await result.current.handleSend("new image", [currentImage]); }); + expect(fetch).toHaveBeenCalledTimes(1); + const [, init] = vi.mocked(fetch).mock.calls[0]; + const sent = JSON.parse(init?.body as string); + expect(sent.messages[0].role).toBe("system"); + expect(sent.messages[1]).toEqual({ role: "user", content: "old image" }); + expect(JSON.stringify(sent)).not.toContain(oldImage); + expect(JSON.stringify(sent)).toContain(currentImage); + expect(useStore.getState().chats[0].messages[0].images).toEqual([oldImage]); + expect(result.current.isStreaming).toBe(false); + expect(useToastStore.getState().toasts).toHaveLength(0); + }); + + it("rechecks current encryption and model settings with pruned retry history", async () => { + const chatId = useStore.getState().createChat(); + const oldImage = "data:image/png;base64,AQID"; + useStore.getState().addMessage(chatId, { id: "old", role: "user", content: "old image", images: [oldImage], timestamp: 0 }); + const currentImage = `data:image/jpeg;base64,${Buffer.alloc(10 * 1024 * 1024).toString("base64")}`; + const { result } = renderHook(() => useChatStream()); + await act(async () => { await result.current.handleSend("new image", [currentImage]); }); + const assistantId = useStore.getState().chats[0].messages[2].id; + expect(fetch).toHaveBeenCalledTimes(1); + + vi.mocked(fetch).mockClear(); + setEncryptionEnabled(true); + act(() => result.current.handleRetry(assistantId)); + await waitFor(() => expect(result.current.isStreaming).toBe(false)); + expect(fetch).not.toHaveBeenCalled(); + expect(useStore.getState().chats[0].messages[2].content).toMatch(/too large/i); + expect(useStore.getState().chats[0].messages[1].images).toEqual([currentImage]); + + setEncryptionEnabled(false); + useStore.setState({ selectedModel: "current-retry-model" }); + act(() => result.current.handleRetry(assistantId)); + await waitFor(() => expect(result.current.isStreaming).toBe(false)); + expect(fetch).toHaveBeenCalledTimes(1); + const sent = JSON.parse(vi.mocked(fetch).mock.calls[0][1]?.body as string); + expect(sent.model).toBe("current-retry-model"); + expect(sent.messages[0].role).toBe("system"); + expect(sent.messages[1]).toEqual({ role: "user", content: "old image" }); + expect(JSON.stringify(sent)).not.toContain(oldImage); + expect(JSON.stringify(sent)).toContain(currentImage); + expect(useStore.getState().chats[0].messages[2].error).toBe(false); + }); +}); diff --git a/console-ui/src/lib/chat-messages.ts b/console-ui/src/lib/chat-messages.ts index adb5d3e58d..103457509d 100644 --- a/console-ui/src/lib/chat-messages.ts +++ b/console-ui/src/lib/chat-messages.ts @@ -8,10 +8,10 @@ import { buildApiContent } from "./image-upload"; * 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. + * Only the newest image turn is sent upstream; older images remain visible + * in chat state. Even one image turn can exceed the coordinator's 16 MiB body + * cap after base64 and optional sealing. streamChat checks the complete + * serialized request and sealed envelope before sending. * * NOTE: `m.images` is undefined for turns restored from persistence (images are * stripped from localStorage to protect the quota — see store.ts `partialize`), diff --git a/console-ui/src/lib/chat/request-budget.test.ts b/console-ui/src/lib/chat/request-budget.test.ts new file mode 100644 index 0000000000..f5f1538d41 --- /dev/null +++ b/console-ui/src/lib/chat/request-budget.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; +import { sealRawRequest } from "../encryption"; +import nacl from "tweetnacl"; +import { assertChatRequestBudget, ChatRequestTooLargeError } from "./request-budget"; + +const LIMIT = 16 * 1024 * 1024; + +describe("chat request byte budget", () => { + it("accepts the exact plaintext cap and refuses one additional UTF-8 byte", () => { + expect(() => assertChatRequestBudget("a".repeat(LIMIT))).not.toThrow(); + expect(() => assertChatRequestBudget("a".repeat(LIMIT + 1))).toThrow(ChatRequestTooLargeError); + }); + + it("counts multibyte text rather than UTF-16 code units", () => { + expect(() => assertChatRequestBudget("雪".repeat(Math.floor(LIMIT / 3) + 1))).toThrow(ChatRequestTooLargeError); + }); + + it("uses only a lower bound before sealing, leaving metadata to the final check", () => { + // This ciphertext alone fits exactly, although its envelope cannot fit. + const largestCiphertextOnlyBody = 3 * (LIMIT / 4) - 24 - 16; + expect(() => assertChatRequestBudget("a".repeat(largestCiphertextOnlyBody), true)).not.toThrow(); + expect(() => assertChatRequestBudget("a".repeat(largestCiphertextOnlyBody + 1), true)).toThrow(ChatRequestTooLargeError); + }); + + it.each([0, 1, 2])("matches real NaCl/base64 padding for remainder %i", (remainder) => { + const body = new TextEncoder().encode("雪".repeat(5) + "a".repeat(remainder)); + const key = nacl.box.keyPair(); + const sealed = sealRawRequest(body, { kid: '"雪\\key', publicKey: key.publicKey }); + const envelope = JSON.parse(sealed.envelopeJson); + expect(envelope.ciphertext.length).toBe(4 * Math.ceil((body.byteLength + 24 + 16) / 3)); + expect(envelope.ciphertext.length).toBeLessThan(new TextEncoder().encode(sealed.envelopeJson).byteLength); + expect(() => assertChatRequestBudget(sealed.envelopeJson)).not.toThrow(); + }); +}); diff --git a/console-ui/src/lib/chat/request-budget.ts b/console-ui/src/lib/chat/request-budget.ts new file mode 100644 index 0000000000..58d016cae2 --- /dev/null +++ b/console-ui/src/lib/chat/request-budget.ts @@ -0,0 +1,26 @@ +import nacl from "tweetnacl"; + +// Matches the coordinator's plaintext and sender-sealed transport body caps. +// Later coordinator rewrites still have their own authoritative size checks. +export const MAX_CHAT_REQUEST_BYTES = 16 * 1024 * 1024; + +export class ChatRequestTooLargeError extends Error { + constructor() { + super("This message is too large to send. Use fewer or smaller images, shorten the conversation, or start a new chat."); + this.name = "ChatRequestTooLargeError"; + } +} + +/** Check serialized UTF-8 bytes, including the full history and request options. */ +export function assertChatRequestBudget(body: string, willSeal = false): void { + const bytes = new TextEncoder().encode(body).byteLength; + if (bytes > MAX_CHAT_REQUEST_BYTES) throw new ChatRequestTooLargeError(); + + // A proven lower bound before fetching a key or allocating ciphertext: + // base64(nonce || authenticated ciphertext), excluding all envelope metadata. + // A fitting lower bound still requires a check of the actual sealed envelope. + const ciphertextBytes = bytes + nacl.box.nonceLength + nacl.box.overheadLength; + if (willSeal && 4 * Math.ceil(ciphertextBytes / 3) > MAX_CHAT_REQUEST_BYTES) { + throw new ChatRequestTooLargeError(); + } +} diff --git a/console-ui/src/lib/chat/stream-budget.test.ts b/console-ui/src/lib/chat/stream-budget.test.ts new file mode 100644 index 0000000000..750a06cded --- /dev/null +++ b/console-ui/src/lib/chat/stream-budget.test.ts @@ -0,0 +1,222 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import nacl from "tweetnacl"; +import { streamChat } from "./stream"; +import { POST } from "@/app/api/chat/route"; +import { setEncryptionEnabled, SEALED_CONTENT_TYPE } from "../encryption"; +import { toApiMessages } from "../chat-messages"; +import type { ChatMessage, StreamCallbacks } from "../api/types"; + +const LIMIT = 16 * 1024 * 1024; +const MIB = 1024 * 1024; +const MODEL = "fixture-vision-model"; +const encoder = new TextEncoder(); +const key = nacl.box.keyPair(); +let kid = "0123456789abcdef"; +let keyCalls = 0; +let chatCalls = 0; +let upstreamCalls = 0; +let sentBody = ""; +let sentHeaders: Headers; +let sentSignal: AbortSignal | null | undefined; +let openedBody = ""; + +function callbacks(): StreamCallbacks { + return { onToken: vi.fn(), onThinking: vi.fn(), onMetrics: vi.fn(), onDone: vi.fn(), onError: vi.fn() }; +} + +function image(bytes: number): string { + return `data:image/jpeg;base64,${Buffer.alloc(bytes).toString("base64")}`; +} + +function requestJson(messages: ChatMessage[], model = MODEL): string { + return JSON.stringify({ model, messages, stream: true, enable_thinking: true }); +} + +function textMessagesAtBytes(bytes: number): ChatMessage[] { + const empty: ChatMessage[] = [{ role: "user", content: "" }]; + const overhead = encoder.encode(requestJson(empty)).byteLength; + return [{ role: "user", content: "a".repeat(bytes - overhead) }]; +} + +function expectSizeError(cb: StreamCallbacks) { + expect(cb.onError).toHaveBeenCalledTimes(1); + expect(vi.mocked(cb.onError).mock.calls[0][0]).toMatch(/too large/i); + expect(vi.mocked(cb.onError).mock.calls[0][0]).toMatch(/image|shorten|reduce/i); + expect(vi.mocked(cb.onError).mock.calls[0][0]).not.toMatch(/encryption setup failed|disable.*encrypt/i); + expect(cb.onDone).not.toHaveBeenCalled(); +} + +beforeEach(() => { + localStorage.clear(); + setEncryptionEnabled(false); + kid = "0123456789abcdef"; + keyCalls = chatCalls = upstreamCalls = 0; + sentBody = openedBody = ""; + sentSignal = undefined; + vi.stubGlobal("fetch", vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => { + if (url === "/api/encryption-key") { + keyCalls++; + return Response.json({ kid, public_key: Buffer.from(key.publicKey).toString("base64"), algorithm: "x25519-nacl-box" }); + } + if (url === "/api/chat") { + chatCalls++; + sentBody = init?.body as string; + sentHeaders = new Headers(init?.headers); + sentSignal = init?.signal; + // Run the real Next POST handler, including sealed byte pass-through. + return POST(new NextRequest("https://console.invalid/api/chat", { ...init, signal: init?.signal ?? undefined })); + } + expect(String(url)).toMatch(/\/v1\/chat\/completions$/); + upstreamCalls++; + const actual = typeof init?.body === "string" ? init.body : new TextDecoder().decode(init?.body as Uint8Array); + expect(actual).toBe(sentBody); + if (sentHeaders.get("content-type") === SEALED_CONTENT_TYPE) { + const envelope = JSON.parse(actual); + const sealed = new Uint8Array(Buffer.from(envelope.ciphertext, "base64")); + const pub = new Uint8Array(Buffer.from(envelope.ephemeral_public_key, "base64")); + const opened = nacl.box.open(sealed.subarray(24), sealed.subarray(0, 24), pub, key.secretKey); + expect(opened).not.toBeNull(); + openedBody = new TextDecoder().decode(opened!); + } + return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }); + })); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe("chat transport byte budget", () => { + it.each([2, 4])("refuses %i accepted large images before any request", async (count) => { + const bytes = count === 2 ? 7 * MIB : 10 * MIB; + const messages = toApiMessages([{ role: "user", content: "describe", images: Array.from({ length: count }, () => image(bytes)) }]); + expect(encoder.encode(requestJson(messages)).byteLength).toBeGreaterThan(LIMIT); + const cb = callbacks(); + await streamChat(messages, MODEL, cb); + expect(chatCalls).toBe(0); + expect(keyCalls).toBe(0); + expectSizeError(cb); + }); + + it("preserves a valid single 10 MiB plaintext image, headers, and abort signal", async () => { + const messages = toApiMessages([{ role: "user", content: "describe", images: [image(10 * MIB)] }]); + localStorage.setItem("darkbloom_api_key", "fixture-only-key"); + const abort = new AbortController(); + const cb = callbacks(); + await streamChat(messages, MODEL, cb, abort.signal, { selfRoute: true }); + expect(chatCalls).toBe(1); + expect(upstreamCalls).toBe(1); + expect(sentBody).toBe(requestJson(messages)); + expect(sentHeaders.get("x-api-key")).toBe("fixture-only-key"); + expect(sentHeaders.get("x-darkbloom-route")).toBe("prefer"); + expect(sentSignal).toBe(abort.signal); + expect(cb.onError).not.toHaveBeenCalled(); + expect(cb.onDone).toHaveBeenCalledTimes(1); + }); + + it.each([0, 1])("enforces the plaintext cap with %i extra byte", async (extra) => { + const messages = textMessagesAtBytes(LIMIT + extra); + const cb = callbacks(); + await streamChat(messages, MODEL, cb); + expect(chatCalls).toBe(extra === 0 ? 1 : 0); + if (extra) expectSizeError(cb); + else expect(encoder.encode(sentBody).byteLength).toBe(LIMIT); + }); + + it("counts UTF-8 history and options rather than JavaScript string length", async () => { + const messages: ChatMessage[] = [ + { role: "system", content: "💡".repeat(3 * MIB) }, + { role: "user", content: "é".repeat(3 * MIB) }, + ]; + expect(requestJson(messages).length).toBeLessThan(LIMIT); + expect(encoder.encode(requestJson(messages)).byteLength).toBeGreaterThan(LIMIT); + const cb = callbacks(); + await streamChat(messages, MODEL, cb, undefined, { enableThinking: false }); + expect(chatCalls).toBe(0); + expectSizeError(cb); + }); + + it("refuses a 10 MiB image with sender encryption before fetching a key", async () => { + setEncryptionEnabled(true); + const messages = toApiMessages([{ role: "user", content: "describe", images: [image(10 * MIB)] }]); + const cb = callbacks(); + await streamChat(messages, MODEL, cb); + expect(keyCalls).toBe(0); + expect(chatCalls).toBe(0); + expectSizeError(cb); + }); + + it("seals and forwards a valid small request with real NaCl and the real proxy", async () => { + setEncryptionEnabled(true); + kid = 'rotation-"雪"\\key'; + const messages: ChatMessage[] = [{ role: "user", content: [{ type: "text", text: 'hello <>&\u2028💡' }, { type: "image_url", image_url: { url: image(1024) } }] }]; + const cb = callbacks(); + await streamChat(messages, MODEL, cb); + expect(keyCalls).toBe(1); + expect(chatCalls).toBe(1); + expect(upstreamCalls).toBe(1); + expect(openedBody).toBe(requestJson(messages)); + expect(JSON.parse(sentBody).kid).toBe(kid); + expect(cb.onError).not.toHaveBeenCalled(); + }); + + it.each([0, 1])("checks the actual sealed envelope at the cap plus %i plaintext byte", async (extra) => { + setEncryptionEnabled(true); + // Independent codec arithmetic: 112 JSON/key bytes for a 16-character kid, + // 24 nonce bytes and 16 authentication bytes, then base64 groups of four. + const maxPlaintext = 3 * ((LIMIT - 112) / 4) - 40; + const messages = textMessagesAtBytes(maxPlaintext + extra); + const cb = callbacks(); + await streamChat(messages, MODEL, cb); + expect(keyCalls).toBe(1); // optimistic lower bound requires actual metadata + expect(chatCalls).toBe(extra === 0 ? 1 : 0); + if (extra) expectSizeError(cb); + else { + expect(encoder.encode(sentBody).byteLength).toBe(LIMIT); + expect(openedBody).toBe(requestJson(messages)); + } + }); + + it.each([0, 1])("accounts for escaped Unicode key metadata at the cap plus %i plaintext byte", async (extra) => { + setEncryptionEnabled(true); + kid = 'rotation-"雪"\\key'; + const overhead = () => encoder.encode(JSON.stringify({ + kid, ephemeral_public_key: "a".repeat(44), ciphertext: "", + })).byteLength; + // Align metadata to a base64 group so the accepted case is exactly at cap. + while (overhead() % 4 !== 0) kid += "a"; + const messages = textMessagesAtBytes(3 * ((LIMIT - overhead()) / 4) - 40 + extra); + const cb = callbacks(); + await streamChat(messages, MODEL, cb); + expect(keyCalls).toBe(1); + expect(chatCalls).toBe(extra === 0 ? 1 : 0); + if (extra) expectSizeError(cb); + else { + expect(encoder.encode(sentBody).byteLength).toBe(LIMIT); + expect(JSON.parse(sentBody).kid).toBe(kid); + expect(openedBody).toBe(requestJson(messages)); + } + }); + + it("preserves a valid four-image request and the thinking override", async () => { + const messages = toApiMessages([{ role: "user", content: "describe", images: [image(1), image(2), image(3), image(4)] }]); + const cb = callbacks(); + await streamChat(messages, MODEL, cb, undefined, { enableThinking: false }); + expect(chatCalls).toBe(1); + expect(JSON.parse(sentBody)).toEqual({ model: MODEL, messages, stream: true, enable_thinking: false }); + expect(cb.onError).not.toHaveBeenCalled(); + }); + + it("retains the existing encryption setup error for key-service failures", async () => { + setEncryptionEnabled(true); + vi.mocked(fetch).mockResolvedValueOnce(new Response("", { status: 503 })); + const cb = callbacks(); + await streamChat([{ role: "user", content: "hello" }], MODEL, cb); + expect(fetch).toHaveBeenCalledTimes(1); + expect(chatCalls).toBe(0); + expect(cb.onError).toHaveBeenCalledTimes(1); + expect(vi.mocked(cb.onError).mock.calls[0][0]).toMatch(/Encryption setup failed/); + }); +}); diff --git a/console-ui/src/lib/chat/stream.ts b/console-ui/src/lib/chat/stream.ts index 88faac8b01..d9271ed09f 100644 --- a/console-ui/src/lib/chat/stream.ts +++ b/console-ui/src/lib/chat/stream.ts @@ -23,6 +23,7 @@ import type { } from "../api/types"; import { ThinkStreamParser } from "./think-parser"; import { readSsePayloads } from "./sse"; +import { assertChatRequestBudget, ChatRequestTooLargeError } from "./request-budget"; import { parseVerification } from "../verification"; @@ -100,11 +101,15 @@ async function prepareBody( requestBody: unknown, selfRouteHeader: Record, ): Promise<{ headers: Record; body: string; sealCtx: SealContext | null }> { - if (!isEncryptionEnabled()) { - return { headers: proxyHeaders(selfRouteHeader), body: JSON.stringify(requestBody), sealCtx: null }; + const body = JSON.stringify(requestBody); + const willSeal = isEncryptionEnabled(); + assertChatRequestBudget(body, willSeal); + if (!willSeal) { + return { headers: proxyHeaders(selfRouteHeader), body, sealCtx: null }; } const coordKey = await getCoordinatorKey(); const sealed = sealRequest(requestBody, coordKey); + assertChatRequestBudget(sealed.envelopeJson); return { headers: proxyHeaders({ "Content-Type": SEALED_CONTENT_TYPE, ...selfRouteHeader }), body: sealed.envelopeJson, @@ -133,6 +138,10 @@ export async function streamChat( try { ({ headers, body, sealCtx } = await prepareBody(requestBody, selfRouteHeader)); } catch (err) { + if (err instanceof ChatRequestTooLargeError) { + callbacks.onError(err.message); + return; + } callbacks.onError( `Encryption setup failed: ${err instanceof Error ? err.message : String(err)} — disable "Encrypt to coordinator" in Settings to continue in plaintext.`, ); diff --git a/coordinator/api/sender_encryption_budget_test.go b/coordinator/api/sender_encryption_budget_test.go new file mode 100644 index 0000000000..a92b9bd23a --- /dev/null +++ b/coordinator/api/sender_encryption_budget_test.go @@ -0,0 +1,68 @@ +package api + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/eigeninference/d-inference/coordinator/internal/e2e" +) + +// The console's envelope guard must agree with the actual middleware read cap. +// Exercise real NaCl ciphertext and decryption without a provider or a listener. +func TestSealedRequest_BodyBudget(t *testing.T) { + key, err := e2e.DeriveCoordinatorKey(senderTestMnemonic) + if err != nil { + t.Fatal(err) + } + s := &Server{coordinatorKey: key} + const limit = 16 * 1024 * 1024 + // A 16-character kid and 44-character ephemeral key add 112 JSON bytes. + const plaintextSize = 3*((limit-112)/4) - 24 - 16 + prefix := []byte(`{"model":"fixture","messages":[{"role":"user","content":"`) + suffix := []byte(`"}]}`) + plaintext := append(prefix, bytes.Repeat([]byte("a"), plaintextSize-len(prefix)-len(suffix))...) + plaintext = append(plaintext, suffix...) + envelope, _, _ := sealRequest(t, plaintext, key.PublicKey, key.KID) + if len(envelope) != limit { + t.Fatalf("sealed fixture = %d bytes, want %d", len(envelope), limit) + } + + for _, extra := range []int{0, 1} { + name := "exact_cap" + if extra != 0 { + name = "one_byte_over" + } + t.Run(name, func(t *testing.T) { + body := envelope + if extra != 0 { + // Valid trailing JSON whitespace isolates the read cap from parsing. + body = append(append([]byte(nil), envelope...), ' ') + } + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + req.Header.Set("Content-Type", SealedContentType) + rec := httptest.NewRecorder() + called := false + s.sealedTransport(func(w http.ResponseWriter, r *http.Request) { + called = true + got, err := io.ReadAll(r.Body) + if err != nil || !bytes.Equal(got, plaintext) { + t.Fatalf("plaintext mismatch: len=%d err=%v", len(got), err) + } + if !isSealedRequest(r) || r.Header.Get("Content-Type") != "application/json" { + t.Fatal("missing sealed handoff context or JSON content type") + } + w.WriteHeader(http.StatusOK) + })(rec, req) + if extra == 0 { + if !called || rec.Code != http.StatusOK { + t.Fatalf("exact-cap envelope: called=%v status=%d", called, rec.Code) + } + } else if called || rec.Code != http.StatusBadRequest || !bytes.Contains(rec.Body.Bytes(), []byte("invalid_request_error")) { + t.Fatalf("over-cap envelope: called=%v status=%d body=%s", called, rec.Code, rec.Body.String()) + } + }) + } +} diff --git a/docs/architecture/security/encryption.md b/docs/architecture/security/encryption.md index cee63147bb..d9df758967 100644 --- a/docs/architecture/security/encryption.md +++ b/docs/architecture/security/encryption.md @@ -1,6 +1,6 @@ # Encryption and privacy model -> Last updated: 2026-09-27 +> Last updated: 2026-10-01 An inference request crosses three NaCl Box hops: consumer → coordinator (optional), coordinator → provider (mandatory), provider → coordinator @@ -81,6 +81,7 @@ sequenceDiagram | Coordinator key | BIP39 mnemonic from `MNEMONIC` / `EIGENINFERENCE_MNEMONIC` ([configuration](../../reference/configuration.md#auth-admin-key-privy-release-key-sender-encryption)) → seed → HKDF-SHA256 with info `eigeninference-coordinator-e2e-v1` → X25519 private key; `kid` = first 16 hex chars of SHA-256(public key) | `coordinator/internal/e2e/coordinator_key.go` (`DeriveCoordinatorKey`, `CoordinatorKeyHKDFInfo`) | | Detection | `Content-Type: application/eigeninference-sealed+json` only (parameters ignored, case-insensitive); there is no marker header | `coordinator/api/sender_encryption.go` (`SealedContentType`, `isSealedContentType`) | | Request envelope | `{kid, ephemeral_public_key, ciphertext}`; `ciphertext` = base64(24-byte nonce ‖ `box.Seal` output); body read capped at the [inference body limit](../../reference/api-contracts.md#limits-and-validation) | `coordinator/api/sender_encryption.go` (`sealedRequestEnvelope`, `sealedTransport`) | +| Console preflight | Checks the full plaintext UTF-8 size and a ciphertext-only base64 lower bound before key discovery. Near the limit, key discovery and sealing may be needed; the actual serialized envelope is checked before the chat POST. A size refusal retains the encryption setting and reports how to reduce the request. Server body and rewrite checks remain authoritative | `console-ui/src/lib/chat/request-budget.ts` (`assertChatRequestBudget`), `console-ui/src/lib/chat/stream.ts` (`prepareBody`, `streamChat`) | | Errors | `400 invalid_request_error` (body unreadable / over cap), `400 invalid_sealed_envelope`, `400 kid_mismatch`, `400 decryption_failed`, `503 encryption_unavailable` | `coordinator/api/sender_encryption.go` (`sealedTransport`) | | Handoff | Plaintext is re-injected as `application/json` with `sealedCtxKey` on the request context; sealed requests refuse remote-media URL fetching (`isSealedRequest`) | `coordinator/api/sender_encryption.go` (`sealedTransport`, `isSealedRequest`); `coordinator/api/media_resolve.go` (`gateRemoteMediaPreDispatch`) | | Response | Sealed to the sender's `ephemeral_public_key` with the coordinator key. Non-streaming: body = `{kid, ciphertext}`. SSE: one sealed event per `\n\n` boundary, written as `data: \n\n`. Headers `X-Eigen-Sealed: true`, `X-Eigen-Sealed-Kid: ` | `coordinator/api/sender_encryption.go` (`sealingResponseWriter`, `sealedResponseEnvelope`) | diff --git a/docs/consumer/quickstart.md b/docs/consumer/quickstart.md index b6517316f8..6667275f0a 100644 --- a/docs/consumer/quickstart.md +++ b/docs/consumer/quickstart.md @@ -1,6 +1,6 @@ # Quickstart: first request in five steps -> Last updated: 2026-09-28 +> Last updated: 2026-10-01 Get an API key from the console, list the models your key can use, and make your first chat completion against `https://api.darkbloom.dev` — first with `curl`, then from the OpenAI and Anthropic SDKs. For developers integrating the API; each step is one action. Route details for everything used here are in [`../reference/api-contracts.md`](../reference/api-contracts.md). @@ -159,6 +159,7 @@ Direct accounts do not have the upstream first-content SLA. Allow enough time fo | Response | Cause | Fix | |---|---|---| +| Console: "This message is too large to send" | The complete chat request, including history and optional encryption, exceeds the [transport budget](../reference/api-contracts.md#limits-and-validation); valid individual uploads can exceed it together | Send fewer or smaller images, shorten the conversation, or start a new chat. The refused message and images remain in the current chat; retry checks the request again | | 400 `invalid_request_error` naming an output-token field | A negative or malformed `max_tokens`, `max_completion_tokens` or `max_output_tokens` | Use a positive integer bound or omit it for the coordinator default; null and zero retain default-bound behavior ([request contract](../reference/api-contracts.md#inference-4)) | | 401 `authentication_error` | `Authorization: Bearer` header missing, or the key is unknown, disabled, expired or revoked | Re-export the key; create or rotate one in the console ([`authentication.md`](authentication.md)) | | 402 | Balance or key budget cannot cover the worst-case reservation ([payment-required taxonomy](../architecture/billing.md#payment-required-responses)) | Deposit, or lower `max_tokens` ([`billing.md`](billing.md)) | diff --git a/docs/reference/api-contracts.md b/docs/reference/api-contracts.md index e37bbbf16b..2883d9904d 100644 --- a/docs/reference/api-contracts.md +++ b/docs/reference/api-contracts.md @@ -794,6 +794,7 @@ Built by `handleStreamingResponseWithFirstChunkAndError` (`coordinator/api/consu |---|---|---| | Global request body | 64 MiB ceiling on every request (`maxRequestBodyBytes`, `bodyLimitMiddleware`) | `coordinator/api/server.go` | | Inference body | 16 MiB (`maxInferenceBodyBytes`) → 413 `invalid_request_error`; sealed bodies are read with the same cap (400 `invalid_request_error` when exceeded) | `parseInferencePrelude` (`coordinator/api/inference_preprocess.go`), `sealedTransport` (`coordinator/api/sender_encryption.go`) | +| Console chat preflight | `MAX_CHAT_REQUEST_BYTES = 16 * 1024 * 1024`; send and retry measure the complete serialized UTF-8 body and, when encryption is enabled, the actual sealed envelope before `POST /api/chat`. Exactly at the cap is allowed. Oversized requests produce a local error and retain the user message/images in current chat state. Uploads still allow four images, each up to 10 MiB; base64, history and envelope overhead can make an accepted upload too large to send. Coordinator rewrite and final-forwarding checks remain authoritative | `assertChatRequestBudget` (`console-ui/src/lib/chat/request-budget.ts`), `streamChat` (`console-ui/src/lib/chat/stream.ts`), `useChatStream` (`console-ui/src/hooks/useChatStream.ts`) | | Control-plane bodies | 64 KiB (`maxControlPlaneBodyBytes`) for enroll, device token, admin auth | `coordinator/api/server.go` | | MDM webhook body | 1 MiB (`maxMDMWebhookBodyBytes`) | `HandleMDMWebhook` (`coordinator/api/server.go`) | | `n` | Must be 1 | `handleChatCompletions` |