Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
35 changes: 35 additions & 0 deletions dashboard/e2e/chat.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 4 additions & 2 deletions dashboard/src/lib/brain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import { request, ApiError } from "./api";
import { streamBase } from "./runtime-config";
import { streamPost } from "./stream-client";

// ── Knowledge bases ───────────────────────────────────────────────

Expand Down Expand Up @@ -318,10 +319,11 @@ async function brainToken(): Promise<string> {
/** Asks a question; events arrive through `onEvent` until `done`. */
export async function askBrain(body: AskBody, onEvent: (e: BrainEvent) => void, signal?: AbortSignal): Promise<void> {
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) {
Expand Down
38 changes: 33 additions & 5 deletions dashboard/src/lib/stream-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>; 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<string> {
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;
Expand Down Expand Up @@ -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,
Expand Down
Loading