// @vitest-environment node import type { ActionFunctionArgs } from "react-router"; import { beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) })); vi.mock("react-router", async () => { const actual = await vi.importActual("react-router"); return { ...actual, Link: () => null, useActionData: () => undefined, useLoaderData: () => ({}), useNavigate: () => vi.fn(), useOutlet: () => null, }; }); vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } })); vi.mock("~/components/core/users/UsersTable", () => ({ default: () => null })); vi.mock("~/components/ui/button", () => ({ Button: () => null })); vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null })); vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null })); vi.mock("~/components/ui/slideOvers/SlideOverWideEmpty", () => ({ default: () => null })); vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({ createMetrics: vi.fn() })); vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders: vi.fn() })); vi.mock("~/utils/data/useAdminData", () => ({ useAdminData: () => ({}) })); vi.mock("~/utils/db/logs.db.server", () => ({ getLastUserLogsByUserIds: vi.fn() })); vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn() })); vi.mock("~/utils/helpers/RowPaginationHelper", () => ({ getFiltersFromCurrentUrl: vi.fn(), getPaginationFromCurrentUrl: vi.fn(), })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })), })); vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: () => ({ routing: { appBaseDomain: "example.test", protocol: "https", webAppHost: "app.example.test", adminAppHost: "admin.example.test", }, }), })); vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ appPath: ({ tenantSlug, path }: { tenantSlug: string; path?: string }) => `/${tenantSlug}${path ? `/${path}` : ""}`, adminPath: (path?: string) => (path ? `/${path}` : "/"), })); vi.mock("~/utils/auth/passwordHasher.server", () => ({ hashPassword: vi.fn(async () => "new-password-hash") })); vi.mock("~/services/auth/password-policy.server", () => ({ validatePassword: vi.fn(async () => ({ valid: true, errors: [] })) })); vi.mock("~/services/auth/sessionStore.server", () => ({ revokeAllUserSessionsForUser: vi.fn() })); vi.mock("~/utils/db/tenants.db.server", () => ({ adminGetAllTenantsIdsAndNames: vi.fn(), getTenant: vi.fn(), })); vi.mock("~/utils/db/users.db.server", () => ({ adminGetAllUsers: vi.fn(), getUser: vi.fn(), updateUserPassword: vi.fn(), })); vi.mock("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() })); vi.mock("~/utils/session.server", () => ({ createImpersonationStartedAt: vi.fn(() => "2026-07-24T17:00:00.000Z"), getUserInfo: vi.fn(), setLoggedUser: vi.fn(), validateCSRFToken: vi.fn(), })); vi.mock("~/services/auth/session-handoff.server", () => ({ createSessionHandoffRedirect: vi.fn() })); vi.mock("~/services/admin/admin-action-audit.server", () => ({ recordAdminAction: vi.fn() })); vi.mock("~/services/admin/admin-identity.server", () => ({ requireAdminIdentityPermission: vi.fn() })); vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { createUserEventWithMutation: vi.fn(async (_args, mutation) => mutation()) }, })); import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server"; import { recordAdminAction } from "~/services/admin/admin-action-audit.server"; import { createSessionHandoffRedirect } from "~/services/auth/session-handoff.server"; import { revokeAllUserSessionsForUser } from "~/services/auth/sessionStore.server"; import { getTenant } from "~/utils/db/tenants.db.server"; import { getUser, updateUserPassword } from "~/utils/db/users.db.server"; import { deleteUserWithItsTenants } from "~/utils/services/userService"; import { setLoggedUser, validateCSRFToken } from "~/utils/session.server"; import { action } from "./users"; const adminSession = { id: "admin-session-1", adminUserId: "admin-1", adminUser: { id: "admin-1", email: "admin@example.test" }, }; const targetUser = { id: "user-1", email: "user@example.test", firstName: "Target", lastName: "User", defaultTenantId: "tenant-1", }; function postRequest(actionName = "impersonate", extra: Record = {}) { return new Request("https://admin.example.test/accounts/users", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ action: actionName, "user-id": targetUser.id, reason: "Supportfall HG-1234 prüfen", ...extra, }), }); } async function callAction(actionName = "impersonate", extra: Record = {}) { return action({ request: postRequest(actionName, extra), params: {}, context: {}, unstable_pattern: "admin/accounts/users", } as ActionFunctionArgs); } describe("separated AdminUser tenant impersonation", () => { beforeEach(() => { vi.clearAllMocks(); vi.mocked(requireAdminIdentityPermission).mockResolvedValue(adminSession as never); vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never); vi.mocked(getUser).mockResolvedValue(targetUser as never); vi.mocked(setLoggedUser).mockResolvedValue({ userId: targetUser.id, defaultTenantId: "tenant-1", defaultTenant: { id: "tenant-1", slug: "acme" }, } as never); vi.mocked(getTenant).mockResolvedValue({ id: "tenant-1", slug: "acme" } as never); vi.mocked(createSessionHandoffRedirect).mockResolvedValue( new Response(null, { status: 302, headers: { Location: "https://app.example.test/auth/session-handoff?code=opaque" } }) as never ); vi.mocked(updateUserPassword).mockResolvedValue({} as never); vi.mocked(deleteUserWithItsTenants).mockResolvedValue({ deletedTenants: [] } as never); }); it("uses the smallest permission, reasoned platform audit and a bounded banner marker", async () => { const response = await callAction(); expect(response.status).toBe(302); expect(requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin_identity.impersonation.start"); expect(recordAdminAction).toHaveBeenCalledWith( expect.objectContaining({ action: "impersonation.started", actorUserId: adminSession.adminUserId, targetId: targetUser.id, reason: "Supportfall HG-1234 prüfen", }) ); expect(createSessionHandoffRedirect).toHaveBeenCalledWith({ request: expect.any(Request), session: expect.objectContaining({ userId: targetUser.id, impersonatingFromAdminUserId: adminSession.adminUserId, impersonatingFromAdminEmail: adminSession.adminUser.email, impersonatingStartedAt: "2026-07-24T17:00:00.000Z", }), redirectTo: "https://app.example.test/acme/dashboard", }); }); it("rejects an impersonation without a meaningful operator reason before switching", async () => { const response = await callAction("impersonate", { reason: "x" }); expect(response.status).toBe(400); expect(setLoggedUser).not.toHaveBeenCalled(); expect(recordAdminAction).not.toHaveBeenCalled(); }); it("uses dedicated AdminRBAC for password reset and revokes the target sessions first", async () => { const response = await callAction("change-password", { "password-new": "new-password-123" }); expect(response.status).toBe(200); expect(requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.changePassword"); expect(revokeAllUserSessionsForUser).toHaveBeenCalledWith(targetUser.id); expect(updateUserPassword).toHaveBeenCalledWith({ passwordHash: "new-password-hash" }, targetUser.id); }); it("uses dedicated AdminRBAC for tenant-user deletion", async () => { const response = await callAction("delete-user"); expect(response.status).toBe(200); expect(requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.delete"); expect(deleteUserWithItsTenants).toHaveBeenCalledWith({ actorUserId: adminSession.adminUserId, targetUser, request: expect.any(Request), }); }); it("propagates permission denial as 404 without touching the tenant target", async () => { vi.mocked(requireAdminIdentityPermission).mockRejectedValueOnce(Response.json({}, { status: 404 })); await expect(callAction()).rejects.toMatchObject({ status: 404 }); expect(setLoggedUser).not.toHaveBeenCalled(); }); });