diff --git a/apps/dc/app/api/proxy/[...url]/route.test.ts b/apps/dc/app/api/proxy/[...url]/route.test.ts index fb4bc8681..6a9ff7fed 100644 --- a/apps/dc/app/api/proxy/[...url]/route.test.ts +++ b/apps/dc/app/api/proxy/[...url]/route.test.ts @@ -116,6 +116,39 @@ describe("DC login API proxy", () => { expect(cookieSet).toHaveBeenCalledWith("refresh-token", "refresh-token-value", { httpOnly: true, sameSite: "lax", path: "/" }); }); + it("forwards the ingress IP, device and refresh cookie to the user service on PUT", async () => { + cookieGet.mockReturnValue({ value: "fixture-refresh" }); + const upstream = vi.fn().mockResolvedValue(new Response(null, { + headers: { "access-token": "fixture-renewed", "token-id": "fixture-user" }, + })); + vi.stubGlobal("fetch", upstream); + const { PUT } = await import("./route"); + const url = ["user-service", "api", "v1", "users", "token", "refresh"]; + const response = await PUT(new Request(`https://frontend.example/api/proxy/${url.join("/")}`, { + method: "PUT", + headers: { + "X-Real-IP": "2001:db8::25", + "X-Client-IP": "192.0.2.99", + "X-Device-Id": "fixture-device", + }, + }), { params: Promise.resolve({ url }) }); + + expect(cookieGet).toHaveBeenCalledWith("refresh-token"); + expect(upstream).toHaveBeenCalledOnce(); + expect(upstream).toHaveBeenCalledWith( + "https://backend.example/user-service/api/v1/users/token/refresh", + expect.objectContaining({ method: "PUT" }), + ); + const options = upstream.mock.calls[0]?.[1]; + const headers = new Headers(options?.headers); + expect(headers.get("x-client-ip")).toBe("2001:db8::25"); + expect(headers.get("x-device-id")).toBe("fixture-device"); + expect(headers.get("authorization")).toBe("fixture-refresh"); + expect(options?.body).toBeUndefined(); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ "access-token": "fixture-renewed", "token-id": "fixture-user" }); + }); + it("omits absent device and ingress identity headers, even if a client IP was supplied", async () => { const fetchMock = vi.fn().mockResolvedValue( new Response(null, { diff --git a/apps/dc/next.config.ts b/apps/dc/next.config.ts index e5006cb03..a2639771e 100644 --- a/apps/dc/next.config.ts +++ b/apps/dc/next.config.ts @@ -4,6 +4,9 @@ const subDomain = process.env.NEXT_PUBLIC_SUB_DOMAIN || "http://localhost:13000"; const nextConfig: NextConfig = { + experimental: { + proxyTimeout: 600000, + }, //output: "standalone", async headers() { return [ diff --git a/apps/dc/src/entities/auth/lib/auth-wrapper.test.tsx b/apps/dc/src/entities/auth/lib/auth-wrapper.test.tsx new file mode 100644 index 000000000..b50067656 --- /dev/null +++ b/apps/dc/src/entities/auth/lib/auth-wrapper.test.tsx @@ -0,0 +1,160 @@ +import { StrictMode } from "react"; +import { act, render, screen } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { AuthWrapper } from "./auth-wrapper"; + +const fixture = vi.hoisted(() => ({ + get: vi.fn(), + getUserId: vi.fn(), + setUserInfo: vi.fn(), + refresh: vi.fn(), + schedule: vi.fn(), + router: { replace: vi.fn() }, + target: "/auth/login", +})); +vi.mock("next/navigation", () => ({ + usePathname: () => window.location.pathname, + useRouter: () => fixture.router, +})); +vi.mock("@/shared/api", () => ({ client: { get: fixture.get } })); +vi.mock("@/shared/lib", () => ({ + useUserStore: (select: (state: object) => unknown) => + select({ userInfo: null, setUserInfo: fixture.setUserInfo }), +})); +vi.mock("@/shared/config", () => ({ + ENDPOINT: { USER_SERVICE: { USERS: "/users" } }, + get AUTH_LOGIN_REDIRECT_URL() { return fixture.target; }, +})); +vi.mock("../api/login-service", () => ({ + LoginApi: { + silentRefresh: fixture.refresh, + setupSilentRefreshTimer: fixture.schedule, + }, +})); +vi.mock("./token-manager", () => ({ + tokenManager: { getUserId: fixture.getUserId }, +})); + +const user = { userId: "user-1" }; +const content = () => ( + 자료관 +); + +function visit(path: string) { + const location = Object.assign(new URL(path, "https://dc.example"), { assign: vi.fn() }); + vi.stubGlobal("window", Object.create(window, { location: { value: location } })); + return location; +} + +async function settle() { + await act(async () => {}); +} + +describe("AuthWrapper", () => { + beforeEach(() => { + vi.resetAllMocks(); + fixture.target = "/auth/login"; + fixture.getUserId.mockReturnValue("user-1"); + fixture.get.mockResolvedValue({ data: user }); + }); + + it.each([ + ["/auth/login", "https://sso.example/login"], + ["/auth/login/", "https://sso.example/login"], + ["/custom/login?next=/files", "https://dc.example/custom/login"], + ])("keeps the login form available at %s without probing or refreshing", async (path, target) => { + fixture.target = target; + const location = visit(path); + render(content()); + await settle(); + window.dispatchEvent(new Event("auth:logout")); + expect(screen.getByText("자료관")).toBeInTheDocument(); + expect(fixture.get).not.toHaveBeenCalled(); + expect(fixture.refresh).not.toHaveBeenCalled(); + expect(fixture.schedule).not.toHaveBeenCalled(); + expect(location.assign).not.toHaveBeenCalled(); + }); + + it("initializes after leaving login and keeps the session across protected pages", async () => { + const location = visit("/auth/login"); + const view = render(content()); + await settle(); + location.pathname = "/generalsearch"; + view.rerender(content()); + await settle(); + location.pathname = "/datatreesearch"; + view.rerender(content()); + await settle(); + expect(fixture.get.mock.calls).toEqual([["/users/info/me"]]); + expect(fixture.setUserInfo.mock.calls).toEqual([[user]]); + expect(fixture.schedule).toHaveBeenCalledTimes(1); + expect(fixture.refresh).not.toHaveBeenCalled(); + }); + + it("recovers once after an initial 401 and reads the user again", async () => { + const location = visit("/generalsearch"); + fixture.get.mockRejectedValueOnce({ response: { status: 401 } }); + fixture.refresh.mockResolvedValueOnce(undefined); + render(content()); + await settle(); + expect(fixture.get.mock.calls).toEqual([["/users/info/me"], ["/users/info/me"]]); + expect(fixture.refresh).toHaveBeenCalledTimes(1); + expect(fixture.setUserInfo.mock.calls).toEqual([[user]]); + // LoginApi sets the timer when silentRefresh succeeds. + expect(fixture.schedule).not.toHaveBeenCalled(); + expect(location.assign).not.toHaveBeenCalled(); + }); + + it("redirects only once when refresh dispatches logout and rejects", async () => { + fixture.target = "https://sso.example/login"; + const location = visit("/generalsearch"); + fixture.get.mockRejectedValueOnce({ status: 401 }); + fixture.refresh.mockImplementationOnce(async () => { + window.dispatchEvent(new Event("auth:logout")); + throw new Error("session expired"); + }); + render(content()); + await settle(); + expect(fixture.refresh).toHaveBeenCalledTimes(1); + expect(fixture.get).toHaveBeenCalledTimes(1); + expect(fixture.setUserInfo.mock.calls).toEqual([[null]]); + expect(location.assign.mock.calls).toEqual([[fixture.target]]); + }); + + it.each([403, 503])("does not refresh or redirect on an initial %i", async (status) => { + const location = visit("/generalsearch"); + fixture.get.mockRejectedValueOnce({ response: { status } }); + render(content()); + await settle(); + expect(fixture.get).toHaveBeenCalledTimes(1); + expect(fixture.refresh).not.toHaveBeenCalled(); + expect(fixture.setUserInfo).not.toHaveBeenCalled(); + expect(location.assign).not.toHaveBeenCalled(); + }); + + it("returns to the default login once on session expiry", async () => { + const location = visit("/generalsearch"); + render(content()); + await settle(); + window.dispatchEvent(new Event("auth:logout")); + window.dispatchEvent(new Event("auth:logout")); + expect(location.assign.mock.calls).toEqual([["/auth/login"]]); + expect(fixture.setUserInfo.mock.calls).toEqual([[user], [null]]); + }); + + it("ignores an old check that fails after moving back to login", async () => { + const location = visit("/generalsearch"); + let reject!: (error: unknown) => void; + fixture.get.mockImplementationOnce(() => new Promise((_, fail) => { reject = fail; })); + const view = render(content()); + await settle(); + location.pathname = "/auth/login"; + view.rerender(content()); + await act(async () => { reject({ status: 401 }); }); + expect(fixture.get).toHaveBeenCalledTimes(1); + expect(fixture.refresh).not.toHaveBeenCalled(); + expect(fixture.schedule).not.toHaveBeenCalled(); + expect(fixture.setUserInfo).not.toHaveBeenCalled(); + expect(location.assign).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/dc/src/entities/auth/lib/auth-wrapper.tsx b/apps/dc/src/entities/auth/lib/auth-wrapper.tsx index a20be4c36..9c4a6c4d7 100644 --- a/apps/dc/src/entities/auth/lib/auth-wrapper.tsx +++ b/apps/dc/src/entities/auth/lib/auth-wrapper.tsx @@ -1,11 +1,12 @@ "use client"; -import { useEffect } from "react"; -import { useRouter } from "next/navigation"; +import { useEffect, useRef } from "react"; +import { usePathname } from "next/navigation"; +import { isAtLoginRedirectUrl } from "@common/network"; import { client } from "@/shared/api"; import type { IUserInfo } from "@/shared/store"; import { useUserStore } from "@/shared/lib"; -import { ENDPOINT } from "@/shared/config"; +import { AUTH_LOGIN_REDIRECT_URL, ENDPOINT } from "@/shared/config"; import { LoginApi } from "../api/login-service"; import { tokenManager } from "./token-manager"; @@ -20,56 +21,66 @@ function getErrorStatus(error: unknown): number | undefined { } const AuthWrapper = ({ children }: { children: React.ReactNode }) => { - const router = useRouter(); + const pathname = usePathname(); + const onLoginPage = + pathname === "/auth/login" || + pathname === "/auth/login/" || + isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL); const { userInfo, setUserInfo } = useUserStore((state) => state); - - async function authCheck() { - const userId = tokenManager.getUserId(); - if (!userId) { - throw new Error("Missing required authentication tokens"); - } - - const response = await client.get( - `${ENDPOINT.USER_SERVICE.USERS}/info/me`, - ); - if (!userInfo) setUserInfo(response.data); - } + const currentUser = useRef(userInfo); useEffect(() => { - const handleAuthLogout = () => { - setUserInfo(null); - router.replace("/auth/login"); - }; + currentUser.current = userInfo; + }, [userInfo]); - (async () => { + useEffect(() => { + if (onLoginPage) return; + let active = true; + let redirecting = false; + const canContinue = () => active && !redirecting; + const handleAuthLogout = () => { + if (!canContinue()) return; + redirecting = true; + setUserInfo(null); + window.location.assign(AUTH_LOGIN_REDIRECT_URL); + }; + async function loadUser() { + if (!tokenManager.getUserId()) { + throw new Error("Missing required authentication tokens"); + } + const response = await client.get( + `${ENDPOINT.USER_SERVICE.USERS}/info/me`, + ); + if (canContinue() && !currentUser.current) setUserInfo(response.data); + } + async function initialize() { + if (!canContinue()) return; try { - await authCheck(); - LoginApi.setupSilentRefreshTimer(); + await loadUser(); + if (canContinue()) LoginApi.setupSilentRefreshTimer(); } catch (error) { + if (!canContinue()) return; console.error(error); const status = getErrorStatus(error); - - if (status && status !== 401) { - return; - } + if (status && status !== 401) return; try { await LoginApi.silentRefresh(); - await authCheck(); + if (canContinue()) await loadUser(); } catch (refreshError) { + if (!active) return; console.error("Token refresh failed:", refreshError); - setUserInfo(null); - router.replace("/auth/login"); + handleAuthLogout(); } } - })(); - + } window.addEventListener("auth:logout", handleAuthLogout); - + void Promise.resolve().then(initialize); return () => { + active = false; window.removeEventListener("auth:logout", handleAuthLogout); }; - }, []); + }, [onLoginPage, setUserInfo]); return <>{children}; }; diff --git a/apps/dc/src/pages/auth/login/ui/login-page.tsx b/apps/dc/src/pages/auth/login/ui/login-page.tsx index 58fe4ba76..5eb5a0d2c 100644 --- a/apps/dc/src/pages/auth/login/ui/login-page.tsx +++ b/apps/dc/src/pages/auth/login/ui/login-page.tsx @@ -10,7 +10,7 @@ function LoginPage() { const submitting = useRef(false); const [status, setStatus] = useState<"idle" | "pending" | "error">("idle"); - const handleSubmit = async (e: React.FormEvent) => { + const handleSubmit = async (e: React.SubmitEvent) => { e.preventDefault(); if (submitting.current) return; diff --git a/apps/dc/src/pages/chatbot/ui/chatbot-page.tsx b/apps/dc/src/pages/chatbot/ui/chatbot-page.tsx index 1023227e7..b5a574f73 100644 --- a/apps/dc/src/pages/chatbot/ui/chatbot-page.tsx +++ b/apps/dc/src/pages/chatbot/ui/chatbot-page.tsx @@ -1055,7 +1055,7 @@ function ChatBotPage() { }); }; - const handleSubmit = (e: React.FormEvent) => { + const handleSubmit = (e: React.SubmitEvent) => { e.preventDefault(); if (!archiveReady || !scopeReady || !input.trim() || loading || abortControllerRef.current || archiveDeleteRef.current?.id === archiveSessionRef.current) return; diff --git a/apps/dc/src/server/dc-middleware-proxy-host.test.ts b/apps/dc/src/server/dc-middleware-proxy-host.test.ts index 8ef4bf09c..fcaa98730 100644 --- a/apps/dc/src/server/dc-middleware-proxy-host.test.ts +++ b/apps/dc/src/server/dc-middleware-proxy-host.test.ts @@ -36,21 +36,42 @@ describe("DC middleware through the actual Next.js HTTP proxy", () => { expect(response.headers.get("x-middleware-rewrite")).toBe(`${expected}/user-service/api/v1/users/info/me?test=1`); }); - const ipCases: { method: string; ingress: Record; expectedIp?: string }[] = [ + const classificationPath = "/dc-service/api/v1/clsf?clsfSystmNm=test"; + const ipCases: { + method: string; ingress: Record; expectedIp?: string; + path?: string; expectedPath?: string; body?: string; + }[] = [ { method: "GET", ingress: { "X-Forwarded-For": "::ffff:192.0.2.12, 192.0.2.13", "X-Real-IP": "192.0.2.14" }, expectedIp: "192.0.2.12" }, { method: "HEAD", ingress: { "X-Real-IP": "2001:db8::7" }, expectedIp: "2001:db8::7" }, { method: "GET", ingress: {} }, + { + method: "POST", + path: "/server/cms-service/api/v1/cntnlog", + expectedPath: "/cms-service/api/v1/cntnlog", + body: JSON.stringify({ cntnId: "fixture-user", siteId: "DC", menuCd: 7, urlPath: "/generalsearch" }), + ingress: { "X-Forwarded-For": "192.0.2.30, 192.0.2.31" }, + expectedIp: "192.0.2.30", + }, ]; - it.each(ipCases)("preserves the destination, auth and ingress IP for $method ($expectedIp)", async ({ method, ingress, expectedIp }) => { + it.each(ipCases)("preserves the destination, auth and ingress IP for $method ($expectedIp)", async ({ + method, ingress, expectedIp, path = classificationPath, expectedPath = classificationPath, body, + }) => { let upstreamHeaders: Record = {}; let upstreamPath = ""; - const upstream = await listen(createServer((req, res) => { + let upstreamMethod: string | undefined; + let upstreamBody = ""; + const upstream = await listen(createServer(async (req, res) => { + upstreamMethod = req.method; + for await (const chunk of req) upstreamBody += chunk.toString(); upstreamHeaders = req.headers; upstreamPath = req.url ?? ""; res.statusCode = 200; res.end(); })); vi.stubEnv("NEXT_PUBLIC_DC_SERVICE_API_URL", upstream); + vi.stubEnv("SERVER_API_URL", upstream); + vi.resetModules(); + const { middleware: gatewayMiddleware } = await import("../../middleware"); const frontend = await listen(createServer(async (req, res) => { try { const incomingHeaders = new Headers(); @@ -59,7 +80,7 @@ describe("DC middleware through the actual Next.js HTTP proxy", () => { incomingHeaders.append(name, part); } } - const rewrite = middleware(new NextRequest(`https://frontend.invalid${req.url}`, { + const rewrite = gatewayMiddleware(new NextRequest(`https://frontend.invalid${req.url}`, { method: req.method, headers: incomingHeaders, })); @@ -75,12 +96,13 @@ describe("DC middleware through the actual Next.js HTTP proxy", () => { } })); const status = await new Promise((resolve, reject) => { - const req = request(`${frontend}/dc-service/api/v1/clsf?clsfSystmNm=test`, { + const req = request(`${frontend}${path}`, { method, headers: { Host: "frontend.invalid", Cookie: "Authorization=fixture-token; token-id=fixture-user", "X-Site-Id": "DC", + ...(body ? { "Content-Type": "application/json" } : {}), "X-Forwarded-Proto": "https", "X-Forwarded-Port": "443", "X-Client-IP": "192.0.2.99", @@ -92,11 +114,13 @@ describe("DC middleware through the actual Next.js HTTP proxy", () => { }); req.setTimeout(5000, () => req.destroy(new Error("local proxy test timed out"))); req.on("error", reject); - req.end(); + req.end(body); }); expect(status).toBe(200); - expect(upstreamPath).toBe("/dc-service/api/v1/clsf?clsfSystmNm=test"); + expect(upstreamPath).toBe(expectedPath); + expect(upstreamMethod).toBe(method); + expect(upstreamBody).toBe(body ?? ""); expect(upstreamHeaders["x-forwarded-host"]).toBe("frontend.invalid"); expect(upstreamHeaders.host).toBe(new URL(upstream).host); expect(upstreamHeaders.authorization).toBe("fixture-token"); diff --git a/apps/dc/src/shared/config/env.ts b/apps/dc/src/shared/config/env.ts index bd8c7a8ab..a73533952 100644 --- a/apps/dc/src/shared/config/env.ts +++ b/apps/dc/src/shared/config/env.ts @@ -18,4 +18,6 @@ export const ACCESS_TOKEN = export const REFRESH_TOKEN = process.env.NEXT_PUBLIC_REFRESH_TOKEN || "refresh-token"; export const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id"; +export const AUTH_LOGIN_REDIRECT_URL = + process.env.NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL || "/auth/login"; export const COOKIE_DOMAIN = process.env.NEXT_PUBLIC_COOKIE_DOMAIN;