Files
frontend/apps/dc/app/api/conversation-memory/route.test.ts
T

484 lines
28 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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/);
});
});