168 lines
6.6 KiB
TypeScript
168 lines
6.6 KiB
TypeScript
// @vitest-environment node
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { getUser } from "~/utils/db/users.db.server";
|
|
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
|
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
|
import {
|
|
forgetTenantTrustedDevice,
|
|
getTenantSecuritySnapshot,
|
|
revokeTenantUserSession,
|
|
TenantSecurityError,
|
|
} from "~/services/admin/tenant-security.server";
|
|
import { action, loader } from "./$id.security";
|
|
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
|
|
|
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
|
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({ default: () => null }));
|
|
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
|
|
vi.mock("~/locale/format", () => ({
|
|
useLocaleFormatters: () => ({
|
|
dateTime: (value: string) => value,
|
|
}),
|
|
}));
|
|
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
|
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
|
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
|
|
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
|
vi.mock("~/services/admin/tenant-security.server", async () => {
|
|
const actual = await vi.importActual<typeof import("~/services/admin/tenant-security.server")>("~/services/admin/tenant-security.server");
|
|
return {
|
|
...actual,
|
|
getTenantSecuritySnapshot: vi.fn(),
|
|
revokeTenantUserSession: vi.fn(),
|
|
forgetTenantTrustedDevice: vi.fn(),
|
|
};
|
|
});
|
|
|
|
function callLoader(id = "tenant_1") {
|
|
return loader({ request: new Request("https://admin.example.test/accounts/tenant_1/security"), params: { id }, context: {} } as LoaderFunctionArgs);
|
|
}
|
|
|
|
function callAction(form: Record<string, string>, id = "tenant_1") {
|
|
return action({
|
|
request: new Request("https://admin.example.test/accounts/tenant_1/security", {
|
|
method: "POST",
|
|
body: new URLSearchParams(form),
|
|
}),
|
|
params: { id },
|
|
context: {},
|
|
} as ActionFunctionArgs);
|
|
}
|
|
|
|
describe("tenant security route", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
process.env.APP_NAME = "HiveGrid";
|
|
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
|
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
|
|
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
|
vi.mocked(getUserInfo).mockResolvedValue({ userId: "admin_1" } as never);
|
|
vi.mocked(getUser).mockResolvedValue({ id: "admin_1", email: "admin@hivegrid.de" } as never);
|
|
vi.mocked(getTenantSecuritySnapshot).mockResolvedValue({
|
|
now: "2026-07-09T10:00:00.000Z",
|
|
tenant: { id: "tenant_1", name: "Acme", slug: "acme", active: true },
|
|
users: [
|
|
{
|
|
id: "user_1",
|
|
email: "owner@example.test",
|
|
name: "Owner Example",
|
|
active: true,
|
|
membershipStatus: "active",
|
|
mfaEnabled: true,
|
|
mfaPending: false,
|
|
recoveryCodesConfigured: true,
|
|
},
|
|
],
|
|
sessions: [],
|
|
trustedDevices: [],
|
|
magicLinks: [],
|
|
ipLogs: [],
|
|
auditEvents: [],
|
|
});
|
|
vi.mocked(revokeTenantUserSession).mockResolvedValue(undefined);
|
|
vi.mocked(forgetTenantTrustedDevice).mockResolvedValue(undefined);
|
|
});
|
|
|
|
it("checks the tenant view permission and builds the security VM", async () => {
|
|
vi.mocked(getTenantSecuritySnapshot).mockImplementationOnce(async () => {
|
|
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
|
return {
|
|
now: "2026-07-09T10:00:00.000Z",
|
|
tenant: { id: "tenant_1", name: "Acme", slug: "acme", active: true },
|
|
users: [
|
|
{
|
|
id: "user_1",
|
|
email: "owner@example.test",
|
|
name: "Owner Example",
|
|
active: true,
|
|
membershipStatus: "active",
|
|
mfaEnabled: true,
|
|
mfaPending: false,
|
|
recoveryCodesConfigured: true,
|
|
},
|
|
],
|
|
sessions: [],
|
|
trustedDevices: [],
|
|
magicLinks: [],
|
|
ipLogs: [],
|
|
auditEvents: [],
|
|
};
|
|
});
|
|
const data = await callLoader();
|
|
|
|
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.view");
|
|
expect(getTenantSecuritySnapshot).toHaveBeenCalledWith("tenant_1");
|
|
expect(data.vm.status).toBe("ready");
|
|
});
|
|
|
|
it("redirects to account list when the tenant is missing", async () => {
|
|
vi.mocked(getTenantSecuritySnapshot).mockRejectedValueOnce(new TenantSecurityError("TENANT_NOT_FOUND"));
|
|
|
|
await expect(callLoader("missing")).rejects.toMatchObject({ status: 302 });
|
|
});
|
|
|
|
it("revokes a user session through the audited service", async () => {
|
|
vi.mocked(revokeTenantUserSession).mockImplementationOnce(async () => {
|
|
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
|
});
|
|
const response = (await callAction({
|
|
csrf: "csrf",
|
|
action: "revoke-session",
|
|
sessionId: "session_1",
|
|
reason: "Supportfall MFA Reset",
|
|
})) as Response;
|
|
|
|
await expect(response.json()).resolves.toEqual({ success: "admin.tenantSecurity.actions.sessionRevoked" });
|
|
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.settings.update");
|
|
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
|
|
expect(revokeTenantUserSession).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
tenantId: "tenant_1",
|
|
sessionId: "session_1",
|
|
reason: "Supportfall MFA Reset",
|
|
actorUserId: "admin_1",
|
|
actorEmail: "admin@hivegrid.de",
|
|
})
|
|
);
|
|
});
|
|
|
|
it("forgets a trusted device through the audited service", async () => {
|
|
vi.mocked(forgetTenantTrustedDevice).mockImplementationOnce(async () => {
|
|
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
|
});
|
|
const response = (await callAction({
|
|
csrf: "csrf",
|
|
action: "forget-device",
|
|
trustedDeviceId: "device_1",
|
|
reason: "Geraet verloren",
|
|
})) as Response;
|
|
|
|
await expect(response.json()).resolves.toEqual({ success: "admin.tenantSecurity.actions.deviceForgotten" });
|
|
expect(forgetTenantTrustedDevice).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1", trustedDeviceId: "device_1" }));
|
|
});
|
|
});
|