Files
frontend/apps/dc/app/api/flask-service/ask-question/route.test.ts
T

117 lines
6.5 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
const state = vi.hoisted(() => ({token: ""}));
vi.mock("next/headers", () => ({
cookies: async () => ({get: (name: string) =>
name === "Authorization" && state.token ? {value:state.token} : undefined}),
}));
vi.mock("@/shared/config", () => ({CLAIM_NAME:"Authorization", AUTH_USER_ID:"token-id"}));
vi.mock("@/server/category-scope-attestation", async importOriginal => ({
...await importOriginal<typeof import("@/server/category-scope-attestation")>(),
prepareCategoryScope: vi.fn(async () => ({ required: false, questionSha256: "hash", family: null })),
}));
import { POST } from "./route";
beforeEach(() => { vi.restoreAllMocks(); state.token = ""; });
const request = () => new NextRequest("https://dc.invalid/api/flask-service/ask-question", {
method:"POST", body:JSON.stringify({question:"synthetic"}),
});
describe("RAG proxy forwarding and errors", () => {
it("preserves upstream authentication handling without a new local access gate", async () => {
const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response("login required", {status:401}));
expect((await POST(request())).status).toBe(401);
expect(fetch).toHaveBeenCalledOnce();
});
it.each([401,403,503])("preserves %i without exposing upstream data", async status => {
state.token = "synthetic";
const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response("sensitive upstream internals", {status}));
const result = await POST(request());
expect(result.status).toBe(status);
expect(await result.text()).not.toContain("sensitive");
expect(result.headers.get("cache-control")).toBe("no-store");
expect(fetch.mock.calls[0]?.[1]).toMatchObject({cache:"no-store",redirect:"error"});
});
it("forwards the allowed SSE body without buffering", async () => {
state.token = "synthetic";
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response('data: {"type":"DONE"}\n\n', {headers:{"content-type":"text/event-stream"}}));
const result = await POST(request());
expect(result.status).toBe(200);
expect(result.headers.get("content-type")).toBe("text/event-stream");
expect(await result.text()).toContain('"type":"DONE"');
});
it("ignores a browser-supplied category assertion when preflight needs no category scope", async () => {
const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("done"));
const request = new NextRequest("https://dc.invalid/api/flask-service/ask-question", {
method: "POST", body: JSON.stringify({question: "test", category_attestation: "forged"}),
});
await POST(request);
expect(JSON.parse(String(fetch.mock.calls[0]?.[1]?.body))).toEqual({
question: "test",
});
});
it("forwards the existing login token only in the upstream request", async () => {
state.token = "synthetic-existing-token";
const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response('data: {"type":"DONE"}\n\n'));
const response = await POST(request());
expect(fetch.mock.calls[0]?.[1]?.headers).toMatchObject({Authorization:state.token});
expect(response.headers.get("Authorization")).toBeNull();
expect(await response.text()).not.toContain(state.token);
});
it.each(["AbortError", "TypeError"])("sanitizes %s without logging the token", async name => {
state.token = "synthetic-existing-token";
const error = new Error(state.token);
error.name = name;
vi.spyOn(globalThis, "fetch").mockRejectedValue(error);
const log = vi.spyOn(console, "error").mockImplementation(() => {});
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const response = await POST(request());
expect(response.status).toBe(name === "AbortError" ? 504 : 500);
expect(await response.text()).not.toContain(state.token);
expect(JSON.stringify([...log.mock.calls, ...warn.mock.calls])).not.toContain(state.token);
expect(name === "AbortError" ? warn : log).toHaveBeenCalledWith(
name === "AbortError" ? "[ask-question] upstream_timeout" : "[ask-question] request_failed",
{status:name === "AbortError" ? 504 : 500},
);
});
});
describe("proxy request ID correlation", () => {
const idPattern = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
it("generates separate IDs, forwards each and ignores caller supplied IDs", async () => {
const fetch=vi.spyOn(globalThis,"fetch").mockImplementation(async () => new Response("done"));
const make=()=>new NextRequest("https://dc.invalid/api/flask-service/ask-question",{
method:"POST",headers:{"x-request-id":"caller-repeat"},body:JSON.stringify({question:"same"})});
const a=await POST(make());const b=await POST(make());
const ids=[a,b].map(x=>x.headers.get("x-request-id"));
expect(ids[0]).toMatch(idPattern);expect(ids[1]).toMatch(idPattern);
expect(ids[0]).not.toBe(ids[1]);expect(ids).not.toContain("caller-repeat");
expect(new Headers(fetch.mock.calls[0]?.[1]?.headers).get("x-request-id")).toBe(ids[0]);
expect(new Headers(fetch.mock.calls[1]?.[1]?.headers).get("x-request-id")).toBe(ids[1]);
expect(JSON.parse(String(fetch.mock.calls[0]?.[1]?.body))).toEqual({question:"same"});
});
it.each([200,503])("returns the valid upstream ID for HTTP %i", async status => {
vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response("body",{status,headers:{"x-request-id":"rag-authoritative-1"}}));
const response=await POST(request());expect(response.headers.get("x-request-id")).toBe("rag-authoritative-1");
});
it.each(["unsafe value", "x".repeat(129)])("retains its own safe ID for an invalid upstream header", async invalid => {
const fetch=vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response("body",{headers:{"x-request-id":invalid}}));
const response=await POST(request());const requestId=response.headers.get("x-request-id");
expect(requestId).toMatch(idPattern);expect(requestId).not.toBe(invalid);
expect(new Headers(fetch.mock.calls[0]?.[1]?.headers).get("x-request-id")).toBe(requestId);
});
it("includes a support ID even when request JSON cannot be parsed", async () => {
const fetch=vi.spyOn(globalThis,"fetch");vi.spyOn(console,"error").mockImplementation(()=>{});
const response=await POST(new NextRequest("https://dc.invalid/api/flask-service/ask-question",{method:"POST",body:"{"}));
expect(response.status).toBe(500);expect(response.headers.get("x-request-id")).toMatch(idPattern);
expect(fetch).not.toHaveBeenCalled();
});
});