diff --git a/dashboard/e2e/chat.spec.ts b/dashboard/e2e/chat.spec.ts index 974c2f9a..9b23b815 100644 --- a/dashboard/e2e/chat.spec.ts +++ b/dashboard/e2e/chat.spec.ts @@ -295,6 +295,41 @@ async function askIt(page: Page, q = "How long is parental leave?") { await box(page).press("Enter"); } +test.describe("chat: the answer stream's request", () => { + /** The headers of the one answer stream request a question makes. */ + async function streamHeaders(page: Page, selfHosted: boolean) { + await mockApi(page); + if (selfHosted) { + await page.route((url) => url.pathname === "/runtime-config.js", (r) => + r.fulfill({ contentType: "text/javascript", body: `window.__CODERHELM_CONFIG__ = ${JSON.stringify({ apiUrl: "", streamUrl: "", selfHosted: true })};` }), + ); + } + const req = page.waitForRequest((r) => r.url().endsWith("/api/brain/stream") && r.method() === "POST"); + await page.goto("/chat"); + await askIt(page); + const r = await req; + return { headers: await r.allHeaders(), body: r.postData() ?? "" }; + } + + test("self-hosted: through the install's CloudFront, the token in its own header and the body's SHA-256", async ({ page }) => { + const { headers, body } = await streamHeaders(page, true); + // CloudFront signs the call to the function URL (its signature is the + // Authorization header): the token can't travel there. + expect(headers["authorization"]).toBeUndefined(); + expect(headers["x-coderhelm-stream-token"]).toBe("t"); + const { createHash } = await import("node:crypto"); + expect(headers["x-amz-content-sha256"]).toBe(createHash("sha256").update(body, "utf8").digest("hex")); + expect(JSON.parse(body).question).toBe("How long is parental leave?"); + }); + + test("a stream on another hostname: a bearer token, nothing else", async ({ page }) => { + const { headers } = await streamHeaders(page, false); + expect(headers["authorization"]).toBe("Bearer t"); + expect(headers["x-coderhelm-stream-token"]).toBeUndefined(); + expect(headers["x-amz-content-sha256"]).toBeUndefined(); + }); +}); + test.describe("chat: the empty page", () => { test("opens on a focused question box with starter questions, and no scope it wasn't given", async ({ page }) => { const db = await mockApi(page); diff --git a/dashboard/src/lib/brain.ts b/dashboard/src/lib/brain.ts index 7cb5f950..11d17867 100644 --- a/dashboard/src/lib/brain.ts +++ b/dashboard/src/lib/brain.ts @@ -4,6 +4,7 @@ import { request, ApiError } from "./api"; import { streamBase } from "./runtime-config"; +import { streamPost } from "./stream-client"; // ── Knowledge bases ─────────────────────────────────────────────── @@ -318,10 +319,11 @@ async function brainToken(): Promise { /** Asks a question; events arrive through `onEvent` until `done`. */ export async function askBrain(body: AskBody, onEvent: (e: BrainEvent) => void, signal?: AbortSignal): Promise { const token = await brainToken(); + const post = await streamPost(token, body); const res = await fetch(`${streamBase()}/api/brain/stream`, { method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify(body), + headers: post.headers, + body: post.body, signal, }); if (!res.ok || !res.body) { diff --git a/dashboard/src/lib/stream-client.ts b/dashboard/src/lib/stream-client.ts index b80dbe35..000ff9eb 100644 --- a/dashboard/src/lib/stream-client.ts +++ b/dashboard/src/lib/stream-client.ts @@ -5,7 +5,37 @@ import type { StreamEvent } from "./stream-types"; import { apiBase, streamBase } from "@/lib/runtime-config"; +/** + * A chat stream POST: its headers and body. + * + * On the dashboard's own hostname (a self-hosted install) the stream goes + * through the install's CloudFront, which signs each call to the streaming + * function (origin access control: the function URL takes only signed calls). + * CloudFront's signature is the Authorization header, so the token goes in + * its own header, and Lambda needs the body's SHA-256 in + * x-amz-content-sha256 to accept a signed POST. A stream on another hostname + * (the hosted service) takes the token as a bearer token, as before. + */ +export async function streamPost(token: string, payload: unknown): Promise<{ headers: Record; body: string }> { + const body = JSON.stringify(payload); + if (streamBase() !== "") { + return { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, body }; + } + return { + headers: { + "Content-Type": "application/json", + "x-coderhelm-stream-token": token, + "x-amz-content-sha256": await sha256Hex(body), + }, + body, + }; +} +/** The SHA-256 of `text` (UTF-8), in lowercase hex. */ +export async function sha256Hex(text: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)); + return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join(""); +} /** How long to wait for the token fetch or initial stream connection */ const CONNECT_TIMEOUT_MS = 15_000; @@ -138,15 +168,13 @@ export async function streamChat( assertOnline(); const token = await fetchStreamToken(signal); + const post = await streamPost(token, { messages, chat_id: chatId }); const res = await withTimeout( fetch(`${streamBase()}/api/plans/chat/stream`, { method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token}`, - }, - body: JSON.stringify({ messages, chat_id: chatId }), + headers: post.headers, + body: post.body, signal, }), CONNECT_TIMEOUT_MS,