// @vitest-environment node import { beforeEach, describe, expect, it, vi } from "vitest"; import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: () => ({ routing: { protocol: "https", adminAppHost: "admin.example.test", webAppHost: "app.example.test", apiHost: "api.example.test", appBaseDomain: "example.test", }, }), })); vi.mock("~/utils/auth/mfa/enforcement.server", () => ({ ADMIN_MFA_DEFAULT_REDIRECT_PATH: "/", ADMIN_MFA_ENROLLMENT_PATH: "/settings/profile", })); vi.mock("~/utils/auth/mfa/step-up.server", () => ({ setMfaStepUpState: vi.fn(), })); vi.mock("~/services/auth/totp.server", () => ({ verifyTotpCode: vi.fn(), })); vi.mock("~/utils/app/HostRouting.server", () => ({ getHostRoutingContextFromRequest: vi.fn(() => "unknown"), })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })), })); vi.mock("~/utils/db/users.db.server", () => ({ consumeUserMfaRecoveryCode: vi.fn(), getUser: vi.fn(), getUserTotpStatus: vi.fn(), })); vi.mock("~/utils/db.server", () => ({ db: { user: { findUnique: vi.fn(), }, }, })); vi.mock("~/utils/session.server", () => ({ commitSession: vi.fn(), getUserSession: vi.fn(), validateCSRFToken: vi.fn(), })); import { setMfaStepUpState } from "~/utils/auth/mfa/step-up.server"; import { verifyTotpCode } from "~/services/auth/totp.server"; import { resetMfaChallengeRateLimiterForTests } from "~/utils/auth/mfa/challenge-rate-limit.server"; import { getHostRoutingContextFromRequest } from "~/utils/app/HostRouting.server"; import { db } from "~/utils/db.server"; import { consumeUserMfaRecoveryCode, getUser, getUserTotpStatus } from "~/utils/db/users.db.server"; import { commitSession, getUserSession } from "~/utils/session.server"; import { action, loader } from "./mfa-challenge"; const adminUser = { id: "admin-1", admin: true }; const enabledStatus = { enabled: true, pending: false, enabledAt: new Date("2026-05-08T12:00:00.000Z"), pendingCreatedAt: null }; const disabledStatus = { enabled: false, pending: false, enabledAt: null, pendingCreatedAt: null }; type SessionMock = { get: ReturnType; set: ReturnType; unset: ReturnType; }; function sessionFor(userId: string | null = adminUser.id): SessionMock { return { get: vi.fn((key: string) => (key === "userId" ? userId : undefined)), set: vi.fn(), unset: vi.fn(), }; } function postRequest(values: Record, url = "https://admin.example.test/mfa-challenge") { return new Request(url, { method: "POST", body: new URLSearchParams(values) }); } async function callLoader(url = "https://admin.example.test/mfa-challenge") { return loader({ request: new Request(url), params: {}, context: {}, unstable_pattern: "admin/mfa-challenge" } as LoaderFunctionArgs) as Promise; } async function callAction(values: Record, url?: string) { try { const response = await action({ request: postRequest(values, url), params: {}, context: {}, unstable_pattern: "admin/mfa-challenge" } as ActionFunctionArgs); return { thrown: false, response: response as Response }; } catch (error) { return { thrown: true, response: error as Response }; } } async function responseJson(response: Response) { return response.json() as Promise>; } function expectNoSecretLeak(payload: unknown) { const serialized = JSON.stringify(payload); expect(serialized).not.toContain("encrypted-secret"); expect(serialized).not.toContain("totpSecretEncrypted"); expect(serialized).not.toContain("recovery-hash"); expect(serialized).not.toContain("cookie-value"); expect(serialized).not.toContain("password"); } describe("admin MFA challenge route", () => { beforeEach(() => { vi.clearAllMocks(); resetMfaChallengeRateLimiterForTests(); vi.mocked(getHostRoutingContextFromRequest).mockReturnValue("admin"); vi.mocked(getUserSession).mockResolvedValue(sessionFor() as never); vi.mocked(getUser).mockResolvedValue(adminUser as never); vi.mocked(getUserTotpStatus).mockResolvedValue(enabledStatus as never); vi.mocked(db.user.findUnique).mockResolvedValue({ totpSecretEncrypted: "encrypted-secret", totpEnabledAt: enabledStatus.enabledAt } as never); vi.mocked(verifyTotpCode).mockReturnValue(true); vi.mocked(consumeUserMfaRecoveryCode).mockResolvedValue({ consumed: true } as never); vi.mocked(commitSession).mockResolvedValue("session=cookie-value; Path=/; HttpOnly" as never); }); it("loader renders enrolled users with a sanitized redirect path", async () => { const response = await callLoader("https://admin.example.test/mfa-challenge?redirectTo=https://evil.test/steal"); const body = await responseJson(response); expect(response.status).toBe(200); expect(getUserTotpStatus).toHaveBeenCalledWith(adminUser.id); expect(body).toEqual({ redirectTo: "/", totpEnabled: true, enrollmentPath: "/settings/profile" }); expectNoSecretLeak(body); }); it("rate limits repeated invalid MFA attempts before verifying more codes", async () => { vi.mocked(verifyTotpCode).mockReturnValue(false); vi.mocked(consumeUserMfaRecoveryCode).mockResolvedValue({ consumed: false } as never); for (let index = 0; index < 5; index += 1) { const result = await callAction({ code: "123456", recoveryCode: "bad-code", redirectTo: "/" }); expect(result.response.status).toBe(400); } vi.mocked(verifyTotpCode).mockClear(); vi.mocked(consumeUserMfaRecoveryCode).mockClear(); const result = await callAction({ code: "123456", recoveryCode: "bad-code", redirectTo: "/" }); const body = await responseJson(result.response); expect(result.response.status).toBe(429); expect(result.response.headers.get("Retry-After")).toBe("300"); expect(body).toEqual({ error: "admin.mfaChallenge.errors.tooManyAttempts", redirectTo: "/" }); expect(verifyTotpCode).not.toHaveBeenCalled(); expect(consumeUserMfaRecoveryCode).not.toHaveBeenCalled(); expect(setMfaStepUpState).not.toHaveBeenCalled(); expect(commitSession).not.toHaveBeenCalled(); }); it("loader redirects non-admin-host requests to the canonical admin host", async () => { vi.mocked(getHostRoutingContextFromRequest).mockReturnValue("app"); await expect(callLoader("https://app.example.test/mfa-challenge?redirectTo=%2Fdashboard")).rejects.toMatchObject({ status: 302, headers: expect.any(Headers), }); expect(getUserSession).not.toHaveBeenCalled(); }); it("loader keeps canonical admin redirect paths on the admin host", async () => { vi.mocked(getHostRoutingContextFromRequest).mockReturnValue("admin"); const response = await callLoader("https://admin.example.test/mfa-challenge?redirectTo=%2Fdashboard"); const body = await responseJson(response); expect(response.status).toBe(200); expect(body).toEqual({ redirectTo: "/dashboard", totpEnabled: true, enrollmentPath: "/settings/profile" }); }); it("loader rejects removed API redirect paths", async () => { vi.mocked(getHostRoutingContextFromRequest).mockReturnValue("admin"); const response = await callLoader("https://admin.example.test/mfa-challenge?redirectTo=%2Fapi%2Fkeys"); const body = await responseJson(response); const apiRootResponse = await callLoader("https://admin.example.test/mfa-challenge?redirectTo=%2Fapi"); const apiRootBody = await responseJson(apiRootResponse); const legacyResponse = await callLoader("https://admin.example.test/mfa-challenge?redirectTo=%2Fapi%2Fv1%2Fhealth"); const legacyBody = await responseJson(legacyResponse); const canonicalApiResponse = await callLoader("https://admin.example.test/mfa-challenge?redirectTo=%2Fv1%2Fhealth"); const canonicalApiBody = await responseJson(canonicalApiResponse); expect(body).toEqual({ redirectTo: "/", totpEnabled: true, enrollmentPath: "/settings/profile" }); expect(apiRootBody).toEqual({ redirectTo: "/", totpEnabled: true, enrollmentPath: "/settings/profile" }); expect(legacyBody).toEqual({ redirectTo: "/", totpEnabled: true, enrollmentPath: "/settings/profile" }); expect(canonicalApiBody).toEqual({ redirectTo: "/", totpEnabled: true, enrollmentPath: "/settings/profile" }); }); it("loader redirects enrolled users to MFA setup when TOTP is disabled", async () => { vi.mocked(getUserTotpStatus).mockResolvedValue(disabledStatus as never); await expect(callLoader("https://admin.example.test/mfa-challenge")).rejects.toMatchObject({ status: 302, headers: expect.any(Headers) }); }); it("loader rejects non-admin users before rendering the challenge", async () => { vi.mocked(getUser).mockResolvedValue({ id: "user-1", admin: false } as never); await expect(callLoader("https://admin.example.test/mfa-challenge?redirectTo=%2Fdashboard")).rejects.toMatchObject({ status: 403 }); expect(getUserTotpStatus).not.toHaveBeenCalled(); }); it("verifies a valid TOTP code, stores step-up state, commits the session, and redirects", async () => { const session = sessionFor(); vi.mocked(getUserSession).mockResolvedValue(session as never); vi.mocked(getHostRoutingContextFromRequest).mockReturnValue("admin"); const result = await callAction({ code: "123456", redirectTo: "/settings/authentication" }); expect(result.thrown).toBe(true); expect(result.response.status).toBe(302); expect(result.response.headers.get("Location")).toBe("/settings/authentication"); expect(verifyTotpCode).toHaveBeenCalledWith("encrypted-secret", "123456"); expect(consumeUserMfaRecoveryCode).not.toHaveBeenCalled(); expect(setMfaStepUpState).toHaveBeenCalledWith(session, { userId: adminUser.id, method: "totp", redirectTo: "/settings/authentication" }); expect(commitSession).toHaveBeenCalledWith(session); expect(result.response.headers.get("Set-Cookie")).toContain("session=cookie-value"); }); it("falls back to a normalized recovery code when TOTP verification fails", async () => { vi.mocked(verifyTotpCode).mockReturnValue(false); const result = await callAction({ code: "123456", recoveryCode: " abcd-efgh ", redirectTo: "/" }); expect(result.thrown).toBe(true); expect(consumeUserMfaRecoveryCode).toHaveBeenCalledWith(adminUser.id, "ABCD-EFGH"); expect(setMfaStepUpState).toHaveBeenCalledWith(expect.anything(), { userId: adminUser.id, method: "recovery-code", redirectTo: "/" }); expect(commitSession).toHaveBeenCalledTimes(1); }); it("falls back to recovery codes when the encrypted TOTP secret cannot be verified", async () => { vi.mocked(verifyTotpCode).mockImplementation(() => { throw new Error("Invalid encrypted payload"); }); const result = await callAction({ code: "123456", recoveryCode: " abcd-efgh ", redirectTo: "/" }); expect(result.thrown).toBe(true); expect(consumeUserMfaRecoveryCode).toHaveBeenCalledWith(adminUser.id, "ABCD-EFGH"); expect(setMfaStepUpState).toHaveBeenCalledWith(expect.anything(), { userId: adminUser.id, method: "recovery-code", redirectTo: "/" }); expect(commitSession).toHaveBeenCalledTimes(1); }); it("rejects invalid codes without committing session state", async () => { vi.mocked(verifyTotpCode).mockReturnValue(false); vi.mocked(consumeUserMfaRecoveryCode).mockResolvedValue({ consumed: false } as never); const result = await callAction({ code: "123456", recoveryCode: "bad-code", redirectTo: "//evil.test" }); const body = await responseJson(result.response); expect(result.thrown).toBe(false); expect(result.response.status).toBe(400); expect(body).toEqual({ error: "admin.mfaChallenge.errors.invalidCode", redirectTo: "/" }); expect(setMfaStepUpState).not.toHaveBeenCalled(); expect(commitSession).not.toHaveBeenCalled(); expectNoSecretLeak(body); }); it("rejects non-admin users before code verification", async () => { vi.mocked(getUser).mockResolvedValue({ id: "user-1", admin: false } as never); const result = await callAction({ code: "123456", redirectTo: "/" }); const body = await responseJson(result.response); expect(result.response.status).toBe(403); expect(body).toEqual({ error: "admin.mfaChallenge.errors.adminAccessRequired", redirectTo: "/" }); expect(verifyTotpCode).not.toHaveBeenCalled(); expect(setMfaStepUpState).not.toHaveBeenCalled(); expect(commitSession).not.toHaveBeenCalled(); }); it("rejects non-admin-host POSTs before reading or mutating MFA state", async () => { vi.mocked(getHostRoutingContextFromRequest).mockReturnValue("app"); const result = await callAction({ code: "123456", redirectTo: "/dashboard" }, "https://app.example.test/mfa-challenge"); const body = await responseJson(result.response); expect(result.thrown).toBe(false); expect(result.response.status).toBe(403); expect(body).toEqual({ error: "admin.mfaChallenge.errors.adminHostRequired", redirectTo: "https://admin.example.test/mfa-challenge", }); expect(getUserSession).not.toHaveBeenCalled(); expect(setMfaStepUpState).not.toHaveBeenCalled(); expect(commitSession).not.toHaveBeenCalled(); }); });