import "@testing-library/jest-dom"; import { fireEvent, render, screen } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import type { LoaderFunctionArgs } from "react-router"; import { MemoryRouter } from "react-router"; const navigate = vi.fn(); let routeLoaderData: unknown; let currentLocation = { pathname: "/unauthorized/app.dashboard.view", search: "?redirect=%2F", hash: "", state: null, key: "test" }; vi.mock("react-router", async () => { const actual = await vi.importActual("react-router"); return { ...actual, useLoaderData: () => routeLoaderData, useLocation: () => currentLocation, useMatches: () => [], useNavigate: () => navigate, }; }); vi.mock("~/components/brand/Logo", () => ({ default: () =>
Logo
})); vi.mock("~/components/public/PublicFooter", () => ({ default: () => })); vi.mock("~/components/ui/modals/ConfirmModal", () => ({ default: () => null })); vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({}) })); vi.mock("~/utils/helpers/AnalyticsHelper", () => ({ default: { addEvent: vi.fn() } })); vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => ({ "pages.unauthorized.goBackToApp": "Go back to app", "pages.unauthorized.goBackToAdmin": "Go back to admin", "pages.unauthorized.recheckPermission": "Re-check permission", "pages.unauthorized.permission": "Permission", "shared.goBack": "Go back", })[key] ?? key, }), })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => (key === "shared.unauthorized" ? "Unauthorized" : key) })), })); vi.mock("~/utils/db/permissions/permissions.db.server", () => ({ getPermissionName: vi.fn() })); vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ getUserPermission: vi.fn() })); vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn() })); vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() })); vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn() })); import GlobalUnauthorizedRoute, { headers as globalHeaders, loader as globalLoader } from "./unauthorized.$permission"; import TenantUnauthorizedRoute, { loader as tenantLoader } from "./unauthorized.$permission.$tenant"; import { getPermissionName } from "~/utils/db/permissions/permissions.db.server"; import { getUser } from "~/utils/db/users.db.server"; import { getUserPermission } from "~/utils/helpers/.server/PermissionsService"; import { getUserInfo } from "~/utils/session.server"; import { getTenantIdFromUrl } from "~/utils/services/.server/urlService"; const mocks = { getPermissionName: vi.mocked(getPermissionName), getUser: vi.mocked(getUser), getUserInfo: vi.mocked(getUserInfo), getUserPermission: vi.mocked(getUserPermission), getTenantIdFromUrl: vi.mocked(getTenantIdFromUrl), }; const permission = { id: "permission_1", name: "app.dashboard.view", description: "View dashboard" }; function unauthorizedLoaderArgs(pathname: string, params: Record): LoaderFunctionArgs { return { request: new Request(`https://example.test${pathname}`), params, context: {}, unstable_pattern: pathname.includes("/acme") ? "unauthorized.$permission.$tenant" : "unauthorized.$permission", } as LoaderFunctionArgs; } function renderRoute(Route: React.ComponentType) { return render( ); } async function expectRedirectLocation(promise: Promise) { try { await promise; } catch (error) { expect(error).toBeInstanceOf(Response); return (error as Response).headers.get("Location"); } throw new Error("Expected redirect response"); } beforeEach(() => { vi.clearAllMocks(); navigate.mockReset(); routeLoaderData = { permission, isAdmin: false, appFallbackPath: "https://app.example.test/" }; currentLocation = { pathname: "/unauthorized/app.dashboard.view", search: "?redirect=%2F", hash: "", state: null, key: "test" }; mocks.getPermissionName.mockResolvedValue(permission); mocks.getUserInfo.mockResolvedValue({ userId: "user_123" } as never); mocks.getUserPermission.mockResolvedValue({ permission, userPermission: null }); mocks.getTenantIdFromUrl.mockResolvedValue("tenant_1"); mocks.getUser.mockResolvedValue({ id: "user_123", admin: false } as never); }); describe("permission-denial pages", () => { it("renders global permission details and app re-check controls through the shared error page", () => { renderRoute(GlobalUnauthorizedRoute); expect(screen.getByTestId("error-page")).toHaveAttribute("data-error-status", "401"); expect(screen.getByTestId("error-page-logo")).toBeInTheDocument(); expect(screen.getByTestId("public-footer")).toBeInTheDocument(); expect(screen.getByText("App Dashboard View")).toBeInTheDocument(); expect(screen.getByText("app.dashboard.view")).toBeInTheDocument(); expect(screen.getByRole("link", { name: /go back to app/i })).toHaveAttribute("href", "https://app.example.test/"); fireEvent.click(screen.getByRole("button", { name: /re-check permission/i })); expect(navigate).toHaveBeenCalledWith(currentLocation); }); it("uses the global admin back target for admin users", () => { routeLoaderData = { permission, isAdmin: true, appFallbackPath: "https://app.example.test/" }; renderRoute(GlobalUnauthorizedRoute); expect(screen.getByRole("link", { name: /go back to admin/i })).toHaveAttribute("href", "/dashboard"); }); it("renders tenant permission details and preserves go-back plus re-check behavior", () => { routeLoaderData = { permission }; currentLocation = { pathname: "/unauthorized/app.dashboard.view/acme", search: "?redirect=%2Fdashboard", hash: "", state: null, key: "tenant" }; renderRoute(TenantUnauthorizedRoute); expect(screen.getByTestId("error-page")).toHaveAttribute("data-error-status", "401"); expect(screen.getByText("App Dashboard View")).toBeInTheDocument(); expect(screen.getByText("app.dashboard.view")).toBeInTheDocument(); fireEvent.click(screen.getByText("Go back")); expect(navigate).toHaveBeenCalledWith(-1); fireEvent.click(screen.getByRole("button", { name: /re-check permission/i })); expect(navigate).toHaveBeenCalledWith(currentLocation); }); it("redirects missing global permissions to the 404 permission-not-found page", async () => { mocks.getPermissionName.mockResolvedValue(null); const location = await expectRedirectLocation(globalLoader(unauthorizedLoaderArgs("/unauthorized/missing", { permission: "missing" }))); expect(location).toBe("/404?error=permission-not-found"); }); it("redirects missing tenant permissions to the 404 permission-not-found page", async () => { mocks.getPermissionName.mockResolvedValue(null); const location = await expectRedirectLocation( tenantLoader(unauthorizedLoaderArgs("/unauthorized/missing/acme", { permission: "missing", tenant: "acme" })) ); expect(location).toBe("/404?error=permission-not-found"); }); it("resolves tenant route params when re-checking tenant permissions without auto-redirecting", async () => { mocks.getUserPermission.mockResolvedValue({ permission, userPermission: "user_permission_123" }); const data = await tenantLoader( unauthorizedLoaderArgs("/unauthorized/app.dashboard.view/acme?redirect=%2Fdashboard", { permission: "app.dashboard.view", tenant: "acme" }) ); expect(data).toMatchObject({ permission }); expect(mocks.getTenantIdFromUrl).toHaveBeenCalledWith({ permission: "app.dashboard.view", tenant: "acme" }); expect(mocks.getUserPermission).toHaveBeenCalledWith({ userId: "user_123", permissionName: "app.dashboard.view", tenantId: "tenant_1" }); }); it("preserves global restored-access behavior without redirecting yet", async () => { mocks.getUserPermission.mockResolvedValue({ permission, userPermission: "user_permission_123" }); mocks.getUser.mockResolvedValue({ id: "user_123", admin: false, passwordHash: "must-never-reach-hydration", totpSecretEncrypted: "must-never-reach-hydration", } as never); const data = await globalLoader(unauthorizedLoaderArgs("/unauthorized/app.dashboard.view?redirect=%2F", { permission: "app.dashboard.view" })); expect(data).toMatchObject({ permission, isAdmin: false }); expect(JSON.stringify(data)).not.toContain("passwordHash"); expect(JSON.stringify(data)).not.toContain("totpSecretEncrypted"); expect(globalHeaders()).toEqual({ "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" }); expect(mocks.getUserPermission).toHaveBeenCalledWith({ userId: "user_123", permissionName: "app.dashboard.view" }); }); });