Files
frontend/apps/dc/app/api/flask-service/complete-embed/route.test.ts
T

191 lines
8.9 KiB
TypeScript

import { NextRequest } from "next/server";
import { createHash } from "node:crypto";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { POST } from "./route";
const jobId = "12345678-1234-1234-1234-123456789abc";
const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEifQ.signature";
const rotatedJwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEiLCJyb3QiOjF9.signature";
const capability = "opaque-rag-capability-with-more-than-32-characters";
const digest = "a".repeat(64);
const artifact = {
status: "parsed", file_sn: "file-1", document_id: `sha256:${digest}`,
facility: { name: "example" },
};
const job = {
job_id: jobId, type: "EMBED_DOCUMENTS", status: "DONE",
result: {
embedded_files: [{ file_sn: "file-1" }],
ingest_profile: { pdf_sha256: digest },
general_survey_import: artifact,
},
};
const file = { fileSn: "file-1", projectId: "root-1", clsfSystmSn: "leaf-1", useYn: "Y" };
const categories = [{
clsfSystmSn: "root-1", clsfSystmNm: "자료관", upClsfSystmSn: "0",
children: [{ clsfSystmSn: "leaf-1", clsfSystmNm: "물 재이용", upClsfSystmSn: "root-1", children: [] }],
}];
function request(options: { token?: string; jwt?: string; jobId?: string } = {}) {
return new NextRequest("https://dc.invalid/api/flask-service/complete-embed", {
method: "POST",
headers: { Cookie: `Authorization=${options.jwt ?? jwt}`, "Content-Type": "application/json" },
body: JSON.stringify({
jobId: options.jobId ?? jobId,
completionAttestation: options.token === undefined ? capability : options.token,
general_survey_import: { forged: true },
registryContext: { fileSn: "forged-browser-file" },
}),
});
}
beforeEach(() => {
vi.stubEnv("FLASK_API_URL", "https://dc-rag.invalid");
vi.stubEnv("DC_SERVICE_API_URL", "https://dc-service.invalid");
});
afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); });
describe("complete embed survey handoff", () => {
it("checks job and dc-service first, consumes the RAG capability, then imports only the verified artifact", async () => {
const calls: string[] = [];
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
calls.push(`${init?.method ?? "GET"} ${url}`);
expect(new Headers(init?.headers).get("Authorization")).toBe(jwt);
if (url.endsWith(`/jobs/${jobId}`)) return Response.json(job);
if (url.includes("/fileprcs")) return Response.json([file]);
if (url.endsWith("/clsf")) return Response.json(categories);
if (url.endsWith(`/jobs/${jobId}/verify-completion`)) {
expect(JSON.parse(String(init?.body))).toEqual({
completionAttestation: capability, fileSn: "file-1",
registryContext: {
version: 1, ...file, classificationPath: ["자료관", "물 재이용"],
subjectSha256: createHash("sha256").update("user-1").digest("hex"),
},
});
return Response.json({ verified: true });
}
if (url.endsWith("/gnsvy/imports")) {
expect(JSON.parse(String(init?.body))).toEqual(artifact);
return Response.json({ status: "IMPORTED", saved_count: 9 });
}
throw new Error("unexpected URL");
});
vi.stubGlobal("fetch", fetchMock);
const response = await POST(request());
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ imported: true });
expect(calls).toEqual([
`GET https://dc-rag.invalid/flask-service/jobs/${jobId}`,
"GET https://dc-service.invalid/dc-service/api/v1/fileprcs?fileSn=file-1",
"GET https://dc-service.invalid/dc-service/api/v1/clsf",
`POST https://dc-rag.invalid/flask-service/jobs/${jobId}/verify-completion`,
"POST https://dc-service.invalid/dc-service/api/v1/gnsvy/imports",
]);
});
it("does not consume a capability when the completed job has no survey artifact", async () => {
const fetchMock = vi.fn(async () => Response.json({
...job, result: { ...job.result, general_survey_import: null },
}));
vi.stubGlobal("fetch", fetchMock);
const response = await POST(request());
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ imported: false });
expect(fetchMock).toHaveBeenCalledOnce();
});
it("rejects a missing completion capability before any lookup", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const response = await POST(request({ token: "" }));
expect(response.status).toBe(403);
expect(fetchMock).not.toHaveBeenCalled();
});
it("does not consume a capability when current JWT fails dc-service readback", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) =>
String(input).endsWith(`/jobs/${jobId}`) ? Response.json(job)
: new Response(null, { status: 401 }));
vi.stubGlobal("fetch", fetchMock);
const response = await POST(request({ jwt: "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEifQ.forged" }));
expect(response.status).toBe(401);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it("rejects RAG capability denial without importing", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith(`/jobs/${jobId}`)) return Response.json(job);
if (url.includes("/fileprcs")) return Response.json([file]);
if (url.endsWith("/clsf")) return Response.json(categories);
if (url.endsWith("/verify-completion")) return new Response(null, { status: 403 });
throw new Error("must not import");
});
vi.stubGlobal("fetch", fetchMock);
const response = await POST(request({ token: "wrong-user-or-file-capability" }));
expect(response.status).toBe(403);
expect((await response.json()).code).toBe("COMPLETE_EMBED_AUTHORITY_INVALID");
expect(fetchMock).toHaveBeenCalledTimes(4);
});
it("uses a refreshed JWT for readback and verification", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
expect(new Headers(init?.headers).get("Authorization")).toBe(rotatedJwt);
if (url.endsWith(`/jobs/${jobId}`)) return Response.json(job);
if (url.includes("/fileprcs")) return Response.json([file]);
if (url.endsWith("/clsf")) return Response.json(categories);
if (url.endsWith("/verify-completion")) return Response.json({ verified: true });
if (url.endsWith("/gnsvy/imports")) return Response.json({ status: "IMPORTED", saved_count: 9 });
throw new Error("unexpected URL");
});
vi.stubGlobal("fetch", fetchMock);
expect((await POST(request({ jwt: rotatedJwt }))).status).toBe(200);
expect(fetchMock).toHaveBeenCalledTimes(5);
});
it("rejects a missing authenticated subject before consuming the completion capability", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith(`/jobs/${jobId}`)) return Response.json(job);
if (url.includes("/fileprcs")) return Response.json([file]);
if (url.endsWith("/clsf")) return Response.json(categories);
throw new Error("must not verify or import");
});
vi.stubGlobal("fetch", fetchMock);
const response = await POST(request({ jwt: "header.e30.signature" }));
expect(response.status).toBe(401);
expect((await response.json()).code).toBe("AUTH_SUBJECT_INVALID");
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it.each([
["unfinished job", { ...job, status: "RUNNING" }],
["different file", { ...job, result: { ...job.result, embedded_files: [{ file_sn: "other-file" }] } }],
["different PDF digest", { ...job, result: { ...job.result, ingest_profile: { pdf_sha256: "b".repeat(64) } } }],
])("does not consume a capability for %s", async (_label, invalidJob) => {
const fetchMock = vi.fn(async () => Response.json(invalidJob));
vi.stubGlobal("fetch", fetchMock);
expect((await POST(request())).status).toBeGreaterThanOrEqual(400);
expect(fetchMock).toHaveBeenCalledOnce();
});
it("holds a disconnected import as uncertain and never retries", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith(`/jobs/${jobId}`)) return Response.json(job);
if (url.includes("/fileprcs")) return Response.json([file]);
if (url.endsWith("/clsf")) return Response.json(categories);
if (url.endsWith("/verify-completion")) return Response.json({ verified: true });
if (url.endsWith("/gnsvy/imports")) throw new TypeError("connection dropped after dispatch");
throw new Error("unexpected URL");
});
vi.stubGlobal("fetch", fetchMock);
const response = await POST(request());
expect(response.status).toBe(502);
expect((await response.json()).code).toBe("GENERAL_SURVEY_IMPORT_UNCERTAIN");
expect(fetchMock).toHaveBeenCalledTimes(5);
});
});