import http from "node:http"; import { gzipSync } from "node:zlib"; import net from "node:net"; import type { AddressInfo, Socket } from "node:net"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { NextRequest } from "next/server"; vi.mock("@/shared/config", async (importOriginal) => ({ ...await importOriginal(), CLAIM_NAME: "Authorization", AUTH_USER_ID: "token-id", })); import { GET } from "./route"; import { middleware } from "../../../../../middleware"; let server: http.Server; let handle: (request: http.IncomingMessage, response: http.ServerResponse) => void; let hits: number; let connections: Set; function request(options: { signal?: AbortSignal; headers?: HeadersInit; query?: string } = {}) { return new NextRequest(`https://dc.invalid/dc-service/api/v1/data?${options.query ?? "query=%EB%AC%BC+%EC%9E%AC%EC%9D%B4%EC%9A%A9&sidoCode=11"}`, { signal: options.signal, headers: options.headers ?? { "X-Site-Id": "DC", Authorization: "header-token" }, }); } beforeEach(async () => { hits = 0; connections = new Set(); handle = (_, response) => response.end('{"data":[]}'); server = http.createServer((req, res) => { hits++; handle(req, res); }); server.on("connection", (socket) => connections.add(socket)); await new Promise((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("GENERAL_SEARCH_PROXY_TIMEOUT_MS", "2000"); vi.stubEnv("GENERAL_SEARCH_PROXY_CONNECT_TIMEOUT_MS", "1000"); }); afterEach(async () => { server.closeAllConnections(); await new Promise((resolve) => server.close(() => resolve())); vi.unstubAllEnvs(); }); describe("general search pooled gateway proxy", () => { it("bypasses middleware rewrite only for the exact GET route", () => { 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"); for (const [path, method] of [ ["/dc-service/api/v1/data", "POST"], ["/dc-service/api/v1/data", "HEAD"], ["/dc-service/api/v1/data/other", "GET"], ["/dc-service/api/v1/files", "GET"], ]) { const other = middleware(new NextRequest(`https://dc.invalid${path}?page=2`, { method })); const rewritten = new URL(other.headers.get("x-middleware-rewrite")!); expect(rewritten.pathname).toBe(path); expect(rewritten.search).toBe("?page=2"); } }); it("retains gateway path/query, request headers, cookies and cookie auth precedence", async () => { let receivedPath = ""; let receivedHeaders: http.IncomingHttpHeaders = {}; let receivedMethod = ""; const responseBody = '{ "data": [{"fileOriginalName":"물 재이용 계획.pdf"}] }'; handle = (req, res) => { receivedPath = req.url!; receivedHeaders = req.headers; receivedMethod = req.method!; res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" }); res.end(responseBody); }; const result = await GET(request({ query: "query=%EB%AC%BC+%EC%9E%AC%EC%9D%B4%EC%9A%A9&filter=one&filter=two&upstream=http%3A%2F%2Funtrusted.invalid", headers: { Cookie: "Authorization=cookie-token; token-id=cookie-user; preference=kept", Authorization: "header-token", "token-id": "header-user", "X-Site-Id": "DC", "X-Device-Id": "existing-device", "X-Request-Id": "trace-id", Connection: "close, X-Private-Hop", "X-Private-Hop": "strip-this", "Proxy-Authorization": "strip-this", Host: "untrusted.invalid", }, })); expect(result.status).toBe(200); expect(await result.text()).toBe(responseBody); expect(receivedMethod).toBe("GET"); expect(receivedPath).toBe("/dc-service/api/v1/data?query=%EB%AC%BC+%EC%9E%AC%EC%9D%B4%EC%9A%A9&filter=one&filter=two&upstream=http%3A%2F%2Funtrusted.invalid"); expect(receivedHeaders).toMatchObject({ authorization: "cookie-token", "token-id": "cookie-user", "x-site-id": "DC", cookie: "Authorization=cookie-token; token-id=cookie-user; preference=kept", "x-device-id": "existing-device", "x-request-id": "trace-id", "x-forwarded-host": "untrusted.invalid", }); expect(receivedHeaders.host).toMatch(/^127\.0\.0\.1:/); expect(receivedHeaders.connection).toBe("keep-alive"); expect(receivedHeaders["x-private-hop"]).toBeUndefined(); expect(receivedHeaders["proxy-authorization"]).toBeUndefined(); expect(result.headers.get("cache-control")).toBe("no-store"); expect(hits).toBe(1); }); it("reuses a connection while querying upstream every time and keeping user/site values isolated", async () => { handle = (req, res) => { res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "public, max-age=3600" }); res.end(JSON.stringify({ hit: hits, user: req.headers["token-id"], site: req.headers["x-site-id"] })); }; for (const [user, site] of [["user-one", "DC"], ["user-two", "OTHER"], ["user-one", "DC"]] as const) { const result = await GET(request({ headers: { Cookie: `token-id=${user}`, "X-Site-Id": site } })); expect(await result.json()).toEqual({ hit: hits, user, site }); expect(result.headers.get("cache-control")).toBe("no-store"); } expect(hits).toBe(3); expect(connections.size).toBe(1); }); it("keeps authentication, tenant and query independent during overlapping requests", async () => { handle = (req, res) => { const value = { user: req.headers["token-id"], site: req.headers["x-site-id"], query: req.url }; setTimeout(() => { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(value)); }, req.headers["x-site-id"] === "DC" ? 10 : 1); }; const values = Array.from({ length: 8 }, (_, index) => ({ user: `concurrent-user-${index}`, site: index % 2 ? "OTHER" : "DC", query: `query=term-${index}`, })); await Promise.all(values.map(async ({ user, site, query }) => { const result = await GET(request({ query, headers: { Cookie: `token-id=${user}`, "X-Site-Id": site } })); expect(await result.json()).toEqual({ user, site, query: `/dc-service/api/v1/data?${query}` }); })); expect(hits).toBe(8); }); it.each([401, 403, 429, 500, 502, 503])("preserves upstream %i with body/challenge/retry headers and no retry", async (status) => { const body = '{"detail":"upstream failure"}'; handle = (_, res) => { res.writeHead(status, { "Content-Type": "application/json", "Retry-After": "7", "WWW-Authenticate": 'Bearer realm="gateway"', "Set-Cookie": ["first=one; Path=/", "second=two; Path=/"], Connection: "keep-alive, X-Upstream-Hop", "X-Upstream-Hop": "must-not-forward", }); res.end(body); }; const result = await GET(request()); expect(result.status).toBe(status); expect(await result.text()).toBe(body); expect(result.headers.get("retry-after")).toBe("7"); expect(result.headers.get("www-authenticate")).toBe('Bearer realm="gateway"'); expect(result.headers.get("set-cookie")).toContain("first=one; Path=/"); expect(result.headers.get("set-cookie")).toContain("second=two; Path=/"); expect(result.headers.getSetCookie()).toEqual(["first=one; Path=/", "second=two; Path=/"]); expect(result.headers.get("connection")).toBeNull(); expect(result.headers.get("x-upstream-hop")).toBeNull(); expect(hits).toBe(1); }); it("preserves redirect status/location without following another target", async () => { handle = (_, res) => { res.writeHead(302, { Location: "http://untrusted.invalid/login" }); res.end("redirect"); }; const result = await GET(request()); expect(result.status).toBe(302); expect(result.headers.get("location")).toBe("http://untrusted.invalid/login"); expect(await result.text()).toBe("redirect"); expect(hits).toBe(1); }); it("preserves compressed response bytes and representation headers", async () => { const body = gzipSync(Buffer.from('{"data":["압축 응답"]}')); handle = (_, res) => { res.writeHead(200, { "Content-Type": "application/json", "Content-Encoding": "gzip", "Content-Length": body.byteLength }); res.end(body); }; const result = await GET(request()); expect(result.headers.get("content-encoding")).toBe("gzip"); expect(result.headers.get("content-length")).toBe(String(body.byteLength)); expect(Buffer.from(await result.arrayBuffer())).toEqual(body); }); it("keeps the response deadline active until the whole body arrives", async () => { vi.stubEnv("GENERAL_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 GET(request()); expect(result.status).toBe(504); expect((await result.json()).detail.code).toBe("GENERAL_SEARCH_TIMEOUT"); await vi.waitFor(() => expect(closed).toBe(true)); expect(hits).toBe(1); }); it("applies the connection deadline to a stalled TLS handshake", async () => { let stalledSocket: Socket | undefined; const stalledServer = net.createServer((socket) => { stalledSocket = socket; socket.resume(); }); await new Promise((resolve) => stalledServer.listen(0, "127.0.0.1", resolve)); vi.stubEnv("NEXT_PUBLIC_DC_SERVICE_API_URL", `https://127.0.0.1:${(stalledServer.address() as AddressInfo).port}`); vi.stubEnv("GENERAL_SEARCH_PROXY_CONNECT_TIMEOUT_MS", "50"); try { const result = await GET(request()); expect(result.status).toBe(504); expect((await result.json()).detail.code).toBe("GENERAL_SEARCH_TIMEOUT"); await vi.waitFor(() => expect(stalledSocket?.destroyed).toBe(true)); expect(hits).toBe(0); } finally { stalledSocket?.destroy(); await new Promise((resolve) => stalledServer.close(() => resolve())); } }); it("returns sanitized 502 for an upstream disconnect without a retry", async () => { const log = vi.spyOn(console, "warn").mockImplementation(() => {}); handle = (req) => req.socket.destroy(); const result = await GET(request()); expect(result.status).toBe(502); expect((await result.json()).detail.code).toBe("GENERAL_SEARCH_UPSTREAM_UNAVAILABLE"); expect(log).toHaveBeenCalledWith("[general-search] upstream_connection_failed", { status: 502 }); expect(hits).toBe(1); }); it("cancels the open upstream when the caller aborts", async () => { const controller = new AbortController(); let closed = false; let started!: () => void; const ready = new Promise((resolve) => { started = resolve; }); handle = (_, res) => { res.on("close", () => { closed = true; }); started(); }; const pending = GET(request({ signal: controller.signal })); await ready; controller.abort(); expect((await pending).status).toBe(499); await vi.waitFor(() => expect(closed).toBe(true)); expect(hits).toBe(1); }); it("does not call the upstream for an already cancelled request", async () => { const controller = new AbortController(); controller.abort(); expect((await GET(request({ signal: controller.signal }))).status).toBe(499); expect(hits).toBe(0); }); it("rejects a credential-bearing upstream setting without exposing it or connecting", async () => { vi.stubEnv("NEXT_PUBLIC_DC_SERVICE_API_URL", "https://user:secret@untrusted.invalid"); const result = await GET(request()); expect(result.status).toBe(502); expect((await result.json()).detail.code).toBe("GENERAL_SEARCH_UPSTREAM_CONFIG"); expect(hits).toBe(0); }); });