diff --git a/CHANGELOG.md b/CHANGELOG.md index 18099e7b83..a8e3107eca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,6 +77,10 @@ - Apply current full Autopilot settings at each new scheduled window. Disabling between windows restores ordinary saved model selection even if unchanged; other runtime inputs remain frozen. - Queue pending-operation uncertainty before removing a disconnected provider, persisting outside registry/provider locks. Connection loss never implies rollback or a confirmed terminal resident set. +## 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. + ## Unreleased — canceled queue waiters - Stop canceled waiters held by a scheduling pass from returning as queued demand and occupying slots needed by fresh requests. Drop completed entries during queue pop and stale cleanup while preserving live FIFO order, timeout notifications, and reservation cleanup. 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/tests/api/inference/sender_encryption_budget_test.go b/coordinator/tests/api/inference/sender_encryption_budget_test.go new file mode 100644 index 0000000000..5f6f54ec04 --- /dev/null +++ b/coordinator/tests/api/inference/sender_encryption_budget_test.go @@ -0,0 +1,72 @@ +package inference_test + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "testing" + + inference "github.com/eigeninference/d-inference/coordinator/api/inference" + "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 := &inference.Owner{} + s.SetCoordinatorKey(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 r.Header.Get("Content-Type") != "application/json" { + t.Fatal("missing JSON content type on the sealed handoff") + } + w.WriteHeader(http.StatusOK) + })(rec, req) + if extra == 0 { + // The sealed response header is how a caller observes that the request + // took the sealed handoff rather than the plaintext bypass. + if !called || rec.Code != http.StatusOK || rec.Header().Get("X-Eigen-Sealed") != "true" { + t.Fatalf("exact-cap envelope: called=%v status=%d sealed=%q", called, rec.Code, rec.Header().Get("X-Eigen-Sealed")) + } + } 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 7252610f5e..ae97b64f73 100644 --- a/docs/architecture/security/encryption.md +++ b/docs/architecture/security/encryption.md @@ -1,6 +1,6 @@ # Encryption and privacy model -> Last updated: 2026-10-03 +> Last updated: 2026-10-04 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/inference/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/inference/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/inference/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/inference/sender_encryption.go` (`SealedTransport`, `isSealedRequest`); `coordinator/api/inference/media_bridge.go` (`gateRemoteMediaPreDispatch`) delegates to `coordinator/internal/inference/media/media_resolve.go` (`Bridge.Gate`) | | 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/inference/sender_encryption.go` (`sealingResponseWriter`, `sealedResponseEnvelope`) | diff --git a/docs/consumer/quickstart.md b/docs/consumer/quickstart.md index 3e9f52faa4..eb1682b849 100644 --- a/docs/consumer/quickstart.md +++ b/docs/consumer/quickstart.md @@ -1,6 +1,6 @@ # Quickstart: first request in five steps -> Last updated: 2026-10-03 +> Last updated: 2026-10-04 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). @@ -162,6 +162,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 c1cb55410e..9afc297019 100644 --- a/docs/reference/api-contracts.md +++ b/docs/reference/api-contracts.md @@ -1,6 +1,6 @@ # HTTP API contracts -> Last updated: 2026-10-03 +> Last updated: 2026-10-04 The public HTTP surface of the coordinator, derived from its composed route bindings under `coordinator/api/`, including the `/v1/` catch-all. Every route is listed below with its handler symbol, authentication requirement, and rate-limit bucket; the second half of the page gives the wire shapes, headers, error table, SSE framing, limits, timeouts, and version-gate semantics that those routes share. For *why* the pipeline is built this way see [`../architecture/components/consumer.md`](../architecture/components/consumer.md); for the crypto model behind sealed transport see [`../architecture/security/encryption.md`](../architecture/security/encryption.md). @@ -815,6 +815,7 @@ Built by `handleStreamingResponseWithFirstChunkAndError` (`coordinator/internal/ |---|---|---| | Global request body | 64 MiB ceiling on every request (`maxRequestBodyBytes`, `bodyLimitMiddleware`) | `coordinator/api/server.go`, `coordinator/internal/api/middleware/middleware.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/inference_preprocess.go`), `SealedTransport` (`coordinator/api/inference/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/provider/trust/settings.go`) | | `n` | Must be 1 | `HandleChatCompletions` |