Files
frontend/apps/dc/app/api/proxy/[...url]/route.test.ts

187 lines
6.9 KiB
TypeScript

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("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 () => {
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);
});
});