Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,10 +1,8 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
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-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
@@ -16,47 +14,41 @@ vi.mock("react-router", async () => {
useOutlet: () => null,
};
});
vi.mock("react-hot-toast", () => ({ default: { success: vi.fn() } }));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
appPath: ({ tenantSlug, path }: { tenantSlug: string; path?: string }) => (path ? `/${tenantSlug}/${path}` : `/${tenantSlug}`),
adminPath: (path?: string | { mode?: string; path?: string }, options?: { mode?: string }) => {
const inputPath = typeof path === "object" ? path.path : path;
const mode = typeof path === "object" ? path.mode : options?.mode;
const normalizedPath = inputPath ? `/${inputPath.replace(/^\/+/, "")}` : "";
return mode === "legacy" ? `/admin${normalizedPath}` : normalizedPath || "/";
},
}));
vi.mock("~/utils/app/HostRouting.server", () => ({
getHostRoutingContextFromRequest: vi.fn(() => "admin"),
}));
vi.mock("@hivegrid/config", () => ({
loadRequiredWebConfig: () => ({ routing: undefined }),
}));
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/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
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", () => ({ getLastUserLog: vi.fn() }));
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("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() }));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
}));
vi.mock("~/utils/auth/mfa/enforcement.server", () => ({
enforceAdminMfa: vi.fn(),
vi.mock("@hivegrid/config", () => ({
loadRequiredWebConfig: () => ({
routing: {
appBaseDomain: "example.test",
protocol: "https",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
},
}),
}));
vi.mock("~/utils/auth/mfa/step-up.server", () => ({
checkMfaStepUpState: vi.fn(),
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(),
@@ -64,163 +56,140 @@ vi.mock("~/utils/db/tenants.db.server", () => ({
vi.mock("~/utils/db/users.db.server", () => ({
adminGetAllUsers: vi.fn(),
getUser: vi.fn(),
getUserTotpStatus: vi.fn(),
updateUserPassword: vi.fn(),
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: vi.fn(),
}));
vi.mock("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() }));
vi.mock("~/utils/session.server", () => ({
createImpersonationStartedAt: vi.fn(() => "2026-05-08T17:00:00.000Z"),
createUserSession: vi.fn(),
createImpersonationStartedAt: vi.fn(() => "2026-07-24T17:00:00.000Z"),
getUserInfo: vi.fn(),
getUserSession: vi.fn(),
setLoggedUser: vi.fn(),
validateCSRFToken: vi.fn(),
}));
vi.mock("@hivegrid/db/impersonation-audit.server", () => ({
createImpersonationAudit: vi.fn(),
}));
vi.mock("@hivegrid/db/audit-events.server", () => ({
createAuditEvent: 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 { createImpersonationAudit } from "@hivegrid/db/impersonation-audit.server";
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
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, getUserTotpStatus, updateUserPassword } from "~/utils/db/users.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getUser, updateUserPassword } from "~/utils/db/users.db.server";
import { deleteUserWithItsTenants } from "~/utils/services/userService";
import { createUserSession, getUserInfo, getUserSession, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
import { setLoggedUser, validateCSRFToken } from "~/utils/session.server";
import { action } from "./users";
const actor = { id: "admin-1", admin: true, email: "admin@example.test" };
const targetUser = { id: "user-1", admin: false, email: "user@example.test", defaultTenantId: "tenant-1" };
const actorInfo = {
userId: actor.id,
lightOrDarkMode: "light",
lng: "en",
cookies: [],
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",
};
const enabledTotpStatus = { enabled: true, pending: false, enabledAt: new Date("2026-05-08T12:00:00.000Z"), pendingCreatedAt: null };
const freshStepUp = { verified: true, state: { userId: actor.id, method: "totp", verifiedAt: "2026-05-08T16:59:00.000Z" }, ageMs: 60_000 };
function postRequest(actionName = "impersonate", extra: Record<string, string> = {}) {
return new Request("https://admin.example.test/accounts/users?filter=active", {
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, ...extra }),
body: new URLSearchParams({
action: actionName,
"user-id": targetUser.id,
reason: "Supportfall HG-1234 prüfen",
...extra,
}),
});
}
async function callAction(actionName = "impersonate", extra: Record<string, string> = {}) {
try {
const response = await action({ request: postRequest(actionName, extra), params: {}, context: {}, unstable_pattern: "admin/accounts/users" } as ActionFunctionArgs);
return { thrown: false, response: response as Response };
} catch (error) {
return { thrown: true, response: await (error as Promise<Response>) };
}
return action({
request: postRequest(actionName, extra),
params: {},
context: {},
unstable_pattern: "admin/accounts/users",
} as ActionFunctionArgs);
}
describe("admin accounts user impersonation MFA guard", () => {
describe("separated AdminUser tenant impersonation", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
vi.mocked(requireAdminIdentityPermission).mockResolvedValue(adminSession as never);
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
vi.mocked(getUserInfo).mockResolvedValue(actorInfo as never);
vi.mocked(getUserSession).mockResolvedValue({ get: vi.fn() } as never);
vi.mocked(getUser).mockImplementation(async (id?: string) => (id === actor.id || id === undefined ? actor : id === targetUser.id ? targetUser : null) as never);
vi.mocked(getUserTotpStatus).mockResolvedValue(enabledTotpStatus as never);
vi.mocked(checkMfaStepUpState).mockReturnValue(freshStepUp as never);
vi.mocked(enforceAdminMfa).mockImplementation(() => ({ allowed: true, reason: "allowed", redirectTo: "/accounts/users" }) as never);
vi.mocked(setLoggedUser).mockResolvedValue({ userId: targetUser.id, defaultTenantId: "tenant-1" } 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);
vi.mocked(createImpersonationAudit).mockResolvedValue({
id: "audit-1",
createdAt: new Date("2026-05-08T17:00:00.000Z"),
actorUserId: actor.id,
targetUserId: targetUser.id,
tenantId: "tenant-1",
action: "start",
reason: "admin.users.impersonate",
requestPath: "/accounts/users",
metadata: null,
} as never);
vi.mocked(createUserSession).mockResolvedValue(new Response(null, { status: 302, headers: { Location: "/acme/dashboard" } }) as never);
});
it("requires fresh admin MFA step-up before creating an impersonation session", async () => {
const result = await callAction();
it("uses the smallest permission, reasoned platform audit and a bounded banner marker", async () => {
const response = await callAction();
expect(result.thrown).toBe(false);
expect(result.response).toBeDefined();
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.impersonate");
expect(getUserTotpStatus).toHaveBeenCalledWith(actor.id);
expect(checkMfaStepUpState).toHaveBeenCalledWith(expect.anything(), actor.id);
expect(enforceAdminMfa).toHaveBeenCalledWith(expect.objectContaining({
requestUrl: "https://admin.example.test/accounts/users?filter=active",
userId: actor.id,
isAdmin: true,
totpStatus: enabledTotpStatus,
stepUp: freshStepUp,
redirectMode: "host-aware",
}));
expect(setLoggedUser).toHaveBeenCalledWith(targetUser);
expect(getTenant).toHaveBeenCalledWith("tenant-1");
expect(result.response.headers.get("Location")).toBe("/acme/dashboard");
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("redirects to the MFA challenge and does not switch sessions when step-up is missing", async () => {
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
vi.mocked(enforceAdminMfa).mockReturnValue({
allowed: false,
reason: "step-up-missing",
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
} as never);
const result = await callAction();
expect(result.thrown).toBe(true);
expect(result.response.status).toBe(302);
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
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(createImpersonationAudit).not.toHaveBeenCalled();
expect(createUserSession).not.toHaveBeenCalled();
expect(recordAdminAction).not.toHaveBeenCalled();
});
it("requires fresh admin MFA before changing a user password", async () => {
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
vi.mocked(enforceAdminMfa).mockReturnValue({
allowed: false,
reason: "step-up-missing",
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
} as never);
const result = await callAction("change-password", { "password-new": "new-password-123" });
expect(result.thrown).toBe(true);
expect(result.response.status).toBe(302);
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
expect(updateUserPassword).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("requires fresh admin MFA before deleting a user", async () => {
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
vi.mocked(enforceAdminMfa).mockReturnValue({
allowed: false,
reason: "step-up-missing",
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
} as never);
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),
});
});
const result = await callAction("delete-user");
expect(result.thrown).toBe(true);
expect(result.response.status).toBe(302);
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
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();
});
});