자료관 로그인 복귀 및 원앤올 프록시 대기시간 반영

This commit is contained in:
2026-12-05 11:18:07 +09:00
parent 3ef863e329
commit cb1b4c19fe
8 changed files with 276 additions and 43 deletions
@@ -116,6 +116,39 @@ describe("DC login API proxy", () => {
expect(cookieSet).toHaveBeenCalledWith("refresh-token", "refresh-token-value", { httpOnly: true, sameSite: "lax", path: "/" }); 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<typeof fetch>().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 () => { it("omits absent device and ingress identity headers, even if a client IP was supplied", async () => {
const fetchMock = vi.fn().mockResolvedValue( const fetchMock = vi.fn().mockResolvedValue(
new Response(null, { new Response(null, {
+3
View File
@@ -4,6 +4,9 @@ const subDomain =
process.env.NEXT_PUBLIC_SUB_DOMAIN || "http://localhost:13000"; process.env.NEXT_PUBLIC_SUB_DOMAIN || "http://localhost:13000";
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
experimental: {
proxyTimeout: 600000,
},
//output: "standalone", //output: "standalone",
async headers() { async headers() {
return [ return [
@@ -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 = () => (
<StrictMode><AuthWrapper>자료관</AuthWrapper></StrictMode>
);
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();
});
});
+45 -34
View File
@@ -1,11 +1,12 @@
"use client"; "use client";
import { useEffect } from "react"; import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation"; import { usePathname } from "next/navigation";
import { isAtLoginRedirectUrl } from "@common/network";
import { client } from "@/shared/api"; import { client } from "@/shared/api";
import type { IUserInfo } from "@/shared/store"; import type { IUserInfo } from "@/shared/store";
import { useUserStore } from "@/shared/lib"; 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 { LoginApi } from "../api/login-service";
import { tokenManager } from "./token-manager"; import { tokenManager } from "./token-manager";
@@ -20,56 +21,66 @@ function getErrorStatus(error: unknown): number | undefined {
} }
const AuthWrapper = ({ children }: { children: React.ReactNode }) => { 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); const { userInfo, setUserInfo } = useUserStore((state) => state);
const currentUser = useRef(userInfo);
async function authCheck() {
const userId = tokenManager.getUserId();
if (!userId) {
throw new Error("Missing required authentication tokens");
}
const response = await client.get<IUserInfo>(
`${ENDPOINT.USER_SERVICE.USERS}/info/me`,
);
if (!userInfo) setUserInfo(response.data);
}
useEffect(() => { useEffect(() => {
const handleAuthLogout = () => { currentUser.current = userInfo;
setUserInfo(null); }, [userInfo]);
router.replace("/auth/login");
};
(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<IUserInfo>(
`${ENDPOINT.USER_SERVICE.USERS}/info/me`,
);
if (canContinue() && !currentUser.current) setUserInfo(response.data);
}
async function initialize() {
if (!canContinue()) return;
try { try {
await authCheck(); await loadUser();
LoginApi.setupSilentRefreshTimer(); if (canContinue()) LoginApi.setupSilentRefreshTimer();
} catch (error) { } catch (error) {
if (!canContinue()) return;
console.error(error); console.error(error);
const status = getErrorStatus(error); const status = getErrorStatus(error);
if (status && status !== 401) return;
if (status && status !== 401) {
return;
}
try { try {
await LoginApi.silentRefresh(); await LoginApi.silentRefresh();
await authCheck(); if (canContinue()) await loadUser();
} catch (refreshError) { } catch (refreshError) {
if (!active) return;
console.error("Token refresh failed:", refreshError); console.error("Token refresh failed:", refreshError);
setUserInfo(null); handleAuthLogout();
router.replace("/auth/login");
} }
} }
})(); }
window.addEventListener("auth:logout", handleAuthLogout); window.addEventListener("auth:logout", handleAuthLogout);
void Promise.resolve().then(initialize);
return () => { return () => {
active = false;
window.removeEventListener("auth:logout", handleAuthLogout); window.removeEventListener("auth:logout", handleAuthLogout);
}; };
}, []); }, [onLoginPage, setUserInfo]);
return <>{children}</>; return <>{children}</>;
}; };
@@ -10,7 +10,7 @@ function LoginPage() {
const submitting = useRef(false); const submitting = useRef(false);
const [status, setStatus] = useState<"idle" | "pending" | "error">("idle"); const [status, setStatus] = useState<"idle" | "pending" | "error">("idle");
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { const handleSubmit = async (e: React.SubmitEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
if (submitting.current) return; if (submitting.current) return;
@@ -1055,7 +1055,7 @@ function ChatBotPage() {
}); });
}; };
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { const handleSubmit = (e: React.SubmitEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
if (!archiveReady || !scopeReady || !input.trim() || loading || abortControllerRef.current || archiveDeleteRef.current?.id === archiveSessionRef.current) return; if (!archiveReady || !scopeReady || !input.trim() || loading || abortControllerRef.current || archiveDeleteRef.current?.id === archiveSessionRef.current) return;
@@ -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`); expect(response.headers.get("x-middleware-rewrite")).toBe(`${expected}/user-service/api/v1/users/info/me?test=1`);
}); });
const ipCases: { method: string; ingress: Record<string, string>; expectedIp?: string }[] = [ const classificationPath = "/dc-service/api/v1/clsf?clsfSystmNm=test";
const ipCases: {
method: string; ingress: Record<string, string>; 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: "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: "HEAD", ingress: { "X-Real-IP": "2001:db8::7" }, expectedIp: "2001:db8::7" },
{ method: "GET", ingress: {} }, { 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<string, string | string[] | undefined> = {}; let upstreamHeaders: Record<string, string | string[] | undefined> = {};
let upstreamPath = ""; 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; upstreamHeaders = req.headers;
upstreamPath = req.url ?? ""; upstreamPath = req.url ?? "";
res.statusCode = 200; res.statusCode = 200;
res.end(); res.end();
})); }));
vi.stubEnv("NEXT_PUBLIC_DC_SERVICE_API_URL", upstream); 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) => { const frontend = await listen(createServer(async (req, res) => {
try { try {
const incomingHeaders = new Headers(); const incomingHeaders = new Headers();
@@ -59,7 +80,7 @@ describe("DC middleware through the actual Next.js HTTP proxy", () => {
incomingHeaders.append(name, part); 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, method: req.method,
headers: incomingHeaders, headers: incomingHeaders,
})); }));
@@ -75,12 +96,13 @@ describe("DC middleware through the actual Next.js HTTP proxy", () => {
} }
})); }));
const status = await new Promise<number | undefined>((resolve, reject) => { const status = await new Promise<number | undefined>((resolve, reject) => {
const req = request(`${frontend}/dc-service/api/v1/clsf?clsfSystmNm=test`, { const req = request(`${frontend}${path}`, {
method, method,
headers: { headers: {
Host: "frontend.invalid", Host: "frontend.invalid",
Cookie: "Authorization=fixture-token; token-id=fixture-user", Cookie: "Authorization=fixture-token; token-id=fixture-user",
"X-Site-Id": "DC", "X-Site-Id": "DC",
...(body ? { "Content-Type": "application/json" } : {}),
"X-Forwarded-Proto": "https", "X-Forwarded-Proto": "https",
"X-Forwarded-Port": "443", "X-Forwarded-Port": "443",
"X-Client-IP": "192.0.2.99", "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.setTimeout(5000, () => req.destroy(new Error("local proxy test timed out")));
req.on("error", reject); req.on("error", reject);
req.end(); req.end(body);
}); });
expect(status).toBe(200); 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["x-forwarded-host"]).toBe("frontend.invalid");
expect(upstreamHeaders.host).toBe(new URL(upstream).host); expect(upstreamHeaders.host).toBe(new URL(upstream).host);
expect(upstreamHeaders.authorization).toBe("fixture-token"); expect(upstreamHeaders.authorization).toBe("fixture-token");
+2
View File
@@ -18,4 +18,6 @@ export const ACCESS_TOKEN =
export const REFRESH_TOKEN = export const REFRESH_TOKEN =
process.env.NEXT_PUBLIC_REFRESH_TOKEN || "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_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; export const COOKIE_DOMAIN = process.env.NEXT_PUBLIC_COOKIE_DOMAIN;