자료관 앱을 원앤올 공통 패키지 기준으로 최신화
This commit is contained in:
@@ -0,0 +1,483 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/shared/config", () => ({ CLAIM_NAME: "memory-auth", AUTH_USER_ID: "memory-user" }));
|
||||
vi.mock("@/shared/config/env", () => ({ CLAIM_NAME: "memory-auth", AUTH_USER_ID: "memory-user", SITE_ID: "test-site" }));
|
||||
|
||||
import { DELETE, GET, PATCH, PUT } from "../../dc-service/api/v1/rag-search/conversation-memory/route";
|
||||
import { GET as listGET, POST } from "../../dc-service/api/v1/rag-search/conversation-sessions/route";
|
||||
|
||||
const sessionId = "00000000-0000-4000-8000-000000000011";
|
||||
const selectedFile = "00000000-0000-4000-8000-000000000012";
|
||||
const key = "test-only-server-key";
|
||||
const subject = "synthetic-owner";
|
||||
const jwt = (sub: unknown = subject, exp = Math.floor(Date.now() / 1000) + 3600) =>
|
||||
`header.${Buffer.from(JSON.stringify({ sub, exp })).toString("base64url")}.synthetic`;
|
||||
const tree = [
|
||||
{ clsfSystmSn: "project-b", upClsfSystmSn: "", children: [{ clsfSystmSn: "leaf-b", upClsfSystmSn: "project-b" }] },
|
||||
{ clsfSystmSn: "project-a", upClsfSystmSn: "" },
|
||||
];
|
||||
// Actual /dc-service/api/v1/clsf top-level DTO contract: null DB parents are "0".
|
||||
const zeroParentTree = [
|
||||
{ clsfSystmSn: "CLS20250529000001", clsfSystmNm: "기본계획", upClsfSystmSn: "0", children: [] },
|
||||
{ clsfSystmSn: "CLS20260601000001", clsfSystmNm: "물재이용", upClsfSystmSn: "0", children: [] },
|
||||
];
|
||||
const snapshot = () => ({
|
||||
version: 1, session_id: sessionId, project_ids: ["project-a"], selected_file_sns: [selectedFile],
|
||||
selected_sources: [`${selectedFile}.pdf`], natural_domain: "all",
|
||||
messages: [{ role: "user", text: "원래 질문" }, { role: "bot", text: "2021년: 214,197㎥/일", conversationComplete: true }],
|
||||
});
|
||||
type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
||||
const handlers = { GET, POST, PUT, PATCH, DELETE };
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
function request(method: Method = "GET", options: {
|
||||
session?: string | null; token?: string | null; body?: unknown; raw?: string; headers?: Record<string, string>;
|
||||
} = {}) {
|
||||
const headers = new Headers(options.headers);
|
||||
if (options.token !== null) headers.set("Cookie", `memory-auth=${options.token ?? jwt()}; memory-user=synthetic-cookie-user`);
|
||||
if (method === "PUT" || method === "PATCH" || method === "POST") headers.set("Content-Type", "application/json");
|
||||
const query = options.session === null ? "" : `?session_id=${options.session ?? sessionId}`;
|
||||
const route = method === "POST" || (method === "GET" && options.session === null) ? "conversation-sessions" : "conversation-memory";
|
||||
return new NextRequest(`http://localhost/dc-service/api/v1/rag-search/${route}${query}`, {
|
||||
method, headers, ...((method === "PUT" || method === "PATCH" || method === "POST") ? { body: options.raw ?? JSON.stringify(options.body ?? (method === "POST" ? {} : method === "PATCH" ? { title: "대화 제목" } : snapshot())) } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("NEXT_PUBLIC_DC_SERVICE_API_URL", "http://127.0.0.1:18082");
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", key);
|
||||
fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = new URL(String(input));
|
||||
return url.pathname.endsWith("/clsf") ? Response.json({ data: tree }) : Response.json({ session_info: snapshot() });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
});
|
||||
afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
|
||||
|
||||
describe("conversation memory owner-bound proxy", () => {
|
||||
it("searches through one owner-bound list request without URL query text or detail fan-out", async () => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json(tree));
|
||||
fetchMock.mockResolvedValueOnce(Response.json({sessions:[{session_id:sessionId,title:"계획",messages:["MUST_NOT_LEAK"],match_count:1,
|
||||
preview_candidate:{role:"bot",text:"2015년 인구계획은 169,370명입니다.\n\n(출처: 1장 총설, 표 1.2‑3, “안심” 항목)",has_sources:true,complete:true}}],total_sessions:72,total_accessible_sessions:100,offset:0,limit:50}));
|
||||
const response = await POST(request("POST",{session:null,body:{query:" 169,370 ",sort:"title",offset:0,limit:50},headers:{"X-Conversation-Context":"forged"}}));
|
||||
expect(response.status).toBe(200); expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
const [url,init] = fetchMock.mock.calls[1]!;
|
||||
expect(String(url)).toBe("http://127.0.0.1:18082/dc-service/api/v1/rag-search/conversation-sessions");
|
||||
expect(init.method).toBe("POST"); expect(JSON.parse(init.body)).toEqual({query:"169,370",sort:"title",offset:0,limit:50});
|
||||
expect(JSON.parse(new Headers(init.headers).get("X-Conversation-Context")!).projectIds).toEqual(["project-a","project-b"]);
|
||||
const body = await response.json(); expect(body.sessions[0].match_preview).toEqual({role:"bot",text:"2015년 인구계획은 169,370명입니다."});
|
||||
expect(JSON.stringify(body)).not.toMatch(/preview_candidate|MUST_NOT_LEAK|표 1.2/);
|
||||
expect(body.total_sessions).toBe(72); expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
});
|
||||
it.each([401,403])("preserves fresh permission rejection %i for search",async status=>{
|
||||
fetchMock.mockResolvedValueOnce(new Response("PRIVATE_SEARCH_AUTH",{status}));
|
||||
const response=await POST(request("POST",{session:null,body:{query:"강릉"}}));
|
||||
expect(response.status).toBe(status); expect(fetchMock).toHaveBeenCalledOnce(); expect(await response.text()).not.toContain("PRIVATE_SEARCH_AUTH");
|
||||
});
|
||||
it("rejects unsigned search before any upstream request",async()=>{
|
||||
expect((await POST(request("POST",{session:null,token:null,body:{query:"강릉"}}))).status).toBe(401); expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([{query:"x".repeat(201)},{query:null},{sort:["recent"]},{offset:-1},{limit:101},{limit:0},{owner:"foreign"},{project_ids:["foreign"]}])("rejects invalid search conditions without trusting browser ownership %j",async body=>{
|
||||
expect((await POST(request("POST",{session:null,body}))).status).toBe(400); expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects a search body beyond its small input budget",async()=>{
|
||||
expect((await POST(request("POST",{session:null,raw:" ".repeat(4097)}))).status).toBe(413); expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not leak private internal candidates on malformed search responses",async()=>{
|
||||
fetchMock.mockResolvedValueOnce(Response.json(tree)); fetchMock.mockResolvedValueOnce(Response.json({sessions:[{preview_candidate:"PRIVATE_RAW_MESSAGE"}]}));
|
||||
const response=await POST(request("POST",{session:null,body:{query:"강릉"}})); expect(response.status).toBe(502); expect(await response.text()).not.toContain("PRIVATE_RAW_MESSAGE");
|
||||
});
|
||||
it("classifies an invalid upstream JSON response as an upstream failure, preserving malformed input as 400",async()=>{
|
||||
fetchMock.mockResolvedValueOnce(Response.json(tree)); fetchMock.mockResolvedValueOnce(new Response("PRIVATE_NON_JSON"));
|
||||
const response=await POST(request("POST",{session:null,body:{query:"강릉"}})); expect(response.status).toBe(502); expect(await response.text()).not.toContain("PRIVATE_NON_JSON");
|
||||
expect((await POST(request("POST",{session:null,raw:"not-json"}))).status).toBe(400); expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("requires a session id on the detail route and keeps the list route collection-only", async () => {
|
||||
const base = "http://localhost/dc-service/api/v1/rag-search";
|
||||
expect((await GET(new NextRequest(base + "/conversation-memory"))).status).toBe(400);
|
||||
expect((await listGET(new NextRequest(base + "/conversation-sessions?session_id=" + sessionId))).status).toBe(400);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([
|
||||
{ method: "GET" as const, session: null, operation: "list" },
|
||||
{ method: "GET" as const, session: sessionId, operation: "restore" },
|
||||
{ method: "PUT" as const, session: sessionId, operation: "save" },
|
||||
{ method: "DELETE" as const, session: sessionId, operation: "delete" },
|
||||
])("uses authenticated zero-parent project roots for $operation", async ({ method, session }) => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json(zeroParentTree));
|
||||
const body = { ...snapshot(), project_ids: [zeroParentTree[0]!.clsfSystmSn] };
|
||||
const token = jwt();
|
||||
const response = await handlers[method](request(method, { session, body, token, headers: {
|
||||
"X-Conversation-Context": '{"version":1,"projectIds":["forged"]}', "X-Rag-V2-Internal-Key": "forged-key",
|
||||
} }));
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(new Headers(fetchMock.mock.calls[0]![1]?.headers).get("X-Dc-Preview-Relay")).toBe("1");
|
||||
const upstream = fetchMock.mock.calls[1]!;
|
||||
expect(String(upstream[0])).toBe(session === null
|
||||
? "http://127.0.0.1:18082/dc-service/api/v1/rag-search/conversation-sessions"
|
||||
: `http://127.0.0.1:18082/dc-service/api/v1/rag-search/conversation-memory?session_id=${sessionId}`);
|
||||
const headers = new Headers(upstream[1]?.headers);
|
||||
expect(headers.get("Authorization")).toBe(token);
|
||||
expect(headers.get("X-Rag-V2-Internal-Key")).toBe(key);
|
||||
expect(JSON.parse(headers.get("X-Conversation-Context")!)).toEqual({
|
||||
version: 1, subjectSha256: createHash("sha256").update(subject).digest("hex"),
|
||||
projectIds: zeroParentTree.map(row=>row.clsfSystmSn),
|
||||
});
|
||||
expect(upstream[1]?.body).toBe(method === "PUT" ? JSON.stringify(body) : undefined);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it("does not promote a nonzero orphan parent to an authorized project root", async () => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json([
|
||||
{ clsfSystmSn:"orphan",upClsfSystmSn:"missing-parent",children:[] },
|
||||
]));
|
||||
expect((await GET(request())).status).toBe(403);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("does not grant an orphan project alongside valid zero-parent roots", async () => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json([
|
||||
...zeroParentTree, { clsfSystmSn:"orphan",upClsfSystmSn:"missing-parent",children:[] },
|
||||
]));
|
||||
const response = await PUT(request("PUT", {body:{...snapshot(),project_ids:["orphan"]}}));
|
||||
expect(response.status).toBe(403);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each(["0", "other-parent"])("retains strict nested parent matching for %s", async parent => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json([
|
||||
{ ...zeroParentTree[0], children:[{clsfSystmSn:"leaf",upClsfSystmSn:parent,children:[]}] },
|
||||
]));
|
||||
expect((await GET(request())).status).toBe(502);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each(["GET", "PUT", "DELETE"] as const)("rejects unauthenticated %s before any upstream access", async method => {
|
||||
const response = await handlers[method](request(method, { token: null }));
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not accept an Authorization header or forged context instead of the login cookie", async () => {
|
||||
const response = await GET(request("GET", { token: null, headers: {
|
||||
Authorization: jwt("forged-owner"), "X-Conversation-Context": '{"subjectSha256":"forged","projectIds":["foreign"]}',
|
||||
"X-Rag-V2-Internal-Key": "browser-key",
|
||||
} }));
|
||||
expect(response.status).toBe(401);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([401, 403])("preserves fresh DC authentication/permission rejection %i without memory dispatch", async status => {
|
||||
fetchMock.mockResolvedValueOnce(new Response("PRIVATE_UPSTREAM_TOKEN", { status }));
|
||||
const response = await GET(request());
|
||||
expect(response.status).toBe(status);
|
||||
expect(await response.text()).not.toContain("PRIVATE_UPSTREAM_TOKEN");
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("requires the fresh DC check to reject an expired cookie before constructing owner context", async () => {
|
||||
const expired = jwt(subject, 1);
|
||||
fetchMock.mockResolvedValueOnce(new Response("expired", { status: 401 }));
|
||||
const response = await GET(request("GET", { token: expired }));
|
||||
expect(response.status).toBe(401);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect(new Headers(fetchMock.mock.calls[0]![1]?.headers).get("Authorization")).toBe(expired);
|
||||
expect(await response.text()).not.toContain(expired);
|
||||
});
|
||||
|
||||
it.each([undefined, "", " owner ", ["owner"]])("rejects an invalid cookie subject after DC acceptance: %j", async sub => {
|
||||
const token = `header.${Buffer.from(JSON.stringify({ sub })).toString("base64url")}.synthetic`;
|
||||
const response = await GET(request("GET", { token }));
|
||||
expect(response.status).toBe(401);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each(["GET", "PUT", "DELETE"] as const)("forwards %s using the cookie subject, fresh project roots and existing server key only", async method => {
|
||||
const token = jwt();
|
||||
const response = await handlers[method](request(method, { token, headers: {
|
||||
Authorization: jwt("different-browser-owner"), "X-Conversation-Context": '{"version":1,"subjectSha256":"forged","projectIds":["foreign"]}',
|
||||
"X-Rag-V2-Internal-Key": "browser-key", "X-User-Id": "forged-user", "X-Project-Id": "foreign",
|
||||
} }));
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
const dc = fetchMock.mock.calls[0]!;
|
||||
expect(String(dc[0])).toBe("http://127.0.0.1:18082/dc-service/api/v1/clsf");
|
||||
expect(new Headers(dc[1]?.headers).get("Authorization")).toBe(token);
|
||||
expect(new Headers(dc[1]?.headers).get("X-Conversation-Context")).toBeNull();
|
||||
expect(new Headers(dc[1]?.headers).get("X-Rag-V2-Internal-Key")).toBeNull();
|
||||
expect(dc[1]).toMatchObject({ cache: "no-store", redirect: "error" });
|
||||
const rag = fetchMock.mock.calls[1]!;
|
||||
const headers = new Headers(rag[1]?.headers);
|
||||
expect(String(rag[0])).toBe(`http://127.0.0.1:18082/dc-service/api/v1/rag-search/conversation-memory?session_id=${sessionId}`);
|
||||
expect(rag[1]).toMatchObject({ method, cache: "no-store", redirect: "error" });
|
||||
expect(headers.get("Authorization")).toBe(token);
|
||||
expect(headers.get("X-Rag-V2-Internal-Key")).toBe(key);
|
||||
expect(JSON.parse(headers.get("X-Conversation-Context")!)).toEqual({
|
||||
version: 1, subjectSha256: createHash("sha256").update(subject).digest("hex"), projectIds: ["project-a", "project-b"],
|
||||
});
|
||||
expect(headers.get("Cookie")).toContain(`memory-auth=${token}`);
|
||||
expect(headers.get("memory-auth")).toBe(token);
|
||||
for (const name of ["X-User-Id", "X-Project-Id"]) expect(headers.get(name)).toBeNull();
|
||||
expect(response.headers.get("Authorization")).toBeNull();
|
||||
expect(response.headers.get("X-Rag-V2-Internal-Key")).toBeNull();
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it("lists sessions with authenticated context and no body or caller project query", async () => {
|
||||
fetchMock.mockImplementationOnce(async () => Response.json(tree));
|
||||
fetchMock.mockResolvedValueOnce(Response.json({ sessions: [{ session_id: sessionId }] }));
|
||||
const response = await GET(new NextRequest("http://localhost/api/conversation-memory?project_id=foreign", {
|
||||
headers: { Cookie: `memory-auth=${jwt()}` },
|
||||
}));
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ sessions: [{ session_id: sessionId }] });
|
||||
expect(String(fetchMock.mock.calls[1]![0])).toBe("http://127.0.0.1:18082/dc-service/api/v1/rag-search/conversation-sessions");
|
||||
expect(fetchMock.mock.calls[1]![1]?.body).toBeUndefined();
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it("uses the configured site for the fresh authority read instead of a browser site header", async () => {
|
||||
const response = await GET(request("GET", { headers: { "X-Site-Id": "browser-foreign-site" } }));
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
const dcHeaders = new Headers(fetchMock.mock.calls[0]![1]?.headers);
|
||||
const ragHeaders = new Headers(fetchMock.mock.calls[1]![1]?.headers);
|
||||
expect(dcHeaders.get("X-Site-Id")).toBe("test-site");
|
||||
expect(ragHeaders.get("X-Site-Id")).toBe("test-site");
|
||||
});
|
||||
|
||||
it("does not trust a browser user-ID header when no matching user-ID cookie exists", async () => {
|
||||
const response = await GET(new NextRequest(`http://localhost/api/conversation-memory?session_id=${sessionId}`, {
|
||||
headers: { Cookie: `memory-auth=${jwt()}`, "memory-user": "forged-header-user" },
|
||||
}));
|
||||
expect(response.status).toBe(200);
|
||||
expect(new Headers(fetchMock.mock.calls[0]![1]?.headers).get("memory-user")).toBeNull();
|
||||
expect(new Headers(fetchMock.mock.calls[1]![1]?.headers).get("memory-user")).toBeNull();
|
||||
});
|
||||
|
||||
it("forwards an unchanged whitelisted snapshot without browser owner or authority fields", async () => {
|
||||
const input = snapshot();
|
||||
const original = JSON.stringify(input);
|
||||
await PUT(request("PUT", { body: { ...input, user_id: "forged", owner: "forged", subjectSha256: "forged", projectIds: ["foreign"],
|
||||
conversation_context: { projectIds: ["foreign"] }, internal_key: "browser-key" } }));
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[1]![1]?.body))).toEqual(input);
|
||||
expect(JSON.stringify(input)).toBe(original);
|
||||
});
|
||||
|
||||
it.each([{ projects: ["foreign"] }, { projects: ["project-a", "foreign"] }, { projects: ["leaf-b"] }])("rejects snapshot projects outside fresh authenticated roots: %j", async ({ projects }) => {
|
||||
const response = await PUT(request("PUT", { body: { ...snapshot(), project_ids: projects } }));
|
||||
expect(response.status).toBe(403);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it.each([null, [], {}, { session_id: "invalid", project_ids: ["project-a"] },
|
||||
{ session_id: sessionId, project_ids: [] }, { session_id: sessionId, project_ids: "project-a" },
|
||||
{ session_id: sessionId, project_ids: Array.from({ length: 65 }, () => "project-a") },
|
||||
])("rejects a malformed snapshot before forwarding: %j", async body => {
|
||||
const response = await PUT(request("PUT", { raw: JSON.stringify(body) }));
|
||||
expect(response.status).toBe(400);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects malformed request JSON without dispatch or content disclosure", async () => {
|
||||
const response = await PUT(request("PUT", { raw: '{"messages":"PRIVATE_BODY"' }));
|
||||
expect(response.status).toBe(400);
|
||||
expect(await response.text()).not.toContain("PRIVATE_BODY");
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["declared", "actual", "utf8"])("rejects an oversized %s request before authentication fetch", async mode => {
|
||||
const response = await PUT(request("PUT", mode === "declared"
|
||||
? { headers: { "content-length": "1048577" } }
|
||||
: { raw: JSON.stringify({ ...snapshot(), padding: mode === "utf8" ? "가".repeat(400_000) : "X".repeat(1_048_577) }) }));
|
||||
expect(response.status).toBe(413);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it.each(["GET", "DELETE"] as const)("rejects an invalid %s session before dispatch", async method => {
|
||||
const response = await handlers[method](request(method, { session: "not-a-uuid" }));
|
||||
expect(response.status).toBe(400);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not allow DELETE to delete the session list", async () => {
|
||||
const response = await DELETE(request("DELETE", { session: null }));
|
||||
expect(response.status).toBe(400);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([401, 403, 404, 409, 413, 422, 429])("preserves safe memory upstream status %i without leaking its body", async status => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json({ data: tree }));
|
||||
fetchMock.mockResolvedValueOnce(new Response(`PRIVATE_BODY ${jwt()} ${key}`, { status }));
|
||||
const response = await GET(request());
|
||||
expect(response.status).toBe(status);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
const body = await response.json();
|
||||
expect(body).toEqual({ message: expect.any(String) });
|
||||
expect(JSON.stringify(body)).not.toMatch(/PRIVATE_BODY|test-only-server-key|synthetic/);
|
||||
});
|
||||
|
||||
it("keeps schema validation in the memory service and safely returns its422", async () => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json({ data: tree }));
|
||||
fetchMock.mockResolvedValueOnce(Response.json({ detail: [{ input: "PRIVATE_BAD_MESSAGES" }] }, { status: 422 }));
|
||||
const response = await PUT(request("PUT", { body: { ...snapshot(), messages: "PRIVATE_BAD_MESSAGES" } }));
|
||||
expect(response.status).toBe(422);
|
||||
expect(await response.text()).not.toContain("PRIVATE_BAD_MESSAGES");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each([[], { data: [] }])("fails closed for an authenticated user without project roots: %j", async categories => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json(categories));
|
||||
expect((await GET(request())).status).toBe(403);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each([{ data: {} }, [{ clsfSystmSn: "root", children: {} }],
|
||||
[{ clsfSystmSn: "root" }, { clsfSystmSn: "root" }],
|
||||
[{ clsfSystmSn: "root", children: [{ clsfSystmSn: "leaf", upClsfSystmSn: "other" }] }],
|
||||
])("rejects malformed category authority without trusting caller context: %j", async categories => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json(categories));
|
||||
expect((await GET(request())).status).toBe(502);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("treats malformed upstream JSON as server failure rather than malformed user input", async () => {
|
||||
fetchMock.mockResolvedValueOnce(new Response("PRIVATE_NOT_JSON", { headers: { "Content-Type": "application/json" } }));
|
||||
const response = await GET(request());
|
||||
expect(response.status).toBe(502);
|
||||
expect(await response.text()).not.toContain("PRIVATE_NOT_JSON");
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("fails closed when the server-only key is unavailable", async () => {
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "");
|
||||
const response = await GET(request());
|
||||
expect(response.status).toBe(503);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("does not expose raw request content, tokens or keys in errors or logs", async () => {
|
||||
const token = jwt();
|
||||
const error = new Error(`PRIVATE_BODY ${token} ${key}`);
|
||||
fetchMock.mockResolvedValueOnce(Response.json({ data: tree }));
|
||||
fetchMock.mockRejectedValueOnce(error);
|
||||
const logs = [vi.spyOn(console, "error"), vi.spyOn(console, "warn"), vi.spyOn(console, "log")];
|
||||
logs.forEach(log => log.mockImplementation(() => {}));
|
||||
const response = await PUT(request("PUT", { token }));
|
||||
expect(response.status).toBe(502);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
const output = await response.text();
|
||||
for (const value of ["PRIVATE_BODY", token, key]) {
|
||||
expect(output).not.toContain(value);
|
||||
expect(JSON.stringify(logs.flatMap(log => log.mock.calls))).not.toContain(value);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("conversation display title metadata proxy", () => {
|
||||
it("renames only the title using fresh server-authenticated owner and project context", async () => {
|
||||
const token = jwt();
|
||||
fetchMock.mockResolvedValueOnce(Response.json(zeroParentTree));
|
||||
fetchMock.mockResolvedValueOnce(Response.json({ session_id: sessionId, title: "새 대화명 2030" }));
|
||||
const response = await PATCH(request("PATCH", { body: { title: " 새 대화명 2030 " }, token, headers: {
|
||||
"X-Conversation-Context": '{"subjectSha256":"foreign","projectIds":["foreign"]}',
|
||||
"X-Rag-V2-Internal-Key": "browser-key", Authorization: jwt("foreign"),
|
||||
} }));
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ session_id: sessionId, title: "새 대화명 2030" });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
const [url, options] = fetchMock.mock.calls[1]!;
|
||||
expect(String(url)).toBe(`http://127.0.0.1:18082/dc-service/api/v1/rag-search/conversation-memory?session_id=${sessionId}`);
|
||||
expect(options).toMatchObject({ method: "PATCH", body: JSON.stringify({ title: "새 대화명 2030" }), cache: "no-store", redirect: "error" });
|
||||
const headers = new Headers(options?.headers);
|
||||
expect(headers.get("Authorization")).toBe(token);
|
||||
expect(headers.get("X-Rag-V2-Internal-Key")).toBe(key);
|
||||
expect(headers.get("Content-Type")).toBe("application/json");
|
||||
expect(JSON.parse(headers.get("X-Conversation-Context")!)).toEqual({
|
||||
version: 1, subjectSha256: createHash("sha256").update(subject).digest("hex"),
|
||||
projectIds: zeroParentTree.map(row => row.clsfSystmSn),
|
||||
});
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it.each([null, "not-a-uuid"])("requires a valid session ID for title edits: %j", async session => {
|
||||
expect((await PATCH(request("PATCH", { session }))).status).toBe(400);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([null, [], {}, { title: 1 }, { title: "" }, { title: " " }, { title: "x".repeat(121) },
|
||||
{ title: "앞\n뒤" }, { title: "\t제목" }, { title: "제목\r" }, { title: "제목\u0000" }, { title: "제목\u007f" },
|
||||
{ title: "제목", messages: [] }, { title: "제목", project_ids: ["foreign"] }, { title: "제목", owner: "foreign" },
|
||||
])("rejects invalid titles or non-title payload fields without dispatch: %j", async body => {
|
||||
const response = await PATCH(request("PATCH", { raw: JSON.stringify(body) }));
|
||||
expect(response.status).toBe(400);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it("accepts the same 120 Unicode-character boundary as the metadata service", async () => {
|
||||
const title = "🙂".repeat(120);
|
||||
expect((await PATCH(request("PATCH", { body: { title } }))).status).toBe(200);
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[1]![1]?.body))).toEqual({ title });
|
||||
});
|
||||
|
||||
it("rejects malformed title JSON without exposing raw content", async () => {
|
||||
const response = await PATCH(request("PATCH", { raw: '{"title":"PRIVATE_BODY"' }));
|
||||
expect(response.status).toBe(400);
|
||||
expect(await response.text()).not.toContain("PRIVATE_BODY");
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["declared", "actual"])("keeps the title request size limit for %s bodies", async mode => {
|
||||
const response = await PATCH(request("PATCH", mode === "declared"
|
||||
? { headers: { "content-length": "1048577" } }
|
||||
: { raw: JSON.stringify({ title: "X".repeat(1_048_577) }) }));
|
||||
expect(response.status).toBe(413);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unauthenticated rename before accessing either service", async () => {
|
||||
expect((await PATCH(request("PATCH", { token: null }))).status).toBe(401);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([401, 403])("preserves a fresh DC permission rejection %i without dispatching the edit", async status => {
|
||||
fetchMock.mockResolvedValueOnce(new Response("PRIVATE_DC", { status }));
|
||||
const response = await PATCH(request("PATCH"));
|
||||
expect(response.status).toBe(status);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect(await response.text()).not.toContain("PRIVATE_DC");
|
||||
});
|
||||
|
||||
it.each([401, 403, 404, 409, 413, 422, 429])("preserves title edit rejection %i without exposing upstream data", async status => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json(tree));
|
||||
fetchMock.mockResolvedValueOnce(new Response("PRIVATE_RENAME_BODY", { status }));
|
||||
const response = await PATCH(request("PATCH"));
|
||||
expect(response.status).toBe(status);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(await response.text()).not.toContain("PRIVATE_RENAME_BODY");
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it("does not dispatch edits without any fresh authorized project roots", async () => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json([]));
|
||||
expect((await PATCH(request("PATCH"))).status).toBe(403);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("keeps private transport failures out of the rename response", async () => {
|
||||
fetchMock.mockResolvedValueOnce(Response.json(tree));
|
||||
fetchMock.mockRejectedValueOnce(new Error(`PRIVATE_RENAME_BODY ${key}`));
|
||||
const response = await PATCH(request("PATCH"));
|
||||
expect(response.status).toBe(502);
|
||||
expect(await response.text()).not.toMatch(/PRIVATE_RENAME_BODY|test-only-server-key/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { AUTH_USER_ID, CLAIM_NAME } from "@/shared/config";
|
||||
import { buildDcServiceRequestHeaders, DC_PREVIEW_RELAY_HEADER, resolveDcServiceUrl } from "@/shared/api/dc-service-request";
|
||||
import { FileRegistryError, ragInternalHeaders, registryAuthHeaders } from "@/server/file-registry-attestation";
|
||||
import { DC_SEARCH_RELAY_PATH, dcGatewayContext } from "@/shared/api/dc-search-relay";
|
||||
import { authenticatedSubjectSha256 } from "@/server/rag-forward-context";
|
||||
import { conversationSearchResponse } from "@/server/conversation-search-preview";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const KEYS = ["version", "session_id", "project_ids", "selected_file_sns", "selected_sources", "natural_domain", "messages"];
|
||||
|
||||
function failure(status: number): NextResponse {
|
||||
return NextResponse.json({ message: status === 401 ? "로그인이 필요합니다."
|
||||
: status === 403 ? "이 대화의 자료관 범위에 접근할 수 없습니다."
|
||||
: status === 404 ? "저장된 대화를 찾을 수 없습니다."
|
||||
: status === 409 ? "대화의 저장 상태가 변경되었습니다. 다시 불러와 주세요."
|
||||
: [400, 413, 422].includes(status) ? "대화 저장 요청을 확인해 주세요."
|
||||
: "저장된 대화를 처리하지 못했습니다. 잠시 후 다시 시도해 주세요." }, {
|
||||
status, headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
async function authorizedHeaders(request: NextRequest): Promise<Headers> {
|
||||
const authenticated = registryAuthHeaders(request);
|
||||
const headers = buildDcServiceRequestHeaders(request, { mode: "browser", forGet: true });
|
||||
headers.set(DC_PREVIEW_RELAY_HEADER, "1");
|
||||
headers.set("Authorization", authenticated.get("Authorization")!);
|
||||
headers.set("X-Site-Id", authenticated.get("X-Site-Id")!);
|
||||
for (const name of ["X-Conversation-Context", "X-Rag-V2-Internal-Key"]) headers.delete(name);
|
||||
if (authenticated.has(AUTH_USER_ID)) headers.set(AUTH_USER_ID, authenticated.get(AUTH_USER_ID)!);
|
||||
else headers.delete(AUTH_USER_ID);
|
||||
const base = process.env.NEXT_PUBLIC_DC_SERVICE_API_URL ?? process.env.DC_SERVICE_API_URL;
|
||||
if (!base) throw new FileRegistryError(503, "UPSTREAM_NOT_CONFIGURED", "자료관 연결 설정이 없습니다.");
|
||||
const response = await fetch(resolveDcServiceUrl("/dc-service/api/v1/clsf", undefined, base), {
|
||||
headers, cache: "no-store", redirect: "error", signal: request.signal,
|
||||
});
|
||||
if (!response.ok) throw new FileRegistryError([401, 403].includes(response.status) ? response.status : 502, "CLASSIFICATION_UNAVAILABLE", "자료관 범위를 확인하지 못했습니다.");
|
||||
let data: unknown;
|
||||
try { data = await response.json(); } catch { throw new Error("invalid classification response"); }
|
||||
const rows = data && typeof data === "object" && "data" in data ? (data as { data: unknown }).data : data;
|
||||
if (!Array.isArray(rows)) throw new Error("invalid classification rows");
|
||||
const roots = new Set<string>(); const seen = new Set<string>();
|
||||
const stack: Array<{ node: unknown; parent?: string }> = rows.map(node => ({ node }));
|
||||
while (stack.length) {
|
||||
const { node, parent } = stack.pop()!;
|
||||
if (!node || typeof node !== "object" || Array.isArray(node)) throw new Error("invalid classification");
|
||||
const row = node as Record<string, unknown>;
|
||||
const id = ["string", "number"].includes(typeof row.clsfSystmSn) ? String(row.clsfSystmSn).trim() : "";
|
||||
const up = row.upClsfSystmSn == null ? "" : String(row.upClsfSystmSn).trim();
|
||||
if (!id || id.length > 256 || seen.has(id) || seen.size >= 100_000 || (parent && up && parent !== up)) throw new Error("invalid classification tree");
|
||||
seen.add(id);
|
||||
if (!parent && (!up || up === "0")) roots.add(id);
|
||||
if (row.children !== undefined && !Array.isArray(row.children)) throw new Error("invalid classification children");
|
||||
for (const child of (row.children as unknown[] | undefined) ?? []) stack.push({ node: child, parent: id });
|
||||
}
|
||||
if (!roots.size || roots.size > 64) throw new FileRegistryError(403, "CLASSIFICATION_NOT_AVAILABLE", "사용 가능한 자료관 범위가 없습니다.");
|
||||
const ragHeaders = ragInternalHeaders(authenticated);
|
||||
ragHeaders.set("X-Conversation-Context", JSON.stringify({ version: 1, subjectSha256: authenticatedSubjectSha256(authenticated), projectIds: [...roots].sort() }));
|
||||
return ragHeaders;
|
||||
}
|
||||
|
||||
async function forward(request: NextRequest, method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"): Promise<Response> {
|
||||
try {
|
||||
const id = request.nextUrl.searchParams.get("session_id");
|
||||
const operation = method === "POST" || (method === "GET" && id === null) ? "conversation-sessions" : "conversation-memory";
|
||||
if (request.nextUrl.pathname.startsWith(DC_SEARCH_RELAY_PATH + "/") &&
|
||||
request.nextUrl.pathname !== `${DC_SEARCH_RELAY_PATH}/${operation}`) return failure(400);
|
||||
if ((id !== null && !UUID.test(id)) || ((method === "DELETE" || method === "PATCH") && !id) || (method === "POST" && id !== null)) return failure(400);
|
||||
let body: Record<string, unknown> | undefined;
|
||||
if (method === "PUT" || method === "PATCH" || method === "POST") {
|
||||
const budget = method === "POST" ? 4096 : 1_048_576;
|
||||
if (Number(request.headers.get("content-length") ?? 0) > budget) return failure(413);
|
||||
const text = await request.text();
|
||||
if (Buffer.byteLength(text, "utf8") > budget) return failure(413);
|
||||
const raw: unknown = JSON.parse(text);
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return failure(400);
|
||||
if (method === "POST") {
|
||||
if (Object.keys(raw).some(key => !["query", "sort", "offset", "limit"].includes(key))) return failure(400);
|
||||
const values = raw as Record<string, unknown>;
|
||||
const { query = "", sort = "recent", offset = 0, limit = 50 } = values;
|
||||
if (typeof query !== "string" || Array.from(query).length > 200 || typeof sort !== "string" || !["recent", "oldest", "title"].includes(sort) ||
|
||||
!Number.isSafeInteger(offset) || (offset as number) < 0 || !Number.isSafeInteger(limit) || (limit as number) < 1 || (limit as number) > 100) return failure(400);
|
||||
body = { query: query.trim(), sort, offset, limit };
|
||||
} else if (method === "PATCH") {
|
||||
const title = (raw as Record<string, unknown>).title;
|
||||
if (Object.keys(raw).length !== 1 || typeof title !== "string" || /[\u0000-\u001f\u007f]/.test(title)) return failure(400);
|
||||
const trimmed = title.trim();
|
||||
if (!trimmed || Array.from(trimmed).length > 120) return failure(400);
|
||||
body = { title: trimmed };
|
||||
} else {
|
||||
body = Object.fromEntries(KEYS.filter(key => key in raw).map(key => [key, (raw as Record<string, unknown>)[key]]));
|
||||
if (typeof body.session_id !== "string" || !UUID.test(body.session_id) || !Array.isArray(body.project_ids) || !body.project_ids.length || body.project_ids.length > 64) return failure(400);
|
||||
}
|
||||
}
|
||||
const headers = await authorizedHeaders(request);
|
||||
if (body) {
|
||||
if (method === "PUT") {
|
||||
const allowed = new Set((JSON.parse(headers.get("X-Conversation-Context")!) as { projectIds: string[] }).projectIds);
|
||||
if (!(body.project_ids as unknown[]).every(value => typeof value === "string" && allowed.has(value))) return failure(403);
|
||||
}
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
for (const [name, value] of Object.entries(dcGatewayContext(request.headers))) headers.set(name, value);
|
||||
headers.set(CLAIM_NAME, headers.get("Authorization")!);
|
||||
|
||||
const url = resolveDcServiceUrl(`${DC_SEARCH_RELAY_PATH}/${operation}`);
|
||||
if (id) url.searchParams.set("session_id", id);
|
||||
const response = await fetch(url, { method, headers, ...(body ? { body: JSON.stringify(body) } : {}), cache: "no-store", redirect: "error", signal: request.signal });
|
||||
if (!response.ok) return failure([400, 401, 403, 404, 409, 413, 422, 429].includes(response.status) ? response.status : 502);
|
||||
if (method === "POST") {
|
||||
let value: unknown;
|
||||
try { value = await response.json(); } catch { throw new Error("invalid conversation search response"); }
|
||||
return NextResponse.json(await conversationSearchResponse(value, body!.query as string), { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
return new Response(response.body, { status: response.status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } });
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) return failure(error.status);
|
||||
if (error instanceof SyntaxError) return failure(400);
|
||||
return failure(request.signal.aborted ? 504 : 502);
|
||||
}
|
||||
}
|
||||
|
||||
export function GET(request: NextRequest) { return forward(request, "GET"); }
|
||||
export function POST(request: NextRequest) { return forward(request, "POST"); }
|
||||
export function PUT(request: NextRequest) { return forward(request, "PUT"); }
|
||||
export function PATCH(request: NextRequest) { return forward(request, "PATCH"); }
|
||||
export function DELETE(request: NextRequest) { return forward(request, "DELETE"); }
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/shared/config", () => ({ CLAIM_NAME: "custom-auth-cookie", AUTH_USER_ID: "token-id" }));
|
||||
vi.mock("next/headers", () => ({
|
||||
cookies: async () => ({ get: (name: string) =>
|
||||
name === "custom-auth-cookie" ? { value: "login.jwt.signature" } : undefined }),
|
||||
}));
|
||||
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";
|
||||
|
||||
afterEach(() => { vi.unstubAllGlobals(); });
|
||||
|
||||
it("uses the same cookie principal for the gateway claim and DC Authorization headers", async () => {
|
||||
const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe("login.jwt.signature");
|
||||
expect(new Headers(init?.headers).get("custom-auth-cookie")).toBe("login.jwt.signature");
|
||||
return new Response("data: done\n\n", { headers: { "Content-Type": "text/event-stream" } });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(new NextRequest("https://dc.invalid/api/flask-service/ask-question", {
|
||||
method: "POST", body: JSON.stringify({ question: "자료관 질문" }),
|
||||
}));
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
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" }));
|
||||
import { POST } from "./route";
|
||||
|
||||
const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEifQ.signature";
|
||||
const fileSn = "68f53c04-36d9-4ae3-8051-3ad1603d0fc5";
|
||||
const request = (body: Record<string, unknown>) => new NextRequest("https://dc.invalid/api/flask-service/ask-question", {
|
||||
method: "POST", body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
state.token = jwt;
|
||||
vi.stubEnv("FLASK_API_URL", "https://rag.invalid");
|
||||
vi.stubEnv("DC_SERVICE_API_URL", "https://dc-service.invalid");
|
||||
});
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
|
||||
|
||||
describe("frontend chat scope forwarding", () => {
|
||||
it("sends an unselected question and its project scope through DC", async () => {
|
||||
const calls: string[] = [];
|
||||
let forwarded: Record<string, unknown> | undefined;
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
calls.push(url);
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe(jwt);
|
||||
if (url.endsWith("/ask-question")) {
|
||||
forwarded = JSON.parse(String(init?.body));
|
||||
return new Response("data: done\n\n", { headers: { "content-type": "text/event-stream" } });
|
||||
}
|
||||
throw new Error("unexpected URL");
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(request({
|
||||
question: "강릉시 하수도정비 계획의 목적 알려줘", project_ids: ["root"],
|
||||
category_attestation: "forged-browser-selection", registry_context: { fileSn: "forged" },
|
||||
registryContext: {}, categoryContext: {}, subjectSha256: "forged",
|
||||
}));
|
||||
expect(response.status).toBe(200);
|
||||
expect(calls).toEqual(["https://dc-service.invalid/dc-service/api/v1/rag-search/ask-question"]);
|
||||
expect(forwarded?.project_ids).toEqual(["root"]);
|
||||
expect(forwarded).not.toHaveProperty("source");
|
||||
expect(forwarded).not.toHaveProperty("category_attestation");
|
||||
expect(forwarded).not.toHaveProperty("registry_context");
|
||||
expect(forwarded).not.toHaveProperty("registryContext");
|
||||
expect(forwarded).not.toHaveProperty("categoryContext");
|
||||
expect(forwarded).not.toHaveProperty("subjectSha256");
|
||||
});
|
||||
|
||||
it("skips category preflight and registry reads for a selected source", async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
expect(String(input)).toBe("https://dc-service.invalid/dc-service/api/v1/rag-search/ask-question");
|
||||
expect(JSON.parse(String(init?.body))).toEqual({ question: "문서 내용", source: [fileSn] });
|
||||
return new Response("data: done\n\n");
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await POST(request({
|
||||
question: "문서 내용", source: [fileSn], category_attestation: "forged", registry_context: {},
|
||||
}))).status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("forwards an ordinary unselected question without a registry read", async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
expect(url).toBe("https://dc-service.invalid/dc-service/api/v1/rag-search/ask-question");
|
||||
expect(JSON.parse(String(init?.body))).toEqual({ question: "사업 효과" });
|
||||
return new Response("done");
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await POST(request({ question: "사업 효과", category_attestation: "forged" }))).status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("preserves the upstream authentication failure", async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
expect(String(input)).toBe("https://dc-service.invalid/dc-service/api/v1/rag-search/ask-question");
|
||||
return new Response(null, { status: 401 });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(request({ question: "기본계획", project_ids: ["root"] }));
|
||||
expect(response.status).toBe(401);
|
||||
expect((await response.json()).error).toContain("로그인이 만료");
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { createServer, type Server, type ServerResponse } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("next/headers", () => ({ cookies: async () => ({ get: () => undefined }) }));
|
||||
import { POST } from "../../../dc-service/api/v1/rag-search/ask-question/route";
|
||||
|
||||
const first = 'data: {"type":"chunk","text":"첫 답변"}\n\n';
|
||||
const last = 'data: {"type":"done","text":"완료"}\n\n';
|
||||
let gateway: Server;
|
||||
let upstream: ServerResponse;
|
||||
let closed: boolean;
|
||||
let paths: string[];
|
||||
|
||||
beforeEach(async () => {
|
||||
paths = [];
|
||||
closed = false;
|
||||
gateway = createServer((req, res) => {
|
||||
paths.push(req.method + " " + req.url);
|
||||
upstream = res;
|
||||
res.once("close", () => { closed = true; });
|
||||
res.writeHead(200, { "Content-Type": "text/event-stream", "X-Request-Id": "dc-loopback" });
|
||||
res.write(first);
|
||||
});
|
||||
await new Promise<void>(resolve => gateway.listen(0, "127.0.0.1", resolve));
|
||||
vi.stubEnv("DC_SERVICE_API_URL", `http://127.0.0.1:${(gateway.address() as AddressInfo).port}`);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
gateway.closeAllConnections();
|
||||
await new Promise<void>(resolve => gateway.close(() => resolve()));
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
function ask(signal?: AbortSignal) {
|
||||
return POST(new NextRequest("http://localhost/dc-service/api/v1/rag-search/ask-question", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ question: "고정 입력" }),
|
||||
signal,
|
||||
}));
|
||||
}
|
||||
|
||||
it("streams the first event over the DC relay before the gateway sends DONE", async () => {
|
||||
const response = await ask();
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toBe("text/event-stream");
|
||||
expect(response.headers.get("x-request-id")).toBe("dc-loopback");
|
||||
const reader = response.body!.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
expect(decoder.decode((await reader.read()).value)).toBe(first);
|
||||
upstream.end(last);
|
||||
expect(decoder.decode((await reader.read()).value)).toBe(last);
|
||||
expect((await reader.read()).done).toBe(true);
|
||||
expect(paths).toEqual(["POST /dc-service/api/v1/rag-search/ask-question"]);
|
||||
});
|
||||
|
||||
it("closes the active DC gateway stream when the requesting client stops", async () => {
|
||||
const stop = new AbortController();
|
||||
const response = await ask(stop.signal);
|
||||
expect(response.status).toBe(200);
|
||||
const reader = response.body!.getReader();
|
||||
expect(new TextDecoder().decode((await reader.read()).value)).toBe(first);
|
||||
stop.abort();
|
||||
await vi.waitFor(() => expect(closed).toBe(true));
|
||||
await expect(reader.read()).rejects.toMatchObject({ name: "AbortError" });
|
||||
expect(paths).toHaveLength(1);
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
CLAIM_NAME,
|
||||
AUTH_USER_ID,
|
||||
} from "@/shared/config";
|
||||
import { SITE_ID } from "@/shared/config/env";
|
||||
import { FileRegistryError } from "@/server/file-registry-attestation";
|
||||
import { stripBrowserRagContext } from "@/server/rag-forward-context";
|
||||
import { resolveDcServiceUrl } from "@/shared/api/dc-service-request";
|
||||
import { DC_SEARCH_RELAY_PATH, dcGatewayContext } from "@/shared/api/dc-search-relay";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 300;
|
||||
|
||||
const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
// Correlation only; a caller ID never supplies authentication or access scope.
|
||||
let requestId: string = randomUUID();
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get(CLAIM_NAME)?.value;
|
||||
const userId = cookieStore.get(AUTH_USER_ID)?.value;
|
||||
|
||||
const parsed: unknown = await request.json();
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||
return NextResponse.json(
|
||||
{ error: "질문 요청 형식이 올바르지 않습니다." },
|
||||
{ status: 400, headers: { "Cache-Control": "no-store", "x-request-id": requestId } },
|
||||
);
|
||||
}
|
||||
const body = { ...parsed } as Record<string, unknown>;
|
||||
stripBrowserRagContext(body);
|
||||
|
||||
const headers: HeadersInit = {
|
||||
...dcGatewayContext(request.headers),
|
||||
"Content-Type": "application/json",
|
||||
Accept: "text/event-stream",
|
||||
"X-Site-Id": SITE_ID,
|
||||
"x-request-id": requestId,
|
||||
};
|
||||
if (token) {
|
||||
if (CLAIM_NAME.toLowerCase() !== "authorization") headers[CLAIM_NAME] = token;
|
||||
headers.Authorization = token;
|
||||
}
|
||||
if (userId) headers[AUTH_USER_ID] = userId;
|
||||
|
||||
const controller = new AbortController();
|
||||
// Keep the downstream disconnect connected after the SSE headers arrive.
|
||||
if (request.signal.aborted) controller.abort();
|
||||
else request.signal.addEventListener("abort", () => controller.abort(), { once: true });
|
||||
const timeoutId = setTimeout(() => controller.abort(), 600000);
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
resolveDcServiceUrl(`${DC_SEARCH_RELAY_PATH}/ask-question`),
|
||||
{
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
signal: controller.signal,
|
||||
redirect: "error",
|
||||
cache: "no-store",
|
||||
}
|
||||
);
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
const upstreamRequestId = response.headers.get("x-request-id");
|
||||
if (upstreamRequestId && REQUEST_ID_PATTERN.test(upstreamRequestId)) {
|
||||
requestId = upstreamRequestId;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn("[ask-question] upstream_http_error", { status: response.status });
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: response.status === 401 ? "로그인이 만료되었습니다. 다시 로그인해 주세요."
|
||||
: response.status === 403 ? "선택한 문서에 접근할 수 없습니다."
|
||||
: "문서 답변 요청을 처리하지 못했습니다.",
|
||||
},
|
||||
{ status: response.status, headers: { "Cache-Control": "no-store", "x-request-id": requestId } }
|
||||
);
|
||||
}
|
||||
|
||||
const contentType =
|
||||
response.headers.get("content-type") ?? "text/event-stream";
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
headers: {
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "no-store, no-transform",
|
||||
Connection: "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
"x-request-id": requestId,
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
clearTimeout(timeoutId);
|
||||
if (request.signal.aborted) {
|
||||
return new Response(null, { status: 499, headers: { "x-request-id": requestId } });
|
||||
}
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
console.warn("[ask-question] upstream_timeout", { status: 504 });
|
||||
return NextResponse.json(
|
||||
{ error: "요청 시간이 초과되었습니다. 잠시 후 다시 시도해 주세요." },
|
||||
{ status: 504, headers: { "Cache-Control": "no-store", "x-request-id": requestId } }
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) {
|
||||
return NextResponse.json(
|
||||
{ error: "질문에 필요한 자료관 분류와 문서 정보를 확인하지 못했습니다.", code: error.code },
|
||||
{ status: error.status, headers: { "Cache-Control": "no-store", "x-request-id": requestId } },
|
||||
);
|
||||
}
|
||||
console.error("[ask-question] request_failed", { status: 500 });
|
||||
return NextResponse.json(
|
||||
{ error: "서버 오류가 발생했습니다." },
|
||||
{ status: 500, headers: { "Cache-Control": "no-store", "x-request-id": requestId } }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { registryForwardContext } from "@/server/rag-forward-context";
|
||||
import {
|
||||
attestRegisteredFile,
|
||||
dcRagUrl,
|
||||
FileRegistryError,
|
||||
registryAuthHeaders,
|
||||
} from "@/server/file-registry-attestation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 60;
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
|
||||
function record(value: unknown): JsonRecord | null {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? value as JsonRecord
|
||||
: null;
|
||||
}
|
||||
|
||||
function text(value: unknown): string {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function failure(status: number, code: string, message: string): NextResponse {
|
||||
return NextResponse.json({ code, error: message }, {
|
||||
status,
|
||||
headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
function dcServiceImportUrl(): URL {
|
||||
const base = process.env.DC_SERVICE_API_URL ?? process.env.NEXT_PUBLIC_DC_SERVICE_API_URL;
|
||||
if (!base) {
|
||||
throw new FileRegistryError(503, "UPSTREAM_NOT_CONFIGURED", "자료관 연결 설정이 없습니다.");
|
||||
}
|
||||
try {
|
||||
const url = new URL(`${base.replace(/\/+$/, "")}/dc-service/api/v1/gnsvy/imports`);
|
||||
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
|
||||
throw new Error("invalid upstream URL");
|
||||
}
|
||||
return url;
|
||||
} catch {
|
||||
throw new FileRegistryError(503, "UPSTREAM_NOT_CONFIGURED", "자료관 연결 설정을 확인해 주세요.");
|
||||
}
|
||||
}
|
||||
|
||||
function verifiedArtifact(job: JsonRecord): { fileSn: string; payload: JsonRecord } | null {
|
||||
if (job.type !== "EMBED_DOCUMENTS" || job.status !== "DONE") {
|
||||
throw new FileRegistryError(409, "EMBED_JOB_NOT_DONE", "임베딩 작업 완료를 확인하지 못했습니다.");
|
||||
}
|
||||
const result = record(job.result);
|
||||
if (!result) {
|
||||
throw new FileRegistryError(502, "EMBED_RESULT_INVALID", "임베딩 결과를 확인할 수 없습니다.");
|
||||
}
|
||||
if (result.general_survey_import == null) return null;
|
||||
|
||||
const payload = record(result.general_survey_import);
|
||||
const files = result.embedded_files;
|
||||
const profile = record(result.ingest_profile);
|
||||
const file = Array.isArray(files) && files.length === 1 ? record(files[0]) : null;
|
||||
const fileSn = text(file?.file_sn);
|
||||
const digest = text(profile?.pdf_sha256).toLowerCase();
|
||||
if (!payload || payload.status !== "parsed" || !fileSn ||
|
||||
text(payload.file_sn) !== fileSn || !/^[a-f0-9]{64}$/.test(digest) ||
|
||||
text(payload.document_id) !== `sha256:${digest}`) {
|
||||
throw new FileRegistryError(502, "SURVEY_HANDOFF_INVALID", "총설 등록 근거를 확인할 수 없습니다.");
|
||||
}
|
||||
return { fileSn, payload };
|
||||
}
|
||||
|
||||
/** Finish a successful RAG embed by handing its verified survey artifact to dc-service. */
|
||||
export async function POST(request: NextRequest): Promise<NextResponse> {
|
||||
try {
|
||||
if (Number(request.headers.get("content-length") ?? 0) > 1024) {
|
||||
return failure(413, "COMPLETE_EMBED_REQUEST_TOO_LARGE", "작업 확인 요청이 너무 큽니다.");
|
||||
}
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return failure(400, "COMPLETE_EMBED_REQUEST_INVALID", "작업 확인 요청이 올바르지 않습니다.");
|
||||
}
|
||||
const jobId = text(record(body)?.jobId);
|
||||
const completionAttestation = text(record(body)?.completionAttestation);
|
||||
if (!/^[a-f0-9-]{36}$/i.test(jobId)) {
|
||||
return failure(400, "COMPLETE_EMBED_REQUEST_INVALID", "작업 식별자가 올바르지 않습니다.");
|
||||
}
|
||||
if (!completionAttestation || completionAttestation.length > 8192) {
|
||||
return failure(403, "COMPLETE_EMBED_AUTHORITY_INVALID", "작업 완료 권한을 확인하지 못했습니다.");
|
||||
}
|
||||
|
||||
const headers = registryAuthHeaders(request);
|
||||
let jobResponse: Response;
|
||||
try {
|
||||
jobResponse = await fetch(dcRagUrl(`/jobs/${jobId}`), {
|
||||
method: "GET", headers, cache: "no-store", signal: request.signal,
|
||||
});
|
||||
} catch {
|
||||
return failure(502, "EMBED_JOB_UNAVAILABLE", "임베딩 결과를 조회할 수 없습니다.");
|
||||
}
|
||||
if (!jobResponse.ok) {
|
||||
return failure(502, "EMBED_JOB_UNAVAILABLE", "임베딩 결과를 조회할 수 없습니다.");
|
||||
}
|
||||
const job = record(await jobResponse.json().catch(() => null));
|
||||
if (!job || job.job_id !== jobId) {
|
||||
return failure(502, "EMBED_JOB_INVALID", "임베딩 작업 결과가 올바르지 않습니다.");
|
||||
}
|
||||
const handoff = verifiedArtifact(job);
|
||||
if (!handoff) {
|
||||
return NextResponse.json({ imported: false }, { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
// Validate the current user token with dc-service before consuming RAG's
|
||||
// one-time completion capability. The job artifact alone grants no write.
|
||||
const registered = await attestRegisteredFile(request, { fileSn: handoff.fileSn });
|
||||
const verifyHeaders = registryAuthHeaders(request);
|
||||
verifyHeaders.set("Content-Type", "application/json");
|
||||
const registryContext = registryForwardContext(registered, verifyHeaders);
|
||||
let verifyResponse: Response;
|
||||
try {
|
||||
verifyResponse = await fetch(dcRagUrl(`/jobs/${jobId}/verify-completion`), {
|
||||
method: "POST",
|
||||
headers: verifyHeaders,
|
||||
body: JSON.stringify({
|
||||
completionAttestation,
|
||||
fileSn: registered.fileSn,
|
||||
registryContext,
|
||||
}),
|
||||
cache: "no-store",
|
||||
signal: request.signal,
|
||||
redirect: "error",
|
||||
});
|
||||
} catch {
|
||||
return failure(502, "COMPLETE_EMBED_AUTHORITY_UNCERTAIN", "작업 완료 권한을 확인하지 못했습니다.");
|
||||
}
|
||||
if (!verifyResponse.ok) {
|
||||
return failure(verifyResponse.status === 403 || verifyResponse.status === 409 ? 403 : 502,
|
||||
"COMPLETE_EMBED_AUTHORITY_INVALID", "작업 완료 권한을 확인하지 못했습니다.");
|
||||
}
|
||||
const verified = record(await verifyResponse.json().catch(() => null));
|
||||
if (verified?.verified !== true) {
|
||||
return failure(502, "COMPLETE_EMBED_AUTHORITY_UNCERTAIN", "작업 완료 권한을 확인하지 못했습니다.");
|
||||
}
|
||||
|
||||
const dcHeaders = registryAuthHeaders(request);
|
||||
dcHeaders.set("Content-Type", "application/json");
|
||||
const importUrl = dcServiceImportUrl();
|
||||
let importResponse: Response;
|
||||
try {
|
||||
// No automatic retry: a failed connection after dispatch has an unknown outcome.
|
||||
importResponse = await fetch(importUrl, {
|
||||
method: "POST", headers: dcHeaders, body: JSON.stringify(handoff.payload), cache: "no-store",
|
||||
});
|
||||
} catch {
|
||||
return failure(502, "GENERAL_SURVEY_IMPORT_UNCERTAIN", "총설 등록 결과를 확인하지 못했습니다. 관리자 확인이 필요합니다.");
|
||||
}
|
||||
if (!importResponse.ok) {
|
||||
const uncertain = importResponse.status >= 500;
|
||||
return failure(
|
||||
uncertain ? 502 : 422,
|
||||
uncertain ? "GENERAL_SURVEY_IMPORT_UNCERTAIN" : "GENERAL_SURVEY_IMPORT_FAILED",
|
||||
uncertain
|
||||
? "총설 등록 결과를 확인하지 못했습니다. 관리자 확인이 필요합니다."
|
||||
: "총설 등록을 완료하지 못했습니다.",
|
||||
);
|
||||
}
|
||||
const imported = record(await importResponse.json().catch(() => null));
|
||||
if (!imported || imported.status !== "IMPORTED" || imported.saved_count !== 9) {
|
||||
return failure(502, "GENERAL_SURVEY_IMPORT_UNCERTAIN", "총설 등록 결과를 확인하지 못했습니다. 관리자 확인이 필요합니다.");
|
||||
}
|
||||
return NextResponse.json({ imported: true }, { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) {
|
||||
return failure(error.status, error.code, error.message);
|
||||
}
|
||||
return failure(502, "COMPLETE_EMBED_FAILED", "임베딩 후속 등록을 완료하지 못했습니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { POST } from "./route";
|
||||
|
||||
const authority = vi.hoisted(() => ({ registry: vi.fn(), owner: vi.fn() }));
|
||||
vi.mock("@/server/file-registry-attestation", async importOriginal => ({
|
||||
...await importOriginal<typeof import("@/server/file-registry-attestation")>(),
|
||||
attestRegisteredFile: authority.registry, attestReuploadOwner: authority.owner,
|
||||
}));
|
||||
const jobId = "123e4567-e89b-42d3-a456-426614174000";
|
||||
const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEifQ.signature";
|
||||
const registered = { fileSn: "file-1", projectId: "project-1", clsfSystmSn: "category-1", classificationPath: ["p", "c"], useYn: "Y" };
|
||||
const body = { file_sn: "file-1", project_id: "project-1", clsf_systm_sn: "category-1" };
|
||||
const request = (data: unknown = body) => new NextRequest("https://dc.invalid/api/flask-service/conversion-failures/lookup", {
|
||||
method: "POST", headers: { "Content-Type": "application/json", Cookie: `Authorization=${jwt}` },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const call = (action: string, data?: unknown) => POST(request(data), { params: Promise.resolve({ action }) });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("FLASK_API_URL", "https://rag.invalid");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "existing-test-key");
|
||||
authority.registry.mockResolvedValue(registered);
|
||||
authority.owner.mockResolvedValue(undefined);
|
||||
});
|
||||
afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals(); });
|
||||
|
||||
describe("conversion failure-history registry proxy", () => {
|
||||
it.each(["lookup", "record"])("attests both read scope and owner before %s; replaces browser authority", async action => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json({ file_sn: "file-1", status: "FAILED", failures: [] }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await call(action, { ...body, conversion_job_id: jobId,
|
||||
source_path: "/attacker", registry_context: { subjectSha256: "forged" } });
|
||||
expect(response.status).toBe(200);
|
||||
expect(authority.registry).toHaveBeenCalledOnce();
|
||||
expect(authority.owner).toHaveBeenCalledOnce();
|
||||
const [url, init] = fetchMock.mock.calls[0]!;
|
||||
expect(String(url)).toBe(`https://rag.invalid/flask-service/convert-to-pdf/failures/${action}`);
|
||||
const sent = JSON.parse(init.body);
|
||||
expect(sent.file_sn).toBe("file-1");
|
||||
expect(sent.registry_context).toMatchObject(registered);
|
||||
expect(sent.registry_context.subjectSha256).not.toBe("forged");
|
||||
expect(sent.source_path).toBeUndefined();
|
||||
expect(new Headers(init.headers).get("X-Rag-V2-Internal-Key")).toBe("existing-test-key");
|
||||
expect(new Headers(init.headers).get("Authorization")).toBe(jwt);
|
||||
expect(response.headers.get("Cache-Control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it.each(["retry", "quarantine", "../retry", "unknown"])("does not forward an unrecognized action %s", async action => {
|
||||
const fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await call(action)).status).toBe(404);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a missing failed job for recording before dispatch", async () => {
|
||||
const fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await call("record")).status).toBe(400);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("blocks unauthorized documents before failure-history access", async () => {
|
||||
const { FileRegistryError } = await import("@/server/file-registry-attestation");
|
||||
authority.owner.mockRejectedValue(new FileRegistryError(403, "REUPLOAD_OWNER_FORBIDDEN", "문서 권한이 없습니다."));
|
||||
const fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await call("record", { ...body, conversion_job_id: jobId })).status).toBe(403);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves an upstream conflict and never automatically repeats a lost failure-record receipt", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValueOnce(Response.json({ detail: "PROCESSING" }, { status: 409 }))
|
||||
.mockRejectedValueOnce(new TypeError("lost response"));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await call("record", { ...body, conversion_job_id: jobId })).status).toBe(409);
|
||||
const unknown = await call("record", { ...body, conversion_job_id: jobId });
|
||||
expect(unknown.status).toBe(502);
|
||||
expect((await unknown.json()).detail.dispatchState).toBe("UNKNOWN");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { registryForwardContext } from "@/server/rag-forward-context";
|
||||
import { operationDiagnostics } from "@/server/operation-diagnostics";
|
||||
import {
|
||||
attestRegisteredFile, attestReuploadOwner, dcRagUrl, FileRegistryError,
|
||||
ragInternalHeaders, registryAuthHeaders,
|
||||
} from "@/server/file-registry-attestation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 60;
|
||||
|
||||
/** Failure recording and lookup never create a document-processing job. */
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
context: { params: Promise<{ action: string }> },
|
||||
): Promise<Response> {
|
||||
const diagnostic = operationDiagnostics("conversion-failures");
|
||||
let dispatched = false;
|
||||
let fileSn: string | undefined;
|
||||
const fail = (status: number, code: string, message: string) => diagnostic.finish(
|
||||
NextResponse.json({ detail: { code, message, dispatchState: dispatched ? "UNKNOWN" : "NOT_SENT" } }, {
|
||||
status, headers: { "Cache-Control": "no-store" },
|
||||
}), { code, fileSn },
|
||||
);
|
||||
try {
|
||||
const { action } = await context.params;
|
||||
if (!["lookup", "record"].includes(action)) {
|
||||
return fail(404, "CONVERSION_FAILURES_NOT_FOUND", "요청한 실패 이력 기능을 찾지 못했습니다.");
|
||||
}
|
||||
if (Number(request.headers.get("content-length") ?? 0) > 16_384) {
|
||||
return fail(413, "CONVERSION_FAILURES_TOO_LARGE", "실패 이력 요청 크기를 초과했습니다.");
|
||||
}
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
const raw: unknown = await request.json();
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("invalid body");
|
||||
body = raw as Record<string, unknown>;
|
||||
} catch {
|
||||
return fail(400, "CONVERSION_FAILURES_INVALID", "실패 이력 요청이 올바르지 않습니다.");
|
||||
}
|
||||
fileSn = typeof body.file_sn === "string" ? body.file_sn : undefined;
|
||||
const projectId = typeof body.project_id === "string" ? body.project_id : "";
|
||||
const classification = typeof body.clsf_systm_sn === "string" ? body.clsf_systm_sn : "";
|
||||
const idField = action === "record" ? "conversion_job_id" : null;
|
||||
if (!fileSn || !/^[A-Za-z0-9_-]{1,128}$/.test(fileSn) || !projectId || !classification ||
|
||||
(idField && (typeof body[idField] !== "string" || !/^[a-f0-9-]{36}$/i.test(body[idField] as string)))) {
|
||||
return fail(400, "CONVERSION_FAILURES_INVALID", "파일·분류·실패 작업 정보를 확인해 주세요.");
|
||||
}
|
||||
const registered = await attestRegisteredFile(request, { fileSn, projectId, clsfSystmSn: classification });
|
||||
// Keep the same owner boundary for retained registration-failure history.
|
||||
await attestReuploadOwner(request, registered);
|
||||
const headers = ragInternalHeaders(registryAuthHeaders(request));
|
||||
headers.set("Content-Type", "application/json");
|
||||
headers.set("x-request-id", diagnostic.requestId);
|
||||
const payload = {
|
||||
file_sn: registered.fileSn,
|
||||
registry_context: registryForwardContext(registered, headers),
|
||||
...(idField ? { [idField]: body[idField] } : {}),
|
||||
};
|
||||
dispatched = true;
|
||||
const upstream = await fetch(dcRagUrl(`/convert-to-pdf/failures/${action}`), {
|
||||
method: "POST", headers, body: JSON.stringify(payload), cache: "no-store", signal: request.signal,
|
||||
});
|
||||
const response = new Response(await upstream.text(), {
|
||||
status: upstream.status,
|
||||
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
|
||||
});
|
||||
return diagnostic.finish(response, { fileSn, upstreamRequestId: upstream.headers.get("x-request-id") });
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) return fail(error.status, error.code, error.message);
|
||||
return fail(request.signal.aborted ? 499 : 502, "CONVERSION_FAILURES_UNAVAILABLE",
|
||||
"실패 이력 요청 결과를 확인하지 못했습니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { GET, POST } from "./route";
|
||||
import { attestRegisteredFile } from "@/server/file-registry-attestation";
|
||||
import { attestReuploadOwner } from "@/server/file-registry-attestation";
|
||||
|
||||
const fileSn = "00000000-0000-4000-8000-000000000001";
|
||||
vi.mock("@/server/file-registry-attestation", async importOriginal => {
|
||||
const original = await importOriginal<typeof import("@/server/file-registry-attestation")>();
|
||||
return {
|
||||
...original,
|
||||
attestRegisteredFile: vi.fn(async () => ({
|
||||
fileSn, projectId: "trusted-project", clsfSystmSn: "trusted-leaf",
|
||||
classificationPath: ["trusted-project", "trusted-leaf"], useYn: "Y",
|
||||
})),
|
||||
attestReuploadOwner: vi.fn(async () => undefined),
|
||||
registryAuthHeaders: vi.fn(() => new Headers({
|
||||
Authorization: `Bearer x.${Buffer.from(JSON.stringify({ sub: "test-user" })).toString("base64url")}.y`,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
describe("Current source lookup", () => {
|
||||
afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); vi.clearAllMocks(); });
|
||||
|
||||
it("derives project and classification from authenticated registry for fileSn-only UI reads", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
const upstream = vi.fn(async (_url: URL, init: RequestInit) => {
|
||||
const body = init.body as FormData;
|
||||
expect(body.get("file_sn")).toBe(fileSn);
|
||||
expect(body.get("project_id")).toBe("trusted-project");
|
||||
expect(body.get("clsf_systm_sn")).toBe("trusted-leaf");
|
||||
expect(new Headers(init.headers).get("X-Rag-V2-Internal-Key")).toBe("test-only-internal-key");
|
||||
return Response.json({ file_sn: fileSn, state: "READY" });
|
||||
});
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
const request = new NextRequest("http://localhost/api/flask-service/current-source", {
|
||||
method: "POST", body: JSON.stringify({ fileSn }), headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
const response = await POST(request);
|
||||
expect(response.status).toBe(200);
|
||||
expect(attestRegisteredFile).toHaveBeenCalledWith(request, { fileSn, projectId: "", clsfSystmSn: "" });
|
||||
expect(attestReuploadOwner).not.toHaveBeenCalled();
|
||||
expect(upstream).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("fails closed before RAG dispatch if the server-only key is absent", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "");
|
||||
const upstream = vi.fn();
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
const response = await POST(new NextRequest("http://localhost/api/flask-service/current-source", {
|
||||
method: "POST", body: JSON.stringify({ fileSn }), headers: { "Content-Type": "application/json" },
|
||||
}));
|
||||
expect(response.status).toBe(503);
|
||||
expect(upstream).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Current revision preview forwarding", () => {
|
||||
afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); vi.clearAllMocks(); });
|
||||
it("forwards literal keyword text only for the authenticated revision page", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
const keyword = "하수처리수 25.27%(A+B) & 관리\n계획";
|
||||
const upstream = vi.fn(async (_url, init) => {
|
||||
const form = init.body as FormData;
|
||||
expect(form.get("preview_keyword")).toBe(keyword);
|
||||
expect(form.get("preview_revision_id")).toBe("rev-current");
|
||||
expect(form.get("preview_page")).toBe("47");
|
||||
expect(form.get("file_sn")).toBe(fileSn);
|
||||
expect(form.get("project_id")).toBe("trusted-project");
|
||||
expect(new Headers(init.headers).get("X-Rag-V2-Internal-Key")).toBe("test-only-internal-key");
|
||||
return new Response(new Uint8Array([137, 80, 78, 71]), { headers: { "Content-Type": "image/png" } });
|
||||
});
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
const params = new URLSearchParams({ fileSn, previewRevisionId: "rev-current", previewPage: "47", previewKeyword: keyword });
|
||||
const response = await GET(new NextRequest(`http://localhost/api/flask-service/current-source?${params}`));
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(upstream).toHaveBeenCalledOnce();
|
||||
});
|
||||
it.each([
|
||||
{ previewKeyword: "관로" },
|
||||
{ previewKeyword: "관로", previewRevisionId: "rev" },
|
||||
{ previewKeyword: " ", previewRevisionId: "rev", previewPage: 2 },
|
||||
{ previewKeyword: ["관로"], previewRevisionId: "rev", previewPage: 2 },
|
||||
])("rejects an unbound or malformed highlight request before dispatch: %j", async body => {
|
||||
const upstream = vi.fn(); vi.stubGlobal("fetch", upstream);
|
||||
const response = await POST(new NextRequest("http://localhost/api/flask-service/current-source", {
|
||||
method: "POST", body: JSON.stringify({ fileSn, ...body }), headers: { "Content-Type": "application/json" },
|
||||
}));
|
||||
expect(response.status).toBe(400);
|
||||
expect(upstream).not.toHaveBeenCalled();
|
||||
});
|
||||
it("forwards lightweight Current preview mode without needing original-file source metadata", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
const upstream = vi.fn(async (_url, init) => {
|
||||
const form = init.body as FormData;
|
||||
expect(form.get("preview_mode")).toBe("true");
|
||||
expect(form.has("preview_revision_id")).toBe(false);
|
||||
expect(form.get("project_id")).toBe("trusted-project");
|
||||
return Response.json({ files: ["page_1.png"], total_pages: 1, document_revision_id: "rev-current" });
|
||||
});
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
const response = await POST(new NextRequest("http://localhost/api/flask-service/current-source", {
|
||||
method: "POST", body: JSON.stringify({ fileSn, previewMode: true }), headers: { "Content-Type": "application/json" },
|
||||
}));
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect((await response.json()).document_revision_id).toBe("rev-current");
|
||||
});
|
||||
it("streams one authenticated revision page as unchanged PNG bytes", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
const png = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 255, 0]);
|
||||
vi.stubGlobal("fetch", vi.fn(async (_url, init) => {
|
||||
const form = init.body as FormData;
|
||||
expect(form.get("preview_revision_id")).toBe("rev-current");
|
||||
expect(form.get("preview_page")).toBe("2");
|
||||
expect(form.get("file_sn")).toBe(fileSn);
|
||||
expect(form.get("clsf_systm_sn")).toBe("trusted-leaf");
|
||||
return new Response(png, { headers: { "Content-Type": "image/png" } });
|
||||
}));
|
||||
const request = new NextRequest(`http://localhost/api/flask-service/current-source?fileSn=${fileSn}&previewRevisionId=rev-current&previewPage=2`);
|
||||
const response = await GET(request);
|
||||
expect(attestRegisteredFile).toHaveBeenCalledWith(request, { fileSn, projectId: "", clsfSystmSn: "" });
|
||||
expect(response.headers.get("content-type")).toBe("image/png");
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(new Uint8Array(await response.arrayBuffer())).toEqual(png);
|
||||
});
|
||||
it("retains upstream revision conflicts without serving old images", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ detail: "CURRENT_PREVIEW_REVISION_CHANGED" }, { status: 409 })));
|
||||
const response = await GET(new NextRequest(`http://localhost/api/flask-service/current-source?fileSn=${fileSn}&previewRevisionId=old-rev&previewPage=1`));
|
||||
expect(response.status).toBe(409);
|
||||
expect(await response.json()).toEqual({ detail: "CURRENT_PREVIEW_REVISION_CHANGED" });
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
});
|
||||
it("rejects invalid pages before upstream dispatch", async () => {
|
||||
const upstream = vi.fn(); vi.stubGlobal("fetch", upstream);
|
||||
const response = await GET(new NextRequest(`http://localhost/api/flask-service/current-source?fileSn=${fileSn}&previewRevisionId=rev&previewPage=0`));
|
||||
expect(response.status).toBe(400); expect(upstream).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { registryForwardContext } from "@/server/rag-forward-context";
|
||||
import {
|
||||
attestRegisteredFile,
|
||||
dcRagUrl,
|
||||
FileRegistryError,
|
||||
ragInternalHeaders,
|
||||
registryAuthHeaders,
|
||||
} from "@/server/file-registry-attestation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
async function forwardCurrentSource(request: NextRequest, body: Record<string, unknown>): Promise<Response> {
|
||||
try {
|
||||
const expected = {
|
||||
fileSn: String(body?.fileSn ?? ""),
|
||||
projectId: String(body?.projectId ?? ""),
|
||||
clsfSystmSn: String(body?.clsfSystmSn ?? ""),
|
||||
};
|
||||
if (!expected.fileSn) {
|
||||
return NextResponse.json({ detail: "CURRENT_SOURCE_REQUEST_INVALID" }, { status: 400, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
const previewRevisionId = String(body?.previewRevisionId ?? "").trim();
|
||||
const previewPage = body?.previewPage == null || body.previewPage === "" ? undefined : Number(body.previewPage);
|
||||
const previewKeyword = body?.previewKeyword;
|
||||
if (previewRevisionId.length > 512 || (previewPage !== undefined &&
|
||||
(!previewRevisionId || !Number.isSafeInteger(previewPage) || previewPage < 1)) ||
|
||||
(previewKeyword !== undefined && (typeof previewKeyword !== "string" ||
|
||||
!previewKeyword.trim() || !previewRevisionId || previewPage === undefined))) {
|
||||
return NextResponse.json({ detail: "CURRENT_PREVIEW_REQUEST_INVALID" }, {
|
||||
status: 400, headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
const registered = await attestRegisteredFile(request, expected);
|
||||
const headers = ragInternalHeaders(registryAuthHeaders(request));
|
||||
const form = new FormData();
|
||||
form.set("file_sn", registered.fileSn);
|
||||
form.set("project_id", registered.projectId);
|
||||
form.set("clsf_systm_sn", registered.clsfSystmSn);
|
||||
form.set("registry_context", JSON.stringify(registryForwardContext(registered, headers)));
|
||||
if (body?.previewMode === true || body?.previewMode === "true") form.set("preview_mode", "true");
|
||||
if (previewRevisionId) form.set("preview_revision_id", previewRevisionId);
|
||||
if (previewPage !== undefined) form.set("preview_page", String(previewPage));
|
||||
if (typeof previewKeyword === "string") form.set("preview_keyword", previewKeyword);
|
||||
const response = await fetch(dcRagUrl("/embed-documents/current-source"), {
|
||||
method: "POST", headers, body: form, cache: "no-store", signal: request.signal,
|
||||
});
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
headers: { "Content-Type": response.headers.get("content-type") || "application/json", "Cache-Control": "no-store" },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) {
|
||||
return NextResponse.json({ detail: error.code }, { status: error.status, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
return NextResponse.json({ detail: "CURRENT_SOURCE_UNAVAILABLE" }, { status: 502, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest): Promise<Response> {
|
||||
try {
|
||||
return await forwardCurrentSource(request, await request.json());
|
||||
} catch {
|
||||
return NextResponse.json({ detail: "CURRENT_SOURCE_REQUEST_INVALID" }, { status: 400, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest): Promise<Response> {
|
||||
const body = Object.fromEntries(request.nextUrl.searchParams);
|
||||
if (!body.previewRevisionId || !body.previewPage) {
|
||||
return NextResponse.json({ detail: "CURRENT_PREVIEW_REQUEST_INVALID" }, { status: 400, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
return forwardCurrentSource(request, body);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { CLAIM_NAME, AUTH_USER_ID } from "@/shared/config";
|
||||
import { getFlaskBaseUrl } from "@/shared/api/flask-upstream-url";
|
||||
import {
|
||||
encodeFormData,
|
||||
isHeadersTimeout,
|
||||
readAllText,
|
||||
requestFlask,
|
||||
} from "@/shared/api/flask-node-request";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 1800;
|
||||
|
||||
const RESPONSE_TIMEOUT_MS = 18000000;
|
||||
|
||||
// 문서 생성 1단계(prepare). 신청서 적재 + 후보 산출은 시간이 걸릴 수 있어
|
||||
// Edge 미들웨어 프록시의 짧은 타임아웃을 피하고자 Node.js API Route를 경유한다.
|
||||
// 스트리밍이 아닌 일반 JSON 응답이라 응답 헤더까지 대기 시간이 그대로 길어지는데,
|
||||
// fetch(undici)는 5분에서 끊기므로 node:http 기반 요청을 사용한다.
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const flaskApiUrl = getFlaskBaseUrl();
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get(CLAIM_NAME)?.value;
|
||||
const userId = cookieStore.get(AUTH_USER_ID)?.value;
|
||||
|
||||
// multipart/form-data 그대로 재구성해 Flask로 전달
|
||||
const { contentType, body } = await encodeFormData(
|
||||
await request.formData(),
|
||||
);
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": contentType,
|
||||
};
|
||||
if (token) headers[CLAIM_NAME] = token;
|
||||
if (userId) headers[AUTH_USER_ID] = userId;
|
||||
|
||||
try {
|
||||
const upstream = await requestFlask(
|
||||
`${flaskApiUrl}/flask-service/doc/generate/prepare`,
|
||||
{
|
||||
method: "POST",
|
||||
headers,
|
||||
body,
|
||||
signal: request.signal,
|
||||
headersTimeoutMs: RESPONSE_TIMEOUT_MS,
|
||||
},
|
||||
);
|
||||
|
||||
// 성공/실패 모두 Flask 응답 바디를 그대로 전달한다
|
||||
// (실패 시 {detail:{code,message}} 형식을 클라이언트가 파싱할 수 있도록)
|
||||
const text = await readAllText(upstream.stream);
|
||||
return new NextResponse(text, {
|
||||
status: upstream.status,
|
||||
headers: {
|
||||
"Content-Type": upstream.contentType || "application/json",
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (isHeadersTimeout(error)) {
|
||||
return NextResponse.json(
|
||||
{ error: "요청이 타임아웃되었습니다. (300분 초과)" },
|
||||
{ status: 504 },
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("flask-service/doc/generate/prepare API Route 오류:", error);
|
||||
const message = error instanceof Error ? error.message : "알 수 없는 오류";
|
||||
return NextResponse.json(
|
||||
{ error: "서버 오류가 발생했습니다.", details: message },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { CLAIM_NAME, AUTH_USER_ID } from "@/shared/config";
|
||||
import { getFlaskBaseUrl } from "@/shared/api/flask-upstream-url";
|
||||
import {
|
||||
encodeFormData,
|
||||
isHeadersTimeout,
|
||||
readAllText,
|
||||
requestFlask,
|
||||
toWebStream,
|
||||
} from "@/shared/api/flask-node-request";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 3600;
|
||||
|
||||
// 첫 응답 헤더까지만 기다리는 제한. 스트림이 시작된 뒤에는 적용되지 않는다.
|
||||
const HEADERS_TIMEOUT_MS = 600000;
|
||||
|
||||
// 문서 생성 2단계(SSE 스트리밍).
|
||||
// Edge 미들웨어 프록시에서 SSE가 버퍼링/중단되는 것을 막기 위해
|
||||
// ask-question과 동일하게 Node.js API Route를 경유해 Flask로 전달한다.
|
||||
// 섹션 하나에 5분 이상 걸려 이벤트 간격이 길어질 수 있어, fetch(undici)의
|
||||
// 고정 bodyTimeout을 피하려고 node:http 기반 요청을 사용한다.
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const flaskApiUrl = getFlaskBaseUrl();
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get(CLAIM_NAME)?.value;
|
||||
const userId = cookieStore.get(AUTH_USER_ID)?.value;
|
||||
|
||||
// multipart/form-data 그대로 재구성해 Flask로 전달
|
||||
const { contentType, body } = await encodeFormData(
|
||||
await request.formData(),
|
||||
);
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "text/event-stream",
|
||||
"Content-Type": contentType,
|
||||
};
|
||||
if (token) headers[CLAIM_NAME] = token;
|
||||
if (userId) headers[AUTH_USER_ID] = userId;
|
||||
|
||||
let upstream;
|
||||
try {
|
||||
upstream = await requestFlask(
|
||||
`${flaskApiUrl}/flask-service/doc/generate`,
|
||||
{
|
||||
method: "POST",
|
||||
headers,
|
||||
body,
|
||||
signal: request.signal,
|
||||
headersTimeoutMs: HEADERS_TIMEOUT_MS,
|
||||
},
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
if (isHeadersTimeout(error)) {
|
||||
return NextResponse.json(
|
||||
{ error: "요청이 타임아웃되었습니다. (10분 내 응답 없음)" },
|
||||
{ status: 504 },
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (upstream.status >= 400) {
|
||||
const errorText = await readAllText(upstream.stream);
|
||||
return new NextResponse(errorText, {
|
||||
status: upstream.status,
|
||||
headers: {
|
||||
"Content-Type": upstream.contentType || "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 스트림을 버퍼링 없이 그대로 클라이언트로 흘려보낸다
|
||||
return new Response(toWebStream(upstream.stream), {
|
||||
status: upstream.status,
|
||||
headers: {
|
||||
"Content-Type": upstream.contentType || "text/event-stream",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
Connection: "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error("flask-service/doc/generate API Route 오류:", error);
|
||||
const message = error instanceof Error ? error.message : "알 수 없는 오류";
|
||||
return NextResponse.json(
|
||||
{ error: "서버 오류가 발생했습니다.", details: message },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({ requestFlask: vi.fn() }));
|
||||
vi.mock("next/headers", () => ({
|
||||
cookies: async () => ({ get: (name: string) =>
|
||||
name === "Authorization" ? { value: "existing-session" } : undefined }),
|
||||
}));
|
||||
vi.mock("@/shared/config", () => ({ CLAIM_NAME: "Authorization", AUTH_USER_ID: "token-id" }));
|
||||
vi.mock("@/shared/api/flask-node-request", () => ({
|
||||
encodeFormData: vi.fn(async () => ({ contentType: "multipart/form-data; boundary=test", body: Buffer.from("fixture") })),
|
||||
isHeadersTimeout: vi.fn(() => false),
|
||||
readAllText: vi.fn(async () => '{"detail":"fixture"}'),
|
||||
requestFlask: state.requestFlask,
|
||||
toWebStream: vi.fn(),
|
||||
}));
|
||||
import { POST as generate } from "./route";
|
||||
import { POST as prepare } from "./prepare/route";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://private-rag:8000/");
|
||||
vi.stubEnv("NEXT_PUBLIC_FLASK_API_URL", "https://previous-public.invalid");
|
||||
state.requestFlask.mockReset().mockResolvedValue({ status: 422, contentType: "application/json", stream: {} });
|
||||
});
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
describe("document Node routes use private runtime Flask target", () => {
|
||||
it.each([
|
||||
["generate", generate, "/flask-service/doc/generate"],
|
||||
["prepare", prepare, "/flask-service/doc/generate/prepare"],
|
||||
] as const)("preserves auth and response while routing %s to the private target", async (_label, handler, suffix) => {
|
||||
const form = new FormData();
|
||||
form.set("fixture", "test");
|
||||
const response = await handler(new NextRequest("https://frontend.invalid/document", { method: "POST", body: form }));
|
||||
expect(state.requestFlask).toHaveBeenCalledOnce();
|
||||
expect(state.requestFlask).toHaveBeenCalledWith(`http://private-rag:8000${suffix}`, expect.objectContaining({
|
||||
method: "POST", headers: expect.objectContaining({ Authorization: "existing-session" }),
|
||||
}));
|
||||
expect(response.status).toBe(422);
|
||||
expect(await response.json()).toEqual({ detail: "fixture" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { POST } from "./route";
|
||||
import { attestReuploadOwner } from "@/server/file-registry-attestation";
|
||||
|
||||
vi.mock("@/server/file-registry-attestation", async importOriginal => {
|
||||
const original = await importOriginal<typeof import("@/server/file-registry-attestation")>();
|
||||
return {
|
||||
...original,
|
||||
attestRegisteredFile: vi.fn(async () => ({
|
||||
fileSn: "file-1", projectId: "test-project", clsfSystmSn: "test-leaf",
|
||||
classificationPath: ["test-project", "test-leaf"], useYn: "Y",
|
||||
})),
|
||||
attestReuploadOwner: vi.fn(async () => undefined),
|
||||
registryAuthHeaders: vi.fn(() => new Headers({
|
||||
Authorization: `Bearer x.${Buffer.from(JSON.stringify({ sub: "test-user" })).toString("base64url")}.y`,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
const requestWithParser = (parserEngine?: string) => {
|
||||
const form = new FormData();
|
||||
form.set("pdf_path", "./output_pdf/file-1.pdf");
|
||||
form.set("original_filename", "source.pdf");
|
||||
form.set("file_sn", "file-1");
|
||||
form.set("project_id", "test-project");
|
||||
form.set("clsf_systm_sn", "test-leaf");
|
||||
if (parserEngine) form.set("parser_engine", parserEngine);
|
||||
return new NextRequest("http://localhost/api/flask-service/embed-documents/jobs", {
|
||||
method: "POST", body: form,
|
||||
});
|
||||
};
|
||||
|
||||
describe("explicit parser selection", () => {
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it("rejects parser selection before registry access when the canary is disabled", async () => {
|
||||
vi.stubEnv("KORDOC_CANARY_ENABLED", "0");
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(requestWithParser("source-kordoc-candidate"));
|
||||
expect(response.status).toBe(403);
|
||||
expect(await response.json()).toMatchObject({ detail: {
|
||||
code: "KORDOC_CANARY_SCOPE_FORBIDDEN", dispatchState: "NOT_SENT",
|
||||
} });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unknown parser value before any registry or RAG dispatch", async () => {
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(requestWithParser("unverified-engine"));
|
||||
expect(response.status).toBe(400);
|
||||
expect(await response.json()).toMatchObject({ detail: {
|
||||
code: "PARSER_ENGINE_INVALID", dispatchState: "NOT_SENT",
|
||||
} });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["0", "1"])("forwards explicit Docling when KorDoc selection is %s", async enabled => {
|
||||
vi.stubEnv("KORDOC_CANARY_ENABLED", enabled);
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json({
|
||||
job_id: "11111111-1111-4111-8111-111111111111", completion_attestation: "a".repeat(32),
|
||||
}));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(requestWithParser("source-docling"));
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect((fetchMock.mock.calls[0]![1].body as FormData).get("parser_engine")).toBe("source-docling");
|
||||
});
|
||||
|
||||
it("preserves omitted-parser API compatibility for the server default", async () => {
|
||||
vi.stubEnv("KORDOC_CANARY_ENABLED", "1");
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json({
|
||||
job_id: "11111111-1111-4111-8111-111111111111", completion_attestation: "a".repeat(32),
|
||||
}));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(requestWithParser());
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect((fetchMock.mock.calls[0]![1].body as FormData).has("parser_engine")).toBe(false);
|
||||
});
|
||||
|
||||
it("forwards the selected parser for a registered file through the configured RAG service", async () => {
|
||||
vi.stubEnv("KORDOC_CANARY_ENABLED", "1");
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
const fetchMock = vi.fn().mockImplementation(async (_url: URL, init: RequestInit) => {
|
||||
const body = init.body as FormData;
|
||||
expect(body.get("parser_engine")).toBe("source-kordoc-candidate");
|
||||
expect(body.get("file_sn")).toBe("file-1");
|
||||
expect(JSON.parse(String(body.get("registry_context")))).toMatchObject({
|
||||
projectId: "test-project", fileSn: "file-1",
|
||||
});
|
||||
return Response.json({
|
||||
job_id: "11111111-1111-4111-8111-111111111111",
|
||||
completion_attestation: "a".repeat(32),
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(requestWithParser("source-kordoc-candidate"));
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
|
||||
"http://127.0.0.1:18081/flask-service/embed-documents/jobs",
|
||||
);
|
||||
});
|
||||
|
||||
it("forwards reupload staging and expected Current only with the server key", async () => {
|
||||
const staging = "00000000-0000-4000-8000-000000000002";
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
const form = new FormData();
|
||||
form.set("pdf_path", `./output_pdf/${staging}.pdf`);
|
||||
form.set("original_filename", "same.pdf");
|
||||
form.set("file_sn", "file-1");
|
||||
form.set("project_id", "test-project");
|
||||
form.set("clsf_systm_sn", "test-leaf");
|
||||
form.set("reupload_staging_file_sn", staging);
|
||||
form.set("reupload_expected_current_ingestion_id", "old-ingestion");
|
||||
const upstream = vi.fn(async (_url: URL, init: RequestInit) => {
|
||||
const sent = init.body as FormData;
|
||||
expect(sent.get("reupload_staging_file_sn")).toBe(staging);
|
||||
expect(sent.get("reupload_expected_current_ingestion_id")).toBe("old-ingestion");
|
||||
expect(new Headers(init.headers).get("X-Rag-V2-Internal-Key")).toBe("test-only-internal-key");
|
||||
return Response.json({
|
||||
job_id: "11111111-1111-4111-8111-111111111111", completion_attestation: "a".repeat(32),
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
const response = await POST(new NextRequest("http://localhost/api/flask-service/embed-documents/jobs", {
|
||||
method: "POST", body: form,
|
||||
}));
|
||||
expect(response.status).toBe(200);
|
||||
expect(attestReuploadOwner).toHaveBeenCalledOnce();
|
||||
expect(upstream).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("initial embedding precondition forwarding", () => {
|
||||
it.each(["true", "false", "1"])("accepts only the explicit initial boolean true (%s)", async flag => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json({ job_id: "11111111-1111-4111-8111-111111111111", completion_attestation: "a".repeat(32) })); vi.stubGlobal("fetch", fetchMock);
|
||||
const request = requestWithParser(); const form = await request.formData(); form.set("initial_embedding_only", flag); vi.spyOn(request, "formData").mockResolvedValue(form);
|
||||
const response = await POST(request);
|
||||
expect(response.status).toBe(flag === "true" ? 200 : 400);
|
||||
if (flag === "true") expect((fetchMock.mock.calls[0]![1].body as FormData).get("initial_embedding_only")).toBe("true");
|
||||
else expect(fetchMock).not.toHaveBeenCalled();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { registryForwardContext } from "@/server/rag-forward-context";
|
||||
import { operationDiagnostics } from "@/server/operation-diagnostics";
|
||||
import {
|
||||
attestReuploadOwner,
|
||||
attestRegisteredFile,
|
||||
dcRagUrl,
|
||||
FileRegistryError,
|
||||
ragInternalHeaders,
|
||||
registryAuthHeaders,
|
||||
type RegistryDiagnostic,
|
||||
} from "@/server/file-registry-attestation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 60;
|
||||
|
||||
function failureResponse(
|
||||
status: number, code: string, message: string,
|
||||
dispatchState: "NOT_SENT" | "UNKNOWN" = "NOT_SENT",
|
||||
diagnostic?: RegistryDiagnostic,
|
||||
): NextResponse {
|
||||
return NextResponse.json({ detail: { code, message, dispatchState, ...(diagnostic ? { diagnostic } : {}) } }, {
|
||||
status,
|
||||
headers: { "Cache-Control": "no-store", "X-Rag-Dispatch-State": dispatchState },
|
||||
});
|
||||
}
|
||||
|
||||
function formString(form: FormData, name: string): string {
|
||||
const value = form.get(name);
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest): Promise<Response> {
|
||||
const diagnostic = operationDiagnostics("embed-start");
|
||||
let diagnosticFileSn: string | undefined;
|
||||
const failure: typeof failureResponse = (...args) => diagnostic.finish(failureResponse(...args), {
|
||||
code: args[1], fileSn: diagnosticFileSn,
|
||||
});
|
||||
// Once the POST starts, a lost receipt cannot prove that RAG did not accept it.
|
||||
let ragRequestStarted = false;
|
||||
try {
|
||||
const length = Number(request.headers.get("content-length") ?? 0);
|
||||
if (length > 16_384) {
|
||||
return failure(413, "EMBED_REQUEST_TOO_LARGE", "임베딩 요청이 너무 큽니다.");
|
||||
}
|
||||
let form: FormData;
|
||||
try {
|
||||
form = await request.formData();
|
||||
} catch {
|
||||
return failure(400, "EMBED_REQUEST_INVALID", "임베딩 요청이 올바르지 않습니다.");
|
||||
}
|
||||
const pdfPath = formString(form, "pdf_path");
|
||||
const originalFilename = formString(form, "original_filename");
|
||||
const fileSn = formString(form, "file_sn");
|
||||
diagnosticFileSn = /^[A-Za-z0-9_-]{1,128}$/.test(fileSn) ? fileSn : undefined;
|
||||
const reuploadStagingFileSn = formString(form, "reupload_staging_file_sn");
|
||||
const reuploadExpectedCurrentIngestionId = formString(form, "reupload_expected_current_ingestion_id");
|
||||
const projectId = formString(form, "project_id");
|
||||
const clsfSystmSn = formString(form, "clsf_systm_sn");
|
||||
const parserEngine = formString(form, "parser_engine");
|
||||
const initialEmbeddingOnly = formString(form, "initial_embedding_only");
|
||||
if (initialEmbeddingOnly && initialEmbeddingOnly !== "true") {
|
||||
return failure(400, "EMBED_REQUEST_INVALID", "최초 임베딩 요청이 올바르지 않습니다.");
|
||||
}
|
||||
if (initialEmbeddingOnly && reuploadStagingFileSn) {
|
||||
return failure(400, "EMBED_REQUEST_INVALID", "최초 임베딩과 재임베딩을 함께 요청할 수 없습니다.");
|
||||
}
|
||||
if (!pdfPath || !originalFilename || !fileSn || !projectId || !clsfSystmSn) {
|
||||
return failure(400, "EMBED_REQUEST_INVALID", "파일 및 분류 정보가 필요합니다.");
|
||||
}
|
||||
// For reupload, the physical upload ID is distinct from the registered
|
||||
// logical file ID. Only that upload's converted PDF may be dispatched.
|
||||
const physicalFileSn = reuploadStagingFileSn || fileSn;
|
||||
const staged = !reuploadStagingFileSn ||
|
||||
(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(reuploadStagingFileSn) &&
|
||||
reuploadStagingFileSn !== fileSn);
|
||||
if (!/^[A-Za-z0-9_-]{1,128}$/.test(fileSn) || !staged ||
|
||||
pdfPath !== `./output_pdf/${physicalFileSn}.pdf`) {
|
||||
return failure(400, "EMBED_PDF_PATH_MISMATCH", "등록된 파일의 PDF 경로가 아닙니다.");
|
||||
}
|
||||
if ((reuploadStagingFileSn && !/^[A-Za-z0-9_-]{1,256}$/.test(reuploadExpectedCurrentIngestionId)) ||
|
||||
(!reuploadStagingFileSn && reuploadExpectedCurrentIngestionId)) {
|
||||
return failure(400, "REUPLOAD_CURRENT_REQUIRED", "기존 Current 식별자가 필요합니다.");
|
||||
}
|
||||
if (parserEngine && parserEngine !== "source-docling" && parserEngine !== "source-kordoc-candidate") {
|
||||
return failure(400, "PARSER_ENGINE_INVALID", "PDF 파서 선택값이 올바르지 않습니다.");
|
||||
}
|
||||
if (parserEngine === "source-kordoc-candidate" && process.env.KORDOC_CANARY_ENABLED !== "1") {
|
||||
return failure(403, "KORDOC_CANARY_SCOPE_FORBIDDEN", "PDF 파서 선택이 현재 비활성화되어 있습니다.");
|
||||
}
|
||||
|
||||
const registered = await attestRegisteredFile(request, { fileSn, projectId, clsfSystmSn });
|
||||
if (reuploadStagingFileSn) await attestReuploadOwner(request, registered);
|
||||
const target = dcRagUrl("/embed-documents/jobs");
|
||||
const upstreamForm = new FormData();
|
||||
upstreamForm.set("pdf_path", pdfPath);
|
||||
upstreamForm.set("original_filename", originalFilename);
|
||||
upstreamForm.set("file_sn", registered.fileSn);
|
||||
if (initialEmbeddingOnly) upstreamForm.set("initial_embedding_only", "true");
|
||||
if (reuploadStagingFileSn) upstreamForm.set("reupload_staging_file_sn", reuploadStagingFileSn);
|
||||
if (reuploadStagingFileSn) upstreamForm.set("reupload_expected_current_ingestion_id", reuploadExpectedCurrentIngestionId);
|
||||
upstreamForm.set("project_id", registered.projectId);
|
||||
upstreamForm.set("clsf_systm_sn", registered.clsfSystmSn);
|
||||
if (parserEngine) upstreamForm.set("parser_engine", parserEngine);
|
||||
const headers = registryAuthHeaders(request);
|
||||
headers.set("x-request-id", diagnostic.requestId);
|
||||
if (reuploadStagingFileSn) ragInternalHeaders(headers);
|
||||
upstreamForm.set("registry_context", JSON.stringify(registryForwardContext(registered, headers)));
|
||||
ragRequestStarted = true;
|
||||
const upstream = await fetch(target, {
|
||||
method: "POST", headers, body: upstreamForm, cache: "no-store", signal: request.signal,
|
||||
});
|
||||
const responseHeaders = new Headers({ "Cache-Control": "no-store" });
|
||||
const contentType = upstream.headers.get("content-type");
|
||||
if (contentType) responseHeaders.set("Content-Type", contentType);
|
||||
const responseText = await upstream.text();
|
||||
if (!upstream.ok) {
|
||||
// Never accept an upstream body's NOT_SENT assertion as frontend proof.
|
||||
responseHeaders.set("X-Rag-Dispatch-State", "UNKNOWN");
|
||||
return diagnostic.finish(new Response(responseText, { status: upstream.status, headers: responseHeaders }), {
|
||||
upstreamRequestId: upstream.headers.get("x-request-id"), fileSn: diagnosticFileSn,
|
||||
});
|
||||
}
|
||||
let job: Record<string, unknown>;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(responseText);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("invalid job");
|
||||
job = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
return failure(502, "EMBED_JOB_START_INVALID", "임베딩 작업 접수 결과가 올바르지 않습니다.", "UNKNOWN");
|
||||
}
|
||||
const jobId = job.job_id;
|
||||
if (typeof jobId !== "string" || !/^[a-f0-9-]{36}$/i.test(jobId)) {
|
||||
return failure(502, "EMBED_JOB_START_INVALID", "임베딩 작업 식별자가 올바르지 않습니다.", "UNKNOWN");
|
||||
}
|
||||
if (typeof job.completion_attestation !== "string" ||
|
||||
!/^[A-Za-z0-9_-]{32,256}$/.test(job.completion_attestation)) {
|
||||
return failure(502, "EMBED_COMPLETION_AUTHORITY_INVALID", "임베딩 완료 권한을 확인하지 못했습니다.", "UNKNOWN");
|
||||
}
|
||||
responseHeaders.set("Content-Type", "application/json");
|
||||
return diagnostic.finish(new Response(JSON.stringify(job), {
|
||||
status: upstream.status, headers: responseHeaders,
|
||||
}), { upstreamRequestId: upstream.headers.get("x-request-id"), fileSn: diagnosticFileSn, jobId, accepted: true });
|
||||
} catch (error) {
|
||||
const dispatchState = ragRequestStarted ? "UNKNOWN" : "NOT_SENT";
|
||||
if (error instanceof FileRegistryError) {
|
||||
return failure(error.status, error.code, error.message, dispatchState, error.diagnostic);
|
||||
}
|
||||
if (request.signal.aborted) {
|
||||
return failure(499, "EMBED_CANCELLED", "임베딩 요청이 취소되었습니다.", dispatchState);
|
||||
}
|
||||
return failure(502, "EMBED_UPSTREAM_UNAVAILABLE", "임베딩 서버에 연결할 수 없습니다.", dispatchState);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { middleware } from "../../../../../middleware";
|
||||
import { GET } from "./route";
|
||||
|
||||
const jobId = "job-123";
|
||||
const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEifQ.signature";
|
||||
const params = Promise.resolve({ jobId });
|
||||
const request = () => new NextRequest(`https://dc.invalid/server/flask-service/jobs/${jobId}`, {
|
||||
headers: { Cookie: `Authorization=${jwt}; token-id=user-1` },
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("FLASK_API_URL", "https://dc-rag.invalid");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("job status privacy proxy", () => {
|
||||
it("routes exact GET status requests through the local handler", () => {
|
||||
const rewritten = middleware(request());
|
||||
expect(new URL(rewritten.headers.get("x-middleware-rewrite")!).pathname)
|
||||
.toBe(`/api/flask-service/jobs/${jobId}`);
|
||||
const cancel = middleware(new NextRequest(`https://dc.invalid/server/flask-service/jobs/${jobId}/cancel`, {
|
||||
method: "POST",
|
||||
}));
|
||||
expect(new URL(cancel.headers.get("x-middleware-rewrite")!).pathname)
|
||||
.toBe(`/flask-service/jobs/${jobId}/cancel`);
|
||||
const malformed = middleware(new NextRequest(`https://dc.invalid/server/flask-service/jobs/${jobId}/`));
|
||||
expect(malformed.status).toBe(404);
|
||||
expect(malformed.headers.get("x-middleware-rewrite")).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
"/flask-service/jobs/job-123",
|
||||
"/server/flask-service/jobs/job-123",
|
||||
"/server/flask-root/flask-service/jobs/job-123",
|
||||
"/flask-service/%6aobs/job-123",
|
||||
"/flask-service/jobs/%6aob-123",
|
||||
])("filters status for every alias and preserves its query: %s", path => {
|
||||
const response = middleware(new NextRequest(`https://legacy-rag.invalid${path}?case=1`));
|
||||
const rewritten = new URL(response.headers.get("x-middleware-rewrite")!);
|
||||
expect(rewritten.origin).toBe("https://legacy-rag.invalid");
|
||||
expect(rewritten.pathname).toBe("/api/flask-service/jobs/job-123");
|
||||
expect(rewritten.search).toBe("?case=1");
|
||||
});
|
||||
|
||||
it("also filters HEAD status rather than forwarding raw job headers", () => {
|
||||
const response = middleware(new NextRequest("https://legacy-rag.invalid/flask-service/jobs/job-123", { method: "HEAD" }));
|
||||
expect(new URL(response.headers.get("x-middleware-rewrite")!).pathname).toBe("/api/flask-service/jobs/job-123");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"/flask-service/jobs/job-123/",
|
||||
"/flask-service/jobs/job-123/nested",
|
||||
"/server/flask-root/flask-service/jobs/job-123/nested",
|
||||
])("does not send malformed status paths to raw RAG: %s", path => {
|
||||
const response = middleware(new NextRequest(`https://legacy-rag.invalid${path}`));
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.headers.get("x-middleware-rewrite")).toBeNull();
|
||||
});
|
||||
|
||||
it("removes the survey artifact while retaining ordinary job status and result fields", async () => {
|
||||
const fetchMock = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
|
||||
expect(String(_url)).toBe(`https://dc-rag.invalid/flask-service/jobs/${jobId}`);
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe(jwt);
|
||||
return Response.json({
|
||||
job_id: jobId,
|
||||
type: "EMBED_DOCUMENTS",
|
||||
status: "DONE",
|
||||
progress: 100,
|
||||
completion_attestation: "server-only-start-capability",
|
||||
general_survey_import: { secret: "top-level" },
|
||||
result: {
|
||||
embedded_files: [{ file_sn: "file-1", chunks_count: 2 }],
|
||||
completion_attestation: "server-only-result-capability",
|
||||
general_survey_import: { status: "parsed", private_detail: "server-only" },
|
||||
},
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const response = await GET(request(), { params });
|
||||
expect(response.status).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body).toMatchObject({
|
||||
job_id: jobId, type: "EMBED_DOCUMENTS", status: "DONE", progress: 100,
|
||||
result: { embedded_files: [{ file_sn: "file-1", chunks_count: 2 }], general_survey_import_ready: true },
|
||||
});
|
||||
expect(body.general_survey_import).toBeUndefined();
|
||||
expect(body.completion_attestation).toBeUndefined();
|
||||
expect(body.result.general_survey_import).toBeUndefined();
|
||||
expect(body.result.completion_attestation).toBeUndefined();
|
||||
expect(JSON.stringify(body)).not.toContain("server-only");
|
||||
});
|
||||
|
||||
it("does not mark a job without a survey artifact for completion", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => Response.json({
|
||||
job_id: jobId, type: "EMBED_DOCUMENTS", status: "DONE",
|
||||
result: { embedded_files: [{ file_sn: "file-1" }], general_survey_import: null, general_survey_import_ready: true },
|
||||
})));
|
||||
const response = await GET(request(), { params });
|
||||
const body = await response.json();
|
||||
expect(body.result.general_survey_import_ready).toBeUndefined();
|
||||
expect(body.result.general_survey_import).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects an invalid or mismatched job identity", async () => {
|
||||
const fetchMock = vi.fn(async () => Response.json({ job_id: "another-job", status: "DONE" }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
expect((await GET(request(), { params })).status).toBe(502);
|
||||
const invalid = await GET(request(), { params: Promise.resolve({ jobId: "../other" }) });
|
||||
expect(invalid.status).toBe(400);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { dcRagUrl, FileRegistryError, registryAuthHeaders } from "@/server/file-registry-attestation";
|
||||
import { operationDiagnostics } from "@/server/operation-diagnostics";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function failureResponse(status: number, code: string, message: string): NextResponse {
|
||||
return NextResponse.json({ detail: { code, message } }, {
|
||||
status, headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | null {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: null;
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ jobId: string }> },
|
||||
): Promise<NextResponse> {
|
||||
const diagnostic = operationDiagnostics("job-status");
|
||||
let diagnosticJobId: string | undefined;
|
||||
let upstreamRequestId: string | null = null;
|
||||
const failure: typeof failureResponse = (...args) => diagnostic.finish(failureResponse(...args), {
|
||||
code: args[1], jobId: diagnosticJobId, upstreamRequestId,
|
||||
});
|
||||
try {
|
||||
const { jobId } = await params;
|
||||
if (!/^[A-Za-z0-9_-]{1,128}$/.test(jobId)) {
|
||||
return failure(400, "JOB_ID_INVALID", "작업 식별자가 올바르지 않습니다.");
|
||||
}
|
||||
diagnosticJobId = jobId;
|
||||
const headers = registryAuthHeaders(request);
|
||||
headers.set("x-request-id", diagnostic.requestId);
|
||||
const response = await fetch(dcRagUrl(`/jobs/${encodeURIComponent(jobId)}`), {
|
||||
method: "GET", headers, cache: "no-store", signal: request.signal,
|
||||
});
|
||||
upstreamRequestId = response.headers.get("x-request-id");
|
||||
if (!response.ok) {
|
||||
return failure(response.status, "JOB_LOOKUP_FAILED", "작업 결과를 조회할 수 없습니다.");
|
||||
}
|
||||
const job = record(await response.json().catch(() => null));
|
||||
if (!job || job.job_id !== jobId) {
|
||||
return failure(502, "JOB_RESULT_INVALID", "작업 결과가 올바르지 않습니다.");
|
||||
}
|
||||
const result = record(job.result);
|
||||
if (result) {
|
||||
const publicResult = { ...result };
|
||||
delete publicResult.general_survey_import_ready;
|
||||
delete publicResult.completion_attestation;
|
||||
if (result.general_survey_import != null) {
|
||||
publicResult.general_survey_import_ready = true;
|
||||
}
|
||||
delete publicResult.general_survey_import;
|
||||
job.result = publicResult;
|
||||
}
|
||||
const publicJob = { ...job };
|
||||
delete publicJob.general_survey_import;
|
||||
delete publicJob.completion_attestation;
|
||||
return diagnostic.finish(NextResponse.json(publicJob, { headers: { "Cache-Control": "no-store" } }), {
|
||||
upstreamRequestId, jobId,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) {
|
||||
return failure(error.status, error.code, error.message);
|
||||
}
|
||||
if (request.signal.aborted) {
|
||||
return failure(499, "JOB_LOOKUP_CANCELLED", "작업 조회가 취소되었습니다.");
|
||||
}
|
||||
return failure(502, "JOB_LOOKUP_UNAVAILABLE", "작업 결과를 조회할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { registryForwardContext } from "@/server/rag-forward-context";
|
||||
import {
|
||||
attestRegisteredFile,
|
||||
dcRagUrl,
|
||||
FileRegistryError,
|
||||
registryAuthHeaders,
|
||||
} from "@/server/file-registry-attestation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 300;
|
||||
|
||||
function failure(status: number, code: string, message: string): NextResponse {
|
||||
return NextResponse.json({ detail: { code, message } }, {
|
||||
status,
|
||||
headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
function stringValue(value: unknown): string {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest): Promise<Response> {
|
||||
try {
|
||||
const length = Number(request.headers.get("content-length") ?? 0);
|
||||
if (length > 8_192) {
|
||||
return failure(413, "REINDEX_REQUEST_TOO_LARGE", "재색인 요청이 너무 큽니다.");
|
||||
}
|
||||
let input: unknown;
|
||||
try {
|
||||
input = await request.json();
|
||||
} catch {
|
||||
return failure(400, "REINDEX_REQUEST_INVALID", "재색인 요청이 올바르지 않습니다.");
|
||||
}
|
||||
if (!input || typeof input !== "object" || Array.isArray(input)) {
|
||||
return failure(400, "REINDEX_REQUEST_INVALID", "재색인 요청이 올바르지 않습니다.");
|
||||
}
|
||||
const body = input as Record<string, unknown>;
|
||||
const fileSn = stringValue(body.file_sn);
|
||||
const projectId = stringValue(body.project_id);
|
||||
const clsfSystmSn = stringValue(body.clsf_systm_sn);
|
||||
const originalName = stringValue(body.original_name);
|
||||
if (!fileSn || !projectId) {
|
||||
return failure(400, "REINDEX_REQUEST_INVALID", "파일 및 자료관 정보가 필요합니다.");
|
||||
}
|
||||
|
||||
const registered = await attestRegisteredFile(request, { fileSn, projectId, clsfSystmSn });
|
||||
const headers = registryAuthHeaders(request);
|
||||
headers.set("Content-Type", "application/json");
|
||||
const upstream = await fetch(dcRagUrl("/keyword-reindex-from-qdrant"), {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
file_sn: registered.fileSn,
|
||||
project_id: registered.projectId,
|
||||
registry_context: registryForwardContext(registered, headers),
|
||||
original_name: originalName,
|
||||
}),
|
||||
cache: "no-store",
|
||||
signal: request.signal,
|
||||
});
|
||||
const responseHeaders = new Headers({ "Cache-Control": "no-store" });
|
||||
const contentType = upstream.headers.get("content-type");
|
||||
if (contentType) responseHeaders.set("Content-Type", contentType);
|
||||
const responseText = await upstream.text();
|
||||
return new Response([204, 205, 304].includes(upstream.status) ? null : responseText, {
|
||||
status: upstream.status, headers: responseHeaders,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) {
|
||||
return failure(error.status, error.code, error.message);
|
||||
}
|
||||
if (request.signal.aborted) {
|
||||
return failure(499, "REINDEX_CANCELLED", "재색인 요청이 취소되었습니다.");
|
||||
}
|
||||
return failure(502, "REINDEX_UPSTREAM_UNAVAILABLE", "재색인 서버에 연결할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import http from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
const auth = vi.hoisted(() => ({ token: "", userId: "" }));
|
||||
vi.mock("next/headers", () => ({
|
||||
cookies: async () => ({ get: (name: string) => {
|
||||
const value = name === "Authorization" ? auth.token : name === "token-id" ? auth.userId : "";
|
||||
return value ? { value } : undefined;
|
||||
} }),
|
||||
}));
|
||||
vi.mock("@/shared/config", async (importOriginal) => ({
|
||||
...await importOriginal<typeof import("@/shared/config")>(),
|
||||
CLAIM_NAME: "Authorization",
|
||||
AUTH_USER_ID: "token-id",
|
||||
}));
|
||||
import { POST } from "./route";
|
||||
import { POST as publicPOST } from "../../../server/flask-service/keyword-search/route";
|
||||
import { POST as dcSearchPOST } from "../../../dc-service/api/v1/rag-search/keyword-search/route";
|
||||
import { middleware } from "../../../../middleware";
|
||||
|
||||
let server: http.Server;
|
||||
let handle: (request: http.IncomingMessage, response: http.ServerResponse) => void;
|
||||
let hits: number;
|
||||
const body = '{ "keyword": "처리시설", "page": 1, "page_size": 10 }';
|
||||
function request(signal?: AbortSignal) {
|
||||
return new NextRequest("https://dc.invalid/server/flask-service/keyword-search?upstream=http://untrusted.invalid", {
|
||||
method: "POST", body, signal,
|
||||
headers: { "Content-Type": "application/json", "X-Site-Id": "DC", Authorization: "header-token" },
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
auth.token = "";
|
||||
auth.userId = "";
|
||||
hits = 0;
|
||||
handle = (_, response) => response.end('{"results":[]}');
|
||||
server = http.createServer((req, res) => { hits++; handle(req, res); });
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
vi.stubEnv("NEXT_PUBLIC_DC_SERVICE_API_URL", `http://127.0.0.1:${(server.address() as AddressInfo).port}`);
|
||||
vi.stubEnv("KEYWORD_SEARCH_PROXY_TIMEOUT_MS", "2000");
|
||||
vi.stubEnv("KEYWORD_SEARCH_PROXY_CONNECT_TIMEOUT_MS", "1000");
|
||||
});
|
||||
afterEach(async () => {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("keyword search proxy", () => {
|
||||
it("preserves the backend support reference without returning secrets or changing error bytes", async () => {
|
||||
let forwardedId: string | string[] | undefined;
|
||||
handle = (req, res) => {
|
||||
forwardedId = req.headers["x-request-id"];
|
||||
res.writeHead(503, { "Content-Type": "application/json", "X-Request-ID": "backend-search-request" });
|
||||
res.end('{"detail":"KEYWORD_BUSY"}');
|
||||
};
|
||||
const result = await POST(request());
|
||||
expect(result.status).toBe(503);
|
||||
expect(await result.text()).toBe('{"detail":"KEYWORD_BUSY"}');
|
||||
expect(result.headers.get("x-request-id")).toBe("backend-search-request");
|
||||
expect(forwardedId).toMatch(/^[a-f0-9-]{36}$/);
|
||||
expect(hits).toBe(1);
|
||||
});
|
||||
it("also exposes the same handler directly at the existing public URL", () => {
|
||||
expect(publicPOST).toBe(POST);
|
||||
expect(dcSearchPOST).toBe(POST);
|
||||
});
|
||||
it("lets keyword search reach its public Node route without a timeout-limited rewrite", () => {
|
||||
const result = middleware(request());
|
||||
expect(result.headers.get("x-middleware-rewrite")).toBeNull();
|
||||
expect(result.headers.get("x-middleware-next")).toBe("1");
|
||||
expect(result.headers.get("content-security-policy")).toContain("img-src");
|
||||
const other = middleware(new NextRequest("https://dc.invalid/server/flask-service/jobs/test"));
|
||||
expect(new URL(other.headers.get("x-middleware-rewrite")!).pathname).toBe("/api/flask-service/jobs/test");
|
||||
});
|
||||
|
||||
it("uses the configured target and preserves exact request bytes and cookie authentication", async () => {
|
||||
auth.token = "cookie-token";
|
||||
auth.userId = "existing-user";
|
||||
let receivedBody = "";
|
||||
let receivedHeaders: http.IncomingHttpHeaders = {};
|
||||
let receivedPath = "";
|
||||
const responseBody = '{ "total_count": 1, "results": [{"name":"처리시설"}] }';
|
||||
handle = (req, res) => {
|
||||
receivedPath = req.url!;
|
||||
receivedHeaders = req.headers;
|
||||
req.setEncoding("utf8");
|
||||
req.on("data", (chunk) => { receivedBody += chunk; });
|
||||
req.on("end", () => {
|
||||
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", Authorization: "must-not-return" });
|
||||
res.end(responseBody);
|
||||
});
|
||||
};
|
||||
const result = await dcSearchPOST(request());
|
||||
expect(result.status).toBe(200);
|
||||
expect(await result.text()).toBe(responseBody);
|
||||
expect(receivedBody).toBe(body);
|
||||
expect(receivedHeaders["x-dc-preview-relay"]).toBe("1");
|
||||
expect(receivedPath).toBe("/dc-service/api/v1/rag-search/keyword-search");
|
||||
expect(receivedHeaders).toMatchObject({ authorization: "cookie-token", "token-id": "existing-user", "x-site-id": "DC" });
|
||||
expect(result.headers.get("authorization")).toBeNull();
|
||||
expect(result.headers.get("cache-control")).toBe("no-store");
|
||||
expect(hits).toBe(1);
|
||||
});
|
||||
|
||||
it.each([401, 403, 429, 500, 503])("preserves upstream %i and its body without retry", async (status) => {
|
||||
const upstreamBody = '{"detail":"upstream search error"}';
|
||||
handle = (_, res) => {
|
||||
res.writeHead(status, { "Content-Type": "application/json", "Retry-After": "5" });
|
||||
res.end(upstreamBody);
|
||||
};
|
||||
const result = await POST(request());
|
||||
expect(result.status).toBe(status);
|
||||
expect(await result.text()).toBe(upstreamBody);
|
||||
expect(result.headers.get("retry-after")).toBe("5");
|
||||
expect(hits).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps the deadline active until the response body completes", async () => {
|
||||
vi.stubEnv("KEYWORD_SEARCH_PROXY_TIMEOUT_MS", "50");
|
||||
let closed = false;
|
||||
handle = (_, res) => {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.write('{"partial":');
|
||||
res.on("close", () => { closed = true; });
|
||||
};
|
||||
const result = await POST(request());
|
||||
expect(result.status).toBe(504);
|
||||
expect((await result.json()).detail.code).toBe("KEYWORD_SEARCH_TIMEOUT");
|
||||
await vi.waitFor(() => expect(closed).toBe(true));
|
||||
expect(hits).toBe(1);
|
||||
});
|
||||
|
||||
it("returns 502 for a broken upstream connection without leaking connection data", async () => {
|
||||
const log = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
handle = (req) => req.socket.destroy();
|
||||
const result = await POST(request());
|
||||
expect(result.status).toBe(502);
|
||||
expect((await result.json()).detail.code).toBe("KEYWORD_SEARCH_UPSTREAM_UNAVAILABLE");
|
||||
expect(log).toHaveBeenCalledWith("[keyword-search] upstream_connection_failed", { status: 502 });
|
||||
expect(hits).toBe(1);
|
||||
});
|
||||
|
||||
it("propagates a client cancellation to the open upstream connection", async () => {
|
||||
const controller = new AbortController();
|
||||
let closed = false;
|
||||
let started!: () => void;
|
||||
const ready = new Promise<void>((resolve) => { started = resolve; });
|
||||
handle = (_, res) => { res.on("close", () => { closed = true; }); started(); };
|
||||
const pending = POST(request(controller.signal));
|
||||
await ready;
|
||||
controller.abort();
|
||||
const result = await pending;
|
||||
expect(result.status).toBe(499);
|
||||
await vi.waitFor(() => expect(closed).toBe(true));
|
||||
expect(hits).toBe(1);
|
||||
});
|
||||
|
||||
it("does not contact the upstream for an already cancelled request", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
expect((await POST(request(controller.signal))).status).toBe(499);
|
||||
expect(hits).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { CLAIM_NAME, AUTH_USER_ID } from "@/shared/config";
|
||||
import { SITE_ID } from "@/shared/config/env";
|
||||
import { resolveDcServiceUrl } from "@/shared/api/dc-service-request";
|
||||
import { DC_SEARCH_RELAY_PATH, dcGatewayContext } from "@/shared/api/dc-search-relay";
|
||||
import { KeywordSearchProxyError, proxyKeywordSearch } from "@/shared/api/keyword-search-proxy";
|
||||
import { operationDiagnostics } from "@/server/operation-diagnostics";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 300;
|
||||
|
||||
function timeoutMs(value: string | undefined, fallback: number): number {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) && parsed > 0 && parsed <= 300_000 ? parsed : fallback;
|
||||
}
|
||||
|
||||
function rawErrorResponse(status: number, code: string, message: string) {
|
||||
return NextResponse.json({ detail: { code, message } }, {
|
||||
status, headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const diagnostic = operationDiagnostics("keyword-search");
|
||||
const errorResponse: typeof rawErrorResponse = (...args) => diagnostic.finish(rawErrorResponse(...args), { code: args[1] });
|
||||
try {
|
||||
// 목적지는 서버 설정으로만 결정한다. URL/헤더/본문의 전달 주소는 사용하지 않는다.
|
||||
const target = resolveDcServiceUrl(`${DC_SEARCH_RELAY_PATH}/keyword-search`);
|
||||
const cookieStore = await cookies();
|
||||
const headers: Record<string, string> = {
|
||||
...dcGatewayContext(request.headers),
|
||||
"X-Site-Id": SITE_ID,
|
||||
"x-request-id": diagnostic.requestId,
|
||||
"Content-Type": request.headers.get("content-type") ?? "application/json",
|
||||
Accept: request.headers.get("accept") ?? "application/json",
|
||||
};
|
||||
for (const name of [CLAIM_NAME, AUTH_USER_ID, "X-Site-Id"]) {
|
||||
const value = request.headers.get(name);
|
||||
if (value) headers[name] = value;
|
||||
}
|
||||
for (const name of [CLAIM_NAME, AUTH_USER_ID]) {
|
||||
const value = cookieStore.get(name)?.value;
|
||||
if (value) headers[name] = value;
|
||||
}
|
||||
const token = headers[CLAIM_NAME];
|
||||
if (token && CLAIM_NAME.toLowerCase() !== "authorization") headers.Authorization = token;
|
||||
if (request.signal.aborted) throw new KeywordSearchProxyError("client_aborted");
|
||||
const body = Buffer.from(await request.arrayBuffer());
|
||||
const upstream = await proxyKeywordSearch({
|
||||
target, headers, body, signal: request.signal,
|
||||
connectTimeoutMs: timeoutMs(process.env.KEYWORD_SEARCH_PROXY_CONNECT_TIMEOUT_MS, 10_000),
|
||||
responseTimeoutMs: timeoutMs(process.env.KEYWORD_SEARCH_PROXY_TIMEOUT_MS, 60_000),
|
||||
});
|
||||
const responseHeaders = new Headers({ "Cache-Control": "no-store" });
|
||||
for (const name of ["content-type", "content-encoding", "content-language", "retry-after"]) {
|
||||
const value = upstream.headers[name];
|
||||
if (typeof value === "string") responseHeaders.set(name, value);
|
||||
}
|
||||
// 상위 서버의 실패 상태와 본문도 그대로 보존한다.
|
||||
return diagnostic.finish(new Response([204, 205, 304].includes(upstream.status) ? null : new Uint8Array(upstream.body), {
|
||||
status: upstream.status, headers: responseHeaders,
|
||||
}), { upstreamRequestId: typeof upstream.headers["x-request-id"] === "string" ? upstream.headers["x-request-id"] : undefined });
|
||||
} catch (error: unknown) {
|
||||
if (request.signal.aborted || (error instanceof KeywordSearchProxyError && error.kind === "client_aborted")) {
|
||||
return errorResponse(499, "KEYWORD_SEARCH_CANCELLED", "검색 요청이 취소되었습니다.");
|
||||
}
|
||||
if (error instanceof KeywordSearchProxyError && error.kind === "timeout") {
|
||||
return errorResponse(504, "KEYWORD_SEARCH_TIMEOUT", "검색 서버 응답 시간이 초과되었습니다. 잠시 후 다시 시도해 주세요.");
|
||||
}
|
||||
// 주소, 쿠키, 원시 예외 문자열을 로그나 응답에 노출하지 않는다.
|
||||
console.warn("[keyword-search] upstream_connection_failed", { status: 502 });
|
||||
return errorResponse(502, "KEYWORD_SEARCH_UPSTREAM_UNAVAILABLE", "검색 서버에 연결할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { GET, POST, PUT } from "./route";
|
||||
import { attestReuploadOwner } from "@/server/file-registry-attestation";
|
||||
|
||||
const logical = "00000000-0000-4000-8000-000000000001";
|
||||
vi.mock("@/server/file-registry-attestation", async importOriginal => {
|
||||
const original = await importOriginal<typeof import("@/server/file-registry-attestation")>();
|
||||
return {
|
||||
...original,
|
||||
attestRegisteredFile: vi.fn(async () => ({
|
||||
fileSn: logical, projectId: "trusted-project", clsfSystmSn: "trusted-leaf",
|
||||
classificationPath: ["trusted-project", "trusted-leaf"], useYn: "Y",
|
||||
})),
|
||||
attestReuploadOwner: vi.fn(async () => undefined),
|
||||
registryAuthHeaders: vi.fn(() => new Headers({
|
||||
Authorization: `Bearer x.${Buffer.from(JSON.stringify({ sub: "test-user" })).toString("base64url")}.y`,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
describe("registered reupload staging", () => {
|
||||
afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); vi.clearAllMocks(); });
|
||||
|
||||
it("forwards only the attested logical target with a server-only key", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
const upstream = vi.fn(async (_url: URL, init: RequestInit) => {
|
||||
const body = init.body as FormData;
|
||||
expect(body.get("existing_file_sn")).toBe(logical);
|
||||
expect(body.get("project_id")).toBe("trusted-project");
|
||||
expect(body.get("clsf_systm_sn")).toBe("trusted-leaf");
|
||||
expect(body.get("reupload_stage")).toBe("1");
|
||||
expect(body.get("reupload_expected_current_ingestion_id")).toBe("old-ingestion");
|
||||
expect(new Headers(init.headers).get("X-Rag-V2-Internal-Key")).toBe("test-only-internal-key");
|
||||
return Response.json({ job_id: "00000000-0000-4000-8000-000000000002" });
|
||||
});
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
const form = new FormData();
|
||||
form.set("file", new File(["%PDF"], "same.pdf", { type: "application/pdf" }));
|
||||
form.set("existing_file_sn", logical);
|
||||
form.set("project_id", "trusted-project");
|
||||
form.set("clsf_systm_sn", "trusted-leaf");
|
||||
form.set("reupload_expected_current_ingestion_id", "old-ingestion");
|
||||
const request = new NextRequest("http://localhost/api/flask-service/reupload-stage/jobs", { method: "POST" });
|
||||
vi.spyOn(request, "formData").mockResolvedValue(form);
|
||||
const response = await POST(request);
|
||||
expect(response.status).toBe(200);
|
||||
expect(attestReuploadOwner).toHaveBeenCalledOnce();
|
||||
expect(upstream).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("looks up only the attested stage identity without starting another upload", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
const stage = "00000000-0000-4000-8000-000000000002";
|
||||
const upstream = vi.fn(async (_url: URL, init: RequestInit) => {
|
||||
const body = init.body as FormData;
|
||||
expect(body.get("existing_file_sn")).toBe(logical);
|
||||
expect(body.get("original_sha256")).toBe("a".repeat(64));
|
||||
expect(body.get("reupload_expected_current_ingestion_id")).toBe("old-ingestion");
|
||||
return Response.json({ stage_file_sn: stage, stored: true, pdf_ready: true });
|
||||
});
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
const query = new URLSearchParams({ existing_file_sn: logical, project_id: "trusted-project",
|
||||
clsf_systm_sn: "trusted-leaf", reupload_expected_current_ingestion_id: "old-ingestion",
|
||||
original_filename: "same.pdf", original_sha256: "a".repeat(64) });
|
||||
const response = await GET(new NextRequest(`http://localhost/api/flask-service/reupload-stage/jobs?${query}`));
|
||||
expect(response.status).toBe(200);
|
||||
expect(upstream).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("converts only the verified stage with the authenticated internal key", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
const stage = "00000000-0000-4000-8000-000000000002";
|
||||
const uploadJobId = "00000000-0000-4000-8000-000000000003";
|
||||
const upstream = vi.fn(async (url: URL, init: RequestInit) => {
|
||||
expect(new Headers(init.headers).get("X-Rag-V2-Internal-Key")).toBe("test-only-internal-key");
|
||||
expect(new Headers(init.headers).get("Authorization")).toMatch(/^Bearer /);
|
||||
const body = init.body as FormData;
|
||||
if (url.pathname.endsWith("/reupload-stage/lookup")) {
|
||||
expect(body.get("original_sha256")).toBe("a".repeat(64));
|
||||
return Response.json({ stage_file_sn: stage, stored: true, pdf_ready: false });
|
||||
}
|
||||
expect(url.pathname).toBe("/flask-service/convert-to-pdf/jobs");
|
||||
expect(body.get("file_sn")).toBe(stage);
|
||||
expect(body.get("upload_job_id")).toBe(uploadJobId);
|
||||
expect(body.get("file")).toBeNull();
|
||||
return Response.json({ job_id: "00000000-0000-4000-8000-000000000004" });
|
||||
});
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
const form = new FormData();
|
||||
form.set("existing_file_sn", logical);
|
||||
form.set("project_id", "trusted-project");
|
||||
form.set("clsf_systm_sn", "trusted-leaf");
|
||||
form.set("reupload_expected_current_ingestion_id", "old-ingestion");
|
||||
form.set("original_filename", "same.pdf");
|
||||
form.set("original_sha256", "a".repeat(64));
|
||||
form.set("stage_file_sn", stage);
|
||||
form.set("upload_job_id", uploadJobId);
|
||||
const request = new NextRequest("http://localhost/api/flask-service/reupload-stage/jobs", { method: "PUT" });
|
||||
vi.spyOn(request, "formData").mockResolvedValue(form);
|
||||
const response = await PUT(request);
|
||||
expect(response.status).toBe(200);
|
||||
expect(attestReuploadOwner).toHaveBeenCalledOnce();
|
||||
expect(upstream).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not convert a stage that differs from the server binding", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081");
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-internal-key");
|
||||
const upstream = vi.fn(async () => Response.json({
|
||||
stage_file_sn: "00000000-0000-4000-8000-000000000009", stored: true, pdf_ready: false,
|
||||
}));
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
const form = new FormData();
|
||||
form.set("existing_file_sn", logical);
|
||||
form.set("project_id", "trusted-project");
|
||||
form.set("clsf_systm_sn", "trusted-leaf");
|
||||
form.set("reupload_expected_current_ingestion_id", "old-ingestion");
|
||||
form.set("original_filename", "same.pdf");
|
||||
form.set("original_sha256", "a".repeat(64));
|
||||
form.set("stage_file_sn", "00000000-0000-4000-8000-000000000002");
|
||||
form.set("upload_job_id", "00000000-0000-4000-8000-000000000003");
|
||||
const request = new NextRequest("http://localhost/api/flask-service/reupload-stage/jobs", { method: "PUT" });
|
||||
vi.spyOn(request, "formData").mockResolvedValue(form);
|
||||
const response = await PUT(request);
|
||||
expect(response.status).toBe(409);
|
||||
expect(upstream).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("authenticated Current-original staging without a browser upload", () => {
|
||||
it("attests the master and owner before forwarding the explicit reuse mode", async () => {
|
||||
vi.stubEnv("FLASK_API_URL", "http://127.0.0.1:18081"); vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-key");
|
||||
const upstream = vi.fn(async (_url, init: RequestInit) => {
|
||||
expect(attestReuploadOwner).toHaveBeenCalledOnce();
|
||||
const body = init.body as FormData;
|
||||
expect(body.has("file")).toBe(false); expect(body.get("reuse_current_original")).toBe("1");
|
||||
expect(body.get("reupload_stage")).toBe("1"); expect(body.get("existing_file_sn")).toBe(logical);
|
||||
expect(body.get("project_id")).toBe("trusted-project");
|
||||
expect(new Headers(init.headers).get("X-Rag-V2-Internal-Key")).toBe("test-only-key");
|
||||
return Response.json({ job_id: "00000000-0000-4000-8000-000000000003" });
|
||||
}); vi.stubGlobal("fetch", upstream);
|
||||
const form = new FormData(); form.set("reuse_current_original", "1"); form.set("existing_file_sn", logical);
|
||||
form.set("project_id", "trusted-project"); form.set("clsf_systm_sn", "trusted-leaf"); form.set("reupload_expected_current_ingestion_id", "current");
|
||||
const request = new NextRequest("http://localhost/api/flask-service/reupload-stage/jobs", { method: "POST" });
|
||||
vi.spyOn(request, "formData").mockResolvedValue(form);
|
||||
expect((await POST(request)).status).toBe(200); expect(upstream).toHaveBeenCalledOnce();
|
||||
vi.unstubAllEnvs(); vi.unstubAllGlobals(); vi.clearAllMocks();
|
||||
});
|
||||
it.each([undefined, "0", "true"])("does not accept a missing file without exact reuse=1: %s", async flag => {
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "test-only-key");
|
||||
const fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock);
|
||||
const form = new FormData(); if (flag) form.set("reuse_current_original", flag);
|
||||
form.set("existing_file_sn", logical); form.set("project_id", "trusted-project"); form.set("clsf_systm_sn", "trusted-leaf"); form.set("reupload_expected_current_ingestion_id", "current");
|
||||
const request = new NextRequest("http://localhost/api/flask-service/reupload-stage/jobs", { method: "POST" }); vi.spyOn(request, "formData").mockResolvedValue(form);
|
||||
expect((await POST(request)).status).toBe(400); expect(fetchMock).not.toHaveBeenCalled();
|
||||
vi.unstubAllEnvs(); vi.unstubAllGlobals(); vi.clearAllMocks();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { registryForwardContext } from "@/server/rag-forward-context";
|
||||
import {
|
||||
attestReuploadOwner,
|
||||
attestRegisteredFile,
|
||||
dcRagUrl,
|
||||
FileRegistryError,
|
||||
ragInternalHeaders,
|
||||
registryAuthHeaders,
|
||||
} from "@/server/file-registry-attestation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 300;
|
||||
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
function value(form: FormData, key: string): string {
|
||||
const item = form.get(key);
|
||||
return typeof item === "string" ? item.trim() : "";
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest): Promise<Response> {
|
||||
try {
|
||||
const headers = ragInternalHeaders(registryAuthHeaders(request));
|
||||
const form = await request.formData();
|
||||
const file = form.get("file");
|
||||
const reuseCurrentOriginal = value(form, "reuse_current_original") === "1";
|
||||
const existingFileSn = value(form, "existing_file_sn");
|
||||
const projectId = value(form, "project_id");
|
||||
const clsfSystmSn = value(form, "clsf_systm_sn");
|
||||
const expectedCurrent = value(form, "reupload_expected_current_ingestion_id");
|
||||
if ((reuseCurrentOriginal ? file !== null : !(file instanceof File) || !file.size) || !UUID.test(existingFileSn) ||
|
||||
!projectId || !clsfSystmSn || !/^[A-Za-z0-9_-]{1,256}$/.test(expectedCurrent)) {
|
||||
return NextResponse.json({ detail: "REUPLOAD_STAGE_REQUEST_INVALID" }, { status: 400 });
|
||||
}
|
||||
const registered = await attestRegisteredFile(request, {
|
||||
fileSn: existingFileSn, projectId, clsfSystmSn,
|
||||
});
|
||||
await attestReuploadOwner(request, registered);
|
||||
const upstream = new FormData();
|
||||
if (reuseCurrentOriginal) upstream.set("reuse_current_original", "1");
|
||||
else upstream.set("file", file as File);
|
||||
upstream.set("reupload_stage", "1");
|
||||
upstream.set("existing_file_sn", registered.fileSn);
|
||||
upstream.set("reupload_expected_current_ingestion_id", expectedCurrent);
|
||||
upstream.set("clsf_systm_sn", registered.clsfSystmSn);
|
||||
upstream.set("project_id", registered.projectId);
|
||||
upstream.set("registry_context", JSON.stringify(registryForwardContext(registered, headers)));
|
||||
const response = await fetch(dcRagUrl("/api/v1/file/jobs"), {
|
||||
method: "POST", headers, body: upstream, cache: "no-store", signal: request.signal,
|
||||
});
|
||||
return new Response(await response.text(), {
|
||||
status: response.status,
|
||||
headers: { "Content-Type": response.headers.get("content-type") || "application/json", "Cache-Control": "no-store" },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) {
|
||||
return NextResponse.json({ detail: error.code }, { status: error.status });
|
||||
}
|
||||
return NextResponse.json({ detail: "REUPLOAD_STAGE_UNAVAILABLE" }, { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest): Promise<Response> {
|
||||
try {
|
||||
const headers = ragInternalHeaders(registryAuthHeaders(request));
|
||||
const query = request.nextUrl.searchParams;
|
||||
const existingFileSn = query.get("existing_file_sn")?.trim() || "";
|
||||
const projectId = query.get("project_id")?.trim() || "";
|
||||
const clsfSystmSn = query.get("clsf_systm_sn")?.trim() || "";
|
||||
const expectedCurrent = query.get("reupload_expected_current_ingestion_id")?.trim() || "";
|
||||
const originalFilename = query.get("original_filename")?.trim() || "";
|
||||
const originalSha256 = query.get("original_sha256")?.trim() || "";
|
||||
if (!UUID.test(existingFileSn) || !projectId || !clsfSystmSn ||
|
||||
!/^[A-Za-z0-9_-]{1,256}$/.test(expectedCurrent) ||
|
||||
!originalFilename || !/^[0-9a-f]{64}$/.test(originalSha256)) {
|
||||
return NextResponse.json({ detail: "REUPLOAD_STAGE_LOOKUP_INVALID" }, { status: 400 });
|
||||
}
|
||||
const registered = await attestRegisteredFile(request, {
|
||||
fileSn: existingFileSn, projectId, clsfSystmSn,
|
||||
});
|
||||
await attestReuploadOwner(request, registered);
|
||||
const upstream = new FormData();
|
||||
upstream.set("existing_file_sn", registered.fileSn);
|
||||
upstream.set("clsf_systm_sn", registered.clsfSystmSn);
|
||||
upstream.set("reupload_expected_current_ingestion_id", expectedCurrent);
|
||||
upstream.set("original_filename", originalFilename);
|
||||
upstream.set("original_sha256", originalSha256);
|
||||
upstream.set("registry_context", JSON.stringify(registryForwardContext(registered, headers)));
|
||||
const response = await fetch(dcRagUrl("/api/v1/file/reupload-stage/lookup"), {
|
||||
method: "POST", headers, body: upstream, cache: "no-store", signal: request.signal,
|
||||
});
|
||||
return new Response(await response.text(), {
|
||||
status: response.status,
|
||||
headers: { "Content-Type": response.headers.get("content-type") || "application/json", "Cache-Control": "no-store" },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) {
|
||||
return NextResponse.json({ detail: error.code }, { status: error.status });
|
||||
}
|
||||
return NextResponse.json({ detail: "REUPLOAD_STAGE_LOOKUP_UNAVAILABLE" }, { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
/** Forward conversion only for the authenticated immutable reupload stage. */
|
||||
export async function PUT(request: NextRequest): Promise<Response> {
|
||||
try {
|
||||
const headers = ragInternalHeaders(registryAuthHeaders(request));
|
||||
const form = await request.formData();
|
||||
const existingFileSn = value(form, "existing_file_sn");
|
||||
const projectId = value(form, "project_id");
|
||||
const clsfSystmSn = value(form, "clsf_systm_sn");
|
||||
const expectedCurrent = value(form, "reupload_expected_current_ingestion_id");
|
||||
const originalFilename = value(form, "original_filename");
|
||||
const originalSha256 = value(form, "original_sha256");
|
||||
const stageFileSn = value(form, "stage_file_sn");
|
||||
const uploadJobId = value(form, "upload_job_id");
|
||||
if (!UUID.test(existingFileSn) || !UUID.test(stageFileSn) || !UUID.test(uploadJobId) ||
|
||||
!projectId || !clsfSystmSn ||
|
||||
!/^[A-Za-z0-9_-]{1,256}$/.test(expectedCurrent) ||
|
||||
!originalFilename || !/^[0-9a-f]{64}$/.test(originalSha256)) {
|
||||
return NextResponse.json({ detail: "REUPLOAD_CONVERSION_REQUEST_INVALID" }, { status: 400 });
|
||||
}
|
||||
const registered = await attestRegisteredFile(request, {
|
||||
fileSn: existingFileSn, projectId, clsfSystmSn,
|
||||
});
|
||||
await attestReuploadOwner(request, registered);
|
||||
const lookup = new FormData();
|
||||
lookup.set("existing_file_sn", registered.fileSn);
|
||||
lookup.set("clsf_systm_sn", registered.clsfSystmSn);
|
||||
lookup.set("reupload_expected_current_ingestion_id", expectedCurrent);
|
||||
lookup.set("original_filename", originalFilename);
|
||||
lookup.set("original_sha256", originalSha256);
|
||||
lookup.set("registry_context", JSON.stringify(registryForwardContext(registered, headers)));
|
||||
const stageResponse = await fetch(dcRagUrl("/api/v1/file/reupload-stage/lookup"), {
|
||||
method: "POST", headers, body: lookup, cache: "no-store", signal: request.signal,
|
||||
});
|
||||
if (!stageResponse.ok) {
|
||||
return new Response(await stageResponse.text(), {
|
||||
status: stageResponse.status,
|
||||
headers: { "Content-Type": stageResponse.headers.get("content-type") || "application/json", "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
const stage = await stageResponse.json();
|
||||
if (stage?.stage_file_sn !== stageFileSn || stage?.stored !== true) {
|
||||
return NextResponse.json({ detail: "REUPLOAD_CONVERSION_STAGE_MISMATCH" }, { status: 409 });
|
||||
}
|
||||
const upstream = new FormData();
|
||||
upstream.set("file_sn", stageFileSn);
|
||||
upstream.set("upload_job_id", uploadJobId);
|
||||
const response = await fetch(dcRagUrl("/convert-to-pdf/jobs"), {
|
||||
method: "POST", headers, body: upstream, cache: "no-store", signal: request.signal,
|
||||
});
|
||||
return new Response(await response.text(), {
|
||||
status: response.status,
|
||||
headers: { "Content-Type": response.headers.get("content-type") || "application/json", "Cache-Control": "no-store" },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) {
|
||||
return NextResponse.json({ detail: error.code }, { status: error.status });
|
||||
}
|
||||
return NextResponse.json({ detail: "REUPLOAD_CONVERSION_UNAVAILABLE" }, { status: 502 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { GET } from "./route";
|
||||
|
||||
const qr = "https://frontend.invalid/api/general-search/current-original?";
|
||||
const query = new URLSearchParams({ fileSn: "file-1", revisionId: "rev-2" }).toString();
|
||||
|
||||
describe("previously issued revision QR links", () => {
|
||||
it("sends the scanning browser to the public DC download with the exact file and revision", () => {
|
||||
const response = GET(new NextRequest(qr + query));
|
||||
expect(response.status).toBe(307);
|
||||
expect(response.headers.get("Location")).toBe("/dc-service/api/v1/fileDownload?" + query);
|
||||
expect(response.headers.get("Cache-Control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it.each([query + "&filePath=unexpected", query + "&revisionId=other", "revisionId=r2", "filePath=doc.pdf"])(
|
||||
"rejects incomplete or ambiguous QR arguments (%s)", search => {
|
||||
const response = GET(new NextRequest(qr + search));
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.headers.has("Location")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { DC_FILE_DOWNLOAD_PATH } from "@/entities/datalibrary/api/source-file-reference";
|
||||
import { downloadFailure } from "@/server/dc-attachment";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Previously issued revision QR codes point here. Resolve them using the scanning user's DC request.
|
||||
export function GET(request: NextRequest): Response {
|
||||
const params = request.nextUrl.searchParams;
|
||||
const fileSn = params.get("fileSn");
|
||||
const revisionId = params.get("revisionId");
|
||||
if (params.size !== 2 || !fileSn || !revisionId || fileSn.length > 256 || revisionId.length > 512) {
|
||||
return downloadFailure(400);
|
||||
}
|
||||
return new Response(null, {
|
||||
status: 307, headers: { Location: `${DC_FILE_DOWNLOAD_PATH}?${params}`, "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { middleware } from "../../../../middleware";
|
||||
import { GET, POST } from "./route";
|
||||
import { GET as legacyPreview } from "../legacy-preview/route";
|
||||
import { DC_PREVIEW_RELAY_HEADER } from "@/shared/api/dc-service-request";
|
||||
|
||||
const gateway = "https://gateway.invalid";
|
||||
const frontend = "https://frontend.invalid";
|
||||
const dc = "/dc-service/api/v1";
|
||||
const current = dc + "/general-search/current-source";
|
||||
const files = dc + "/general-search/files";
|
||||
const imageQuery = "?fileSn=f&previewRevisionId=r&previewPage=2";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("NEXT_PUBLIC_DC_SERVICE_API_URL", gateway);
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "server-only");
|
||||
});
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
describe("general search gateway routing", () => {
|
||||
it.each([
|
||||
["GET", dc + "/fileprcs?fileSn=f"],
|
||||
["GET", dc + "/fileDownload?filePath=uploads%2Fdoc.pdf&fileSn=f"],
|
||||
["GET", dc + "/fileDownload?fileSn=f&revisionId=r"],
|
||||
["POST", current],
|
||||
["GET", current + imageQuery],
|
||||
["GET", files + "/f/image-list"],
|
||||
["GET", files + "/f/image-preview/report%20A.PNG"],
|
||||
])("forwards %s %s to the DC gateway with the signed-in user", async (method, path) => {
|
||||
const body = method === "POST" ? JSON.stringify({ fileSn: "f", previewMode: true }) : undefined;
|
||||
const req = new NextRequest(frontend + path, {
|
||||
method, body,
|
||||
headers: {
|
||||
Cookie: "Authorization=session.fixture.token", Authorization: "untrusted",
|
||||
Accept: path.includes("preview") ? "image/png" : "application/json",
|
||||
...(body ? { "Content-Type": "application/json" } : {}),
|
||||
"X-Rag-V2-Internal-Key": "untrusted",
|
||||
},
|
||||
});
|
||||
const response = middleware(req);
|
||||
expect(response.headers.get("x-middleware-rewrite")).toBe(gateway + path);
|
||||
expect(response.headers.has("Location")).toBe(false);
|
||||
expect(response.headers.get("x-middleware-request-authorization")).toBe("session.fixture.token");
|
||||
if (path.startsWith(dc + "/general-search/") || path.includes("revisionId=")) {
|
||||
expect(response.headers.has("x-middleware-request-x-rag-v2-internal-key")).toBe(false);
|
||||
}
|
||||
if (path.includes("preview")) expect(response.headers.get("x-middleware-request-accept")).toBe("image/png");
|
||||
if (body) {
|
||||
expect(response.headers.get("x-middleware-request-content-type")).toBe("application/json");
|
||||
expect(await req.text()).toBe(body);
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a preview accidentally routed back to this frontend", () => {
|
||||
const req = new NextRequest(frontend + current, { headers: { [DC_PREVIEW_RELAY_HEADER]: "1" } });
|
||||
expect(middleware(req).status).toBe(502);
|
||||
});
|
||||
|
||||
it("keeps the existing general search results GET in the connection-reusing handler", () => {
|
||||
const response = middleware(new NextRequest(frontend + dc + "/data?searchText=f"));
|
||||
expect(response.headers.get("x-middleware-next")).toBe("1");
|
||||
expect(response.headers.has("x-middleware-rewrite")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("previously published preview URLs", () => {
|
||||
it.each([["GET", imageQuery], ["POST", ""]])("preserves the %s method in the redirect to DC", (method, query) => {
|
||||
const req = new NextRequest(frontend + "/api/general-search/current-source" + query, { method });
|
||||
const response = method === "POST" ? POST(req) : GET(req);
|
||||
expect(response.status).toBe(307);
|
||||
expect(response.headers.get("Location")).toBe(current + query);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["fileSn=f", files + "/f/image-list"],
|
||||
["fileSn=f&imageName=report%20A.png", files + "/f/image-preview/report%20A.png"],
|
||||
])("keeps older image links usable (%s)", (query, expected) => {
|
||||
const response = legacyPreview(new NextRequest(frontend + "/api/general-search/legacy-preview?" + query));
|
||||
expect(response.status).toBe(307);
|
||||
expect(response.headers.get("Location")).toBe(expected);
|
||||
});
|
||||
|
||||
it.each(["fileSn=..", "fileSn=f&fileSn=g", "fileSn=f&imageName=..%2Fother.png", "fileSn=f&imageName=other.svg"])(
|
||||
"rejects an invalid legacy link before redirecting (%s)", query => {
|
||||
const response = legacyPreview(new NextRequest(frontend + "/api/general-search/legacy-preview?" + query));
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.headers.has("Location")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { currentSourceUrl } from "@/entities/datalibrary/api/preview-routes";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Older clients used this URL for both JSON lookups and inline page images.
|
||||
function redirectToDc(request: NextRequest): Response {
|
||||
return new Response(null, {
|
||||
status: 307,
|
||||
headers: { Location: currentSourceUrl("general-search") + request.nextUrl.search, "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
export { redirectToDc as GET, redirectToDc as POST };
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { legacyPreviewUrl } from "@/entities/datalibrary/api/preview-routes";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export function GET(request: NextRequest): Response {
|
||||
const params = request.nextUrl.searchParams;
|
||||
const fileSn = params.get("fileSn") ?? "";
|
||||
const imageName = params.get("imageName");
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(fileSn) || params.size !== (imageName === null ? 1 : 2) ||
|
||||
(imageName !== null && (imageName.length > 255 || !/\.png$/i.test(imageName) ||
|
||||
imageName.startsWith(".") || /[\\/%:?#;\u0000-\u001f\u007f]/.test(imageName)))) {
|
||||
return NextResponse.json({ detail: "INVALID_PREVIEW_REQUEST" }, { status: 400, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
return new Response(null, {
|
||||
status: 307,
|
||||
headers: { Location: legacyPreviewUrl("general-search", fileSn, imageName ?? undefined), "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const cookieGet = vi.fn();
|
||||
const cookieSet = vi.fn();
|
||||
|
||||
vi.mock("next/headers", () => ({
|
||||
cookies: vi.fn(async () => ({
|
||||
get: cookieGet,
|
||||
set: cookieSet,
|
||||
})),
|
||||
}));
|
||||
|
||||
describe("DC login API proxy", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
cookieGet.mockReset();
|
||||
cookieSet.mockReset();
|
||||
vi.stubEnv("SERVER_API_URL", "https://backend.example");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[undefined, "DC"],
|
||||
["custom-site", "custom-site"],
|
||||
])("sends the archive site ID for login and refresh (%s)", async (configured, expected) => {
|
||||
vi.stubEnv("NEXT_PUBLIC_SITE_ID", configured);
|
||||
cookieGet.mockReturnValue({ value: "test-refresh-token" });
|
||||
const fetchMock = vi.fn().mockImplementation(async () => new Response(null, { status: 401 }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { POST } = await import("./route");
|
||||
for (const suffix of [["login"], ["token", "refresh"]]) {
|
||||
const url = ["user-service", "api", "v1", ...suffix];
|
||||
const response = await POST(new Request(`https://frontend.example/api/proxy/${url.join("/")}`, {
|
||||
method: "POST", body: "{}",
|
||||
}), { params: Promise.resolve({ url }) });
|
||||
expect(response.status).toBe(401);
|
||||
}
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
for (const [, options] of fetchMock.mock.calls) {
|
||||
expect(new Headers(options.headers).get("x-site-id")).toBe(expected);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["", "https://legacy.example"],
|
||||
["https://server.example", "https://server.example"],
|
||||
])("routes login with both gateway variable conventions (%s)", async (server, expected) => {
|
||||
vi.stubEnv("SERVER_API_URL", server);
|
||||
vi.stubEnv("NEXT_PUBLIC_SERVER_API_URL", "https://legacy.example");
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response("{}", { status: 401 }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { POST } = await import("./route");
|
||||
const response = await POST(new Request("https://frontend.example/api/proxy/user-service/login", {
|
||||
method: "POST", body: "{}",
|
||||
}), { params: Promise.resolve({ url: ["user-service", "login"] }) });
|
||||
expect(response.status).toBe(401);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
`${expected}/user-service/login`,
|
||||
expect.objectContaining({ method: "POST" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("forwards the ingress IP and device ID while preserving the login body and tokens", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"access-token": "access-token-value",
|
||||
"token-id": "token-id-value",
|
||||
"refresh-token": "refresh-token-value",
|
||||
},
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const { POST } = await import("./route");
|
||||
const request = new Request(
|
||||
"https://frontend.example/api/proxy/user-service/login",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Device-Id": "device-id-value",
|
||||
"X-Forwarded-For": "192.0.2.20, 192.0.2.21",
|
||||
"X-Real-IP": "192.0.2.22",
|
||||
"X-Client-IP": "192.0.2.99",
|
||||
},
|
||||
body: JSON.stringify({ username: "user" }),
|
||||
},
|
||||
);
|
||||
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ url: ["user-service", "login"] }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect(fetchMock.mock.calls[0]?.[0]).toBe(
|
||||
"https://backend.example/user-service/login",
|
||||
);
|
||||
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ username: "user" }),
|
||||
headers: expect.objectContaining({
|
||||
"X-Device-Id": "device-id-value",
|
||||
}),
|
||||
});
|
||||
const forwarded = new Headers(fetchMock.mock.calls[0]?.[1]?.headers);
|
||||
expect(forwarded.get("x-client-ip")).toBe("192.0.2.20");
|
||||
expect(await response.json()).toEqual({ "access-token": "access-token-value", "token-id": "token-id-value" });
|
||||
expect(cookieSet).toHaveBeenCalledWith("refresh-token", "refresh-token-value", { httpOnly: true, sameSite: "lax", path: "/" });
|
||||
});
|
||||
|
||||
it("omits absent device and ingress identity headers, even if a client IP was supplied", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"access-token": "access-token-value",
|
||||
"token-id": "token-id-value",
|
||||
},
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const { POST } = await import("./route");
|
||||
const request = new Request(
|
||||
"https://frontend.example/api/proxy/user-service/login",
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "X-Client-IP": "192.0.2.99" },
|
||||
body: JSON.stringify({ username: "user" }),
|
||||
},
|
||||
);
|
||||
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ url: ["user-service", "login"] }),
|
||||
});
|
||||
const forwardedHeaders = fetchMock.mock.calls[0]?.[1]?.headers as Record<
|
||||
string,
|
||||
string
|
||||
>;
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(forwardedHeaders).not.toHaveProperty("X-Device-Id");
|
||||
expect(new Headers(forwardedHeaders).has("x-client-ip")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,29 +1,48 @@
|
||||
import {
|
||||
ACCESS_TOKEN,
|
||||
AUTH_USER_ID,
|
||||
CLAIM_NAME,
|
||||
REFRESH_TOKEN,
|
||||
SERVER_API_URL,
|
||||
SITE_ID,
|
||||
} from "@/shared/config";
|
||||
/**
|
||||
* 📄 Proxy Route
|
||||
* API 프록시 라우트
|
||||
*
|
||||
* - 서버 API로의 요청 프록시 처리
|
||||
* - 쿠키 기반 인증 토큰 및 리프레시 토큰 관리
|
||||
* - POST 및 PUT 요청 핸들링
|
||||
* - 사용자 인증 정보 검증 및 응답 처리
|
||||
* - 에러 핸들링 및 상태 코드 반환
|
||||
* - 사이트 ID 및 헤더 설정
|
||||
*/
|
||||
import { cookies } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { clientIpHeaders } from "../../../../client-ip";
|
||||
import { protectedRagProxyRoute } from "@/shared/api/rag-proxy-boundary";
|
||||
import { SERVER_API_URL, SITE_ID } from "@/shared/config/env";
|
||||
|
||||
const ACCESS_TOKEN = process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token";
|
||||
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
|
||||
const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
|
||||
const REFRESH_TOKEN = process.env.NEXT_PUBLIC_REFRESH_TOKEN || "refresh-token";
|
||||
|
||||
async function handler(
|
||||
request: Request,
|
||||
params: { url: string[] },
|
||||
method: "GET" | "POST" | "PUT" | "DELETE",
|
||||
) {
|
||||
if (protectedRagProxyRoute(`/${params.url.join("/")}`)) {
|
||||
return NextResponse.json({ message: "RAG_FRONTEND_ROUTE_REQUIRED" }, { status: 403 });
|
||||
}
|
||||
const cookieStore = await cookies();
|
||||
const isRefreshHandler = params.url.includes("refresh");
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
"X-Site-Id": SITE_ID,
|
||||
// 브라우저 IP (로그인/접속 로그용)
|
||||
...clientIpHeaders(request),
|
||||
};
|
||||
const deviceId = request.headers.get("X-Device-Id");
|
||||
if (deviceId) {
|
||||
headers["X-Device-Id"] = deviceId;
|
||||
}
|
||||
let body = {};
|
||||
const isRefreshHandler = params.url.includes("refresh");
|
||||
|
||||
if (!isRefreshHandler) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
// silent refresh
|
||||
if (isRefreshHandler) {
|
||||
@@ -43,13 +62,20 @@ async function handler(
|
||||
const result = await fetch(`${SERVER_API_URL}/${params.url.join("/")}`, {
|
||||
method,
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
...(isRefreshHandler ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
const contentType = result.headers.get("content-type") ?? "";
|
||||
const errorBody = contentType.includes("application/json")
|
||||
? await result.json().catch(() => null)
|
||||
: await result.text().catch(() => "");
|
||||
|
||||
return NextResponse.json(
|
||||
{ message: "Invalid Credentials" },
|
||||
{ status: 401 },
|
||||
typeof errorBody === "object" && errorBody !== null
|
||||
? errorBody
|
||||
: { message: errorBody || result.statusText || "Server Error" },
|
||||
{ status: result.status },
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { POST } from "./route";
|
||||
|
||||
const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEifQ.signature";
|
||||
const fileSn = "68f53c04-36d9-4ae3-8051-3ad1603d0fc5";
|
||||
const json = (value: unknown, status = 200) => Response.json(value, { status });
|
||||
|
||||
function request(authorization?: string) {
|
||||
return new NextRequest("https://dc.invalid/api/rag-authority/category", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
...(authorization ? { Authorization: authorization } : {}),
|
||||
Cookie: `Authorization=${jwt}`,
|
||||
},
|
||||
body: JSON.stringify({ question: "서울시 물 재이용 계획", project_ids: ["root"] }),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("FLASK_API_URL", "https://rag.invalid");
|
||||
vi.stubEnv("DC_SERVICE_API_URL", "https://dc-service.invalid");
|
||||
});
|
||||
afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); });
|
||||
|
||||
describe("RAG category callback", () => {
|
||||
it("requires the RAG-forwarded JWT header even when a browser cookie is present", async () => {
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(request());
|
||||
expect(response.status).toBe(401);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns only active files from the selected leaves and never trusts caller fileSns", async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
const headers = new Headers(init?.headers);
|
||||
expect(headers.get("Authorization")).toBe(jwt);
|
||||
if (url.endsWith("/category-preflight")) {
|
||||
const body = JSON.parse(String(init?.body));
|
||||
return json(body.tree ? {
|
||||
required: true, questionSha256: "same-hash", family: "reuse",
|
||||
projectIds: ["root"], leafIds: ["leaf"], regionVerified: true,
|
||||
changeVerified: false,
|
||||
} : { required: true, questionSha256: "same-hash", family: "reuse" });
|
||||
}
|
||||
if (url.endsWith("/clsf")) return json([{ clsfSystmSn: "root", clsfSystmNm: "물 재이용" }]);
|
||||
if (url.includes("clsfSystmSn=leaf")) return json([
|
||||
{ fileSn, useYn: "Y" }, { fileSn: "11111111-1111-4111-8111-111111111111", useYn: "N" },
|
||||
]);
|
||||
throw new Error("unexpected URL");
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const submitted = new NextRequest("https://dc.invalid/api/rag-authority/category", {
|
||||
method: "POST", headers: { Authorization: `Bearer ${jwt}` },
|
||||
body: JSON.stringify({ question: "서울시 물 재이용 계획", project_ids: ["root"], fileSns: ["forged"] }),
|
||||
});
|
||||
const response = await POST(submitted);
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({
|
||||
required: true, questionSha256: "same-hash", family: "reuse",
|
||||
projectIds: ["root"], fileSns: [fileSn], regionVerified: true,
|
||||
changeVerified: false,
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("fails closed when dc-service rejects the forwarded JWT", async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => String(input).endsWith("/category-preflight")
|
||||
? json({ required: true, questionSha256: "hash", family: "basic" })
|
||||
: new Response(null, { status: 401 }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(request(`Bearer ${jwt}`));
|
||||
expect(response.status).toBe(401);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("returns a no-category preflight without making a trusted registry claim", async () => {
|
||||
const fetchMock = vi.fn(async () => json({ required: false, questionSha256: "hash", family: null }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await POST(request(`Bearer ${jwt}`));
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ required: false, questionSha256: "hash", family: null });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
CategoryScopePreparationError,
|
||||
prepareCategoryScope,
|
||||
} from "@/server/category-scope-attestation";
|
||||
import { FileRegistryError, registryAuthHeaders } from "@/server/file-registry-attestation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 60;
|
||||
|
||||
function failure(status: number, code: string): NextResponse {
|
||||
return NextResponse.json({ code }, {
|
||||
status, headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve a question's category from freshly read dc-service rows. */
|
||||
export async function POST(request: NextRequest): Promise<NextResponse> {
|
||||
try {
|
||||
if (Number(request.headers.get("content-length") ?? 0) > 16_384) {
|
||||
return failure(413, "CATEGORY_AUTHORITY_REQUEST_TOO_LARGE");
|
||||
}
|
||||
const body: unknown = await request.json();
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
||||
return failure(400, "CATEGORY_AUTHORITY_REQUEST_INVALID");
|
||||
}
|
||||
const headers = registryAuthHeaders(request, { requireHeader: true });
|
||||
const selection = await prepareCategoryScope(
|
||||
body as Record<string, unknown>, headers, request.signal,
|
||||
);
|
||||
return NextResponse.json(selection, { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError || error instanceof CategoryScopePreparationError) {
|
||||
return failure(error.status, error.code);
|
||||
}
|
||||
if (error instanceof SyntaxError) return failure(400, "CATEGORY_AUTHORITY_REQUEST_INVALID");
|
||||
if (request.signal.aborted) return failure(504, "CATEGORY_AUTHORITY_TIMEOUT");
|
||||
return failure(502, "CATEGORY_AUTHORITY_UNAVAILABLE");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/shared/config", () => ({ CLAIM_NAME: "custom-auth-cookie", AUTH_USER_ID: "token-id" }));
|
||||
|
||||
import { POST as fileAuthorityPOST } from "./route";
|
||||
import { POST as embedPOST } from "../../flask-service/embed-documents/jobs/route";
|
||||
|
||||
const validJwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEifQ.signature";
|
||||
const forgedJwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmb3JnZWQifQ.signature";
|
||||
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" }],
|
||||
}];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("DC_SERVICE_API_URL", "https://dc-service.invalid");
|
||||
vi.stubEnv("FLASK_API_URL", "https://dc-rag.invalid");
|
||||
});
|
||||
afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); });
|
||||
|
||||
describe("fixed Authorization protocol with a configurable browser cookie", () => {
|
||||
it("uses callback Authorization and ignores a contradictory cookie", async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe(validJwt);
|
||||
return Response.json(String(input).endsWith("/clsf") ? categories : [file]);
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await fileAuthorityPOST(new NextRequest("https://dc.invalid/api/rag-authority/file", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${validJwt}`,
|
||||
Cookie: `custom-auth-cookie=${forgedJwt}`,
|
||||
},
|
||||
body: JSON.stringify({ fileSn: "file-1" }),
|
||||
}));
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not treat an anonymous dc-service response as proof for a forged JWT", async () => {
|
||||
const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
// A real dc-service authentication filter rejects an invalid Authorization JWT.
|
||||
// It would return public data if this exact header were accidentally omitted.
|
||||
return new Headers(init?.headers).get("Authorization") === forgedJwt
|
||||
? Response.json({ error: "invalid token" }, { status: 401 })
|
||||
: Response.json([file]);
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await fileAuthorityPOST(new NextRequest("https://dc.invalid/api/rag-authority/file", {
|
||||
method: "POST", headers: { Authorization: `Bearer ${forgedJwt}` },
|
||||
body: JSON.stringify({ fileSn: "file-1" }),
|
||||
}));
|
||||
expect(response.status).toBe(401);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reads the configured browser cookie but forwards its token as Authorization", async () => {
|
||||
const form = new FormData();
|
||||
form.set("file_sn", "file-1");
|
||||
form.set("project_id", "root-1");
|
||||
form.set("clsf_systm_sn", "leaf-1");
|
||||
form.set("pdf_path", "./output_pdf/file-1.pdf");
|
||||
form.set("original_filename", "자료.pdf");
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe(validJwt);
|
||||
const url = String(input);
|
||||
if (url.includes("/fileprcs")) return Response.json([file]);
|
||||
if (url.endsWith("/clsf")) return Response.json(categories);
|
||||
return Response.json({
|
||||
job_id: "123e4567-e89b-42d3-a456-426614174000",
|
||||
completion_attestation: "opaque-rag-capability-with-more-than-32-characters",
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const response = await embedPOST(new NextRequest("https://dc.invalid/api/flask-service/embed-documents/jobs", {
|
||||
method: "POST", headers: { Cookie: `custom-auth-cookie=${validJwt}` }, body: form,
|
||||
}));
|
||||
expect(response.status).toBe(200);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { attestRegisteredFile, FileRegistryError } from "@/server/file-registry-attestation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function failure(status: number, code: string): NextResponse {
|
||||
return NextResponse.json({ code }, {
|
||||
status, headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
function field(value: unknown): string {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
/** Return only registry fields re-read with the caller's dc-service JWT. */
|
||||
export async function POST(request: NextRequest): Promise<NextResponse> {
|
||||
try {
|
||||
if (Number(request.headers.get("content-length") ?? 0) > 4096) {
|
||||
return failure(413, "FILE_AUTHORITY_REQUEST_TOO_LARGE");
|
||||
}
|
||||
const body: unknown = await request.json();
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
||||
return failure(400, "FILE_AUTHORITY_REQUEST_INVALID");
|
||||
}
|
||||
const input = body as Record<string, unknown>;
|
||||
const fileSn = field(input.fileSn);
|
||||
const projectId = field(input.projectId);
|
||||
const clsfSystmSn = field(input.clsfSystmSn);
|
||||
if (!fileSn) return failure(400, "FILE_AUTHORITY_REQUEST_INVALID");
|
||||
const record = await attestRegisteredFile(request, { fileSn, projectId, clsfSystmSn }, { requireHeader: true });
|
||||
return NextResponse.json(record, { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) return failure(error.status, error.code);
|
||||
if (error instanceof SyntaxError) return failure(400, "FILE_AUTHORITY_REQUEST_INVALID");
|
||||
return failure(502, "FILE_AUTHORITY_UNAVAILABLE");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { GET } from "./route";
|
||||
|
||||
const jwt = "fixture.user.token";
|
||||
const dcBase = "https://dc-service.invalid";
|
||||
const file = {
|
||||
fileSn: "file-1", useYn: "Y", projectId: "library", clsfSystmSn: "library",
|
||||
filePath: "./uploads/연구 & 계획.pdf", fileTitle: "연구 & 계획", fileExtn: "pdf",
|
||||
};
|
||||
const categories = [{ clsfSystmSn: "library", clsfSystmNm: "자료관" }];
|
||||
const disposition = "attachment; filename*=UTF-8''" + encodeURIComponent("연구 & 계획.pdf");
|
||||
|
||||
function request(query = "fileSn=file-1", authenticated = true) {
|
||||
return new NextRequest("https://frontend.invalid/api/registered-original?" + query, {
|
||||
headers: authenticated ? { Cookie: `Authorization=${jwt}` } : {},
|
||||
});
|
||||
}
|
||||
|
||||
const fetchMock = vi.fn<typeof fetch>();
|
||||
function registryReads(row = file) {
|
||||
fetchMock.mockResolvedValueOnce(Response.json({ data: [row] }))
|
||||
.mockResolvedValueOnce(Response.json(categories));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("NEXT_PUBLIC_DC_SERVICE_API_URL", dcBase);
|
||||
vi.stubEnv("RAG_V2_INGESTION_INTERNAL_API_KEY", "");
|
||||
vi.stubGlobal("fetch", fetchMock.mockReset());
|
||||
});
|
||||
afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); });
|
||||
|
||||
describe("registered original download", () => {
|
||||
it.each(["연구 & 계획", "연구 & 계획.pdf"])("passes the attested path and registered filename to DC for %s", async (fileTitle) => {
|
||||
registryReads({ ...file, fileTitle });
|
||||
const bytes = new Uint8Array([0, 255, 2, 66]);
|
||||
fetchMock.mockResolvedValueOnce(new Response(bytes, { headers: { "Content-Disposition": disposition } }));
|
||||
const req = request();
|
||||
const response = await GET(req);
|
||||
expect(response.status).toBe(200);
|
||||
const urls = fetchMock.mock.calls.map(([input]) => new URL(String(input)));
|
||||
expect(urls.map(url => url.origin + url.pathname)).toEqual(
|
||||
["fileprcs", "clsf", "fileDownload"].map(path => dcBase + "/dc-service/api/v1/" + path));
|
||||
expect(Object.fromEntries(urls[0]!.searchParams)).toEqual({ fileSn: file.fileSn });
|
||||
expect(Object.fromEntries(urls[2]!.searchParams)).toEqual({ filePath: file.filePath, fileName: "연구 & 계획.pdf" });
|
||||
for (const [, init] of fetchMock.mock.calls) {
|
||||
expect(init).toMatchObject({ cache: "no-store", redirect: "manual", signal: req.signal });
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe(jwt);
|
||||
}
|
||||
expect(response.headers.get("Content-Disposition")).toBe(disposition);
|
||||
expect(response.headers.get("Cache-Control")).toBe("no-store");
|
||||
expect(new Uint8Array(await response.arrayBuffer())).toEqual(bytes);
|
||||
});
|
||||
|
||||
it.each(["", "filePath=other", "fileSn=file-1&filePath=other", "fileSn=file-1&fileName=other", "fileSn=file-1&fileSn=file-2"])(
|
||||
"requires a single file ID (%s)", async query => {
|
||||
expect((await GET(request(query))).status).toBe(400);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires a browser session before registry access", async () => {
|
||||
expect((await GET(request("fileSn=file-1", false))).status).toBe(401);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([401, 403])("propagates registry authentication failure (%i) before download", async status => {
|
||||
fetchMock.mockResolvedValueOnce(new Response(null, { status }));
|
||||
const response = await GET(request());
|
||||
expect(response.status).toBe(status);
|
||||
expect(response.headers.has("Content-Disposition")).toBe(false);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ ...file, fileSn: "other" },
|
||||
{ ...file, useYn: "N" },
|
||||
{ ...file, clsfSystmSn: "other" },
|
||||
{ ...file, projectId: "other" },
|
||||
])("enforces active file and classification before download", async row => {
|
||||
registryReads(row);
|
||||
expect((await GET(request())).status).toBe(409);
|
||||
expect(fetchMock.mock.calls.some(([input]) => String(input).includes("fileDownload"))).toBe(false);
|
||||
});
|
||||
|
||||
it("declines a missing registered path without calling fileDownload", async () => {
|
||||
registryReads({ ...file, filePath: " " });
|
||||
expect((await GET(request())).status).toBe(404);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each([[200, 502], [302, 502], [401, 401], [403, 403], [404, 404], [504, 504]])(
|
||||
"does not return a gateway page or upstream error as a file (%i)", async (upstream, expected) => {
|
||||
registryReads();
|
||||
fetchMock.mockResolvedValueOnce(new Response("UPSTREAM_PRIVATE_MESSAGE", {
|
||||
status: upstream, headers: { Location: "https://login.invalid", "Content-Type": "text/html" },
|
||||
}));
|
||||
const response = await GET(request());
|
||||
expect(response.status).toBe(expected);
|
||||
expect(response.headers.get("Content-Type")).toBe("text/plain; charset=utf-8");
|
||||
expect(response.headers.has("Content-Disposition")).toBe(false);
|
||||
expect(response.headers.has("Location")).toBe(false);
|
||||
expect(await response.text()).not.toContain("UPSTREAM_PRIVATE_MESSAGE");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { FileRegistryError, registeredOriginalRequest } from "@/server/file-registry-attestation";
|
||||
import { downloadFailure, streamDcAttachment } from "@/server/dc-attachment";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: NextRequest): Promise<Response> {
|
||||
const params = request.nextUrl.searchParams;
|
||||
const fileSn = params.get("fileSn");
|
||||
if (!fileSn || params.size !== 1) return downloadFailure(400);
|
||||
try {
|
||||
const { url, headers } = await registeredOriginalRequest(request, fileSn);
|
||||
return await streamDcAttachment(url, headers, request.signal);
|
||||
} catch (error) {
|
||||
if (error instanceof FileRegistryError) return downloadFailure(error.status);
|
||||
return downloadFailure(request.signal.aborted ? 499 : 502);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user