409 lines
19 KiB
TypeScript
409 lines
19 KiB
TypeScript
// @vitest-environment node
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
|
import { action, loader } from "./index";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { adminGetAllTenantsWithUsage, getTenantSimple, updateTenantDeactivated } from "~/utils/db/tenants.db.server";
|
|
import { adminGetAllUsersNames, getUser } from "~/utils/db/users.db.server";
|
|
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
|
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
|
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
|
import { reserveTenantWithoutOwner } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
|
import { TENANT_PENDING_OWNER_REASON } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
|
|
import { requireUserId } from "~/utils/session.server";
|
|
import { prepareReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
|
|
import { getReservedOwnerInvitationReissueTarget, reissueReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationReissue.server";
|
|
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
|
|
|
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 {
|
|
...actual,
|
|
Link: () => null,
|
|
useActionData: () => undefined,
|
|
useLoaderData: () => ({}),
|
|
useNavigation: () => ({ state: "idle" }),
|
|
useSubmit: () => vi.fn(),
|
|
};
|
|
});
|
|
|
|
vi.mock("~/components/core/tenants/DeactivateTenantModal", () => ({ default: () => null }));
|
|
vi.mock("~/components/core/tenants/TenantsTable", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/button", () => ({ Button: () => null }));
|
|
vi.mock("~/components/ui/forms/FormGroup", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/input/InputText", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/modals/ActionResultModal", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/slideOvers/SlideOverWideEmpty", () => ({ default: () => null }));
|
|
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({
|
|
createMetrics: vi.fn(async () => ({
|
|
time: async <T,>(value: T | Promise<T>) => value,
|
|
getServerTimingHeader: () => ({ "Server-Timing": "admin.accounts;dur=1" }),
|
|
})),
|
|
}));
|
|
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders: vi.fn() }));
|
|
vi.mock("~/locale/i18next.server", () => ({
|
|
getTranslations: vi.fn(),
|
|
}));
|
|
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({
|
|
reserveTenantWithoutOwner: vi.fn(),
|
|
}));
|
|
vi.mock("~/domain/tenant-bootstrap/ownerInvitationIssuance.server", () => ({
|
|
prepareReservedOwnerInvitation: vi.fn(),
|
|
}));
|
|
vi.mock("~/domain/tenant-bootstrap/ownerInvitationReissue.server", () => ({
|
|
getReservedOwnerInvitationReissueTarget: vi.fn(),
|
|
reissueReservedOwnerInvitation: vi.fn(),
|
|
}));
|
|
vi.mock("~/domain/tenant-bootstrap/tenantBootstrap.constants", () => ({ TENANT_PENDING_OWNER_REASON: "pending_owner" }));
|
|
vi.mock("~/utils/app/UrlUtils", () => ({ default: { slugify: (value: string) => value.toLowerCase() } }));
|
|
vi.mock("~/utils/csrf", () => ({ appendCSRFToken: vi.fn() }));
|
|
vi.mock("~/utils/data/useAppOrAdminData", () => ({ useAppOrAdminData: () => ({}) }));
|
|
vi.mock("~/utils/db/tenants.db.server", () => ({
|
|
adminGetAllTenantsWithUsage: vi.fn(),
|
|
getTenantSimple: vi.fn(),
|
|
updateTenantDeactivated: vi.fn(),
|
|
}));
|
|
vi.mock("~/utils/db/users.db.server", () => ({ adminGetAllUsersNames: vi.fn(), getUser: vi.fn() }));
|
|
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
|
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn() }));
|
|
vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
|
getFiltersFromCurrentUrl: vi.fn(),
|
|
getPaginationFromCurrentUrl: vi.fn(),
|
|
}));
|
|
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn(), requireUserId: vi.fn() }));
|
|
vi.mock("~/utils/app/UserValidationUtils", () => ({ default: { validateEmail: vi.fn() } }));
|
|
|
|
const OWNER_INVITATION = {
|
|
issuanceKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
|
|
email: "owner@heizkraft.de",
|
|
firstName: "Anna",
|
|
lastName: "Berger",
|
|
fromUserId: "operator_1",
|
|
token: "o".repeat(43),
|
|
mail: { subject: "Einladung", html: `https://app.example.test/invitation/${"o".repeat(43)}` },
|
|
};
|
|
const tenants = [
|
|
{
|
|
id: "tenant-1",
|
|
name: "Acme",
|
|
slug: "acme",
|
|
createdAt: new Date("2026-05-01T00:00:00.000Z"),
|
|
subscription: { billingProviderCustomerId: "cus_1" },
|
|
},
|
|
{
|
|
id: "tenant-2",
|
|
name: "Beta",
|
|
slug: "beta",
|
|
createdAt: new Date("2026-05-02T00:00:00.000Z"),
|
|
subscription: null,
|
|
},
|
|
];
|
|
|
|
function callLoader(url = "https://admin.example.test/accounts") {
|
|
const request = new Request(url);
|
|
return loader({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as LoaderFunctionArgs) as Promise<Response>;
|
|
}
|
|
|
|
describe("admin accounts invoice hydration", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
process.env.APP_NAME = "HiveGrid";
|
|
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
|
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
|
vi.mocked(adminGetAllUsersNames).mockResolvedValue([] as never);
|
|
vi.mocked(getFiltersFromCurrentUrl).mockReturnValue(undefined as never);
|
|
vi.mocked(getPaginationFromCurrentUrl).mockReturnValue({ page: 1, pageSize: 10 } as never);
|
|
vi.mocked(adminGetAllTenantsWithUsage).mockResolvedValue({
|
|
items: tenants,
|
|
pagination: { page: 1, pageSize: 10, totalItems: tenants.length, totalPages: 1 },
|
|
} as never);
|
|
vi.mocked(requireUserId).mockResolvedValue("operator_1");
|
|
vi.mocked(getUser).mockResolvedValue({ id: "operator_1", firstName: "Olivia", locale: "de" } as never);
|
|
vi.mocked(UserValidationUtils.validateEmail).mockReturnValue(true);
|
|
vi.mocked(prepareReservedOwnerInvitation).mockResolvedValue(OWNER_INVITATION);
|
|
vi.mocked(getReservedOwnerInvitationReissueTarget).mockResolvedValue({
|
|
tenantName: "Heizkraft GmbH",
|
|
invitationId: "invite-old",
|
|
email: "owner@heizkraft.de",
|
|
firstName: "Anna",
|
|
lastName: "Berger",
|
|
});
|
|
vi.mocked(reissueReservedOwnerInvitation).mockResolvedValue({ invitationId: "invite-new", replayed: false });
|
|
vi.mocked(getTenantSimple).mockResolvedValue({ deactivatedReason: null } as never);
|
|
});
|
|
|
|
it("loads the default tenant list without processor invoice hydration", async () => {
|
|
const response = await callLoader();
|
|
const body = await response.json();
|
|
|
|
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.accounts.view");
|
|
expect(body.tenantInvoices).toBeUndefined();
|
|
expect(body).not.toHaveProperty("includeInvoices");
|
|
expect(body.reservationRequestKey).toMatch(/^[0-9a-f-]{36}$/i);
|
|
expect(body.ownerInvitationReissueKey).toMatch(/^[0-9a-f-]{36}$/i);
|
|
expect(body.ownerInvitationReissueKey).not.toBe(body.reservationRequestKey);
|
|
});
|
|
|
|
it.each([
|
|
["deactivate", false, "billing"],
|
|
["activate", true, ""],
|
|
] as const)("runs the %s mutation inside the selected tenant RLS context", async (operation, active, reason) => {
|
|
vi.mocked(updateTenantDeactivated).mockImplementationOnce(async (tenantId) => {
|
|
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId });
|
|
return { id: tenantId } as never;
|
|
});
|
|
const form = new FormData();
|
|
form.set("action", operation);
|
|
form.set("id", "tenant-1");
|
|
form.set("reason", reason);
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
await runWithRlsContext({ userId: "operator_1" }, () =>
|
|
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
|
);
|
|
|
|
expect(updateTenantDeactivated).toHaveBeenCalledWith("tenant-1", {
|
|
active,
|
|
deactivatedReason: active ? null : "billing",
|
|
});
|
|
expect(getRlsExecutionContext()).toBeNull();
|
|
});
|
|
|
|
it("atomically reserves an inactive tenant and queues its OWNER invitation", async () => {
|
|
vi.mocked(reserveTenantWithoutOwner).mockResolvedValue({
|
|
id: "tenant-reserved",
|
|
name: "Heizkraft GmbH",
|
|
slug: "heizkraft",
|
|
active: false,
|
|
deactivatedReason: TENANT_PENDING_OWNER_REASON,
|
|
} as never);
|
|
const form = new FormData();
|
|
form.set("action", "create");
|
|
form.set("name", "Heizkraft GmbH");
|
|
form.set("slug", "heizkraft");
|
|
form.set("reservationRequestKey", "d7077797-054b-497a-b1ce-8e4f36257a96");
|
|
form.set("ownerEmail", "OWNER@HEIZKRAFT.DE");
|
|
form.set("ownerFirstName", "Anna");
|
|
form.set("ownerLastName", "Berger");
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
const result = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
|
|
|
expect(prepareReservedOwnerInvitation).toHaveBeenCalledWith({
|
|
request,
|
|
issuanceKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
|
|
tenantName: "Heizkraft GmbH",
|
|
email: "owner@heizkraft.de",
|
|
firstName: "Anna",
|
|
lastName: "Berger",
|
|
issuer: { id: "operator_1", firstName: "Olivia", locale: "de" },
|
|
});
|
|
expect(reserveTenantWithoutOwner).toHaveBeenCalledWith({
|
|
name: "Heizkraft GmbH",
|
|
slug: "heizkraft",
|
|
operatorUserId: "operator_1",
|
|
reservationRequestKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
|
|
ownerInvitation: OWNER_INVITATION,
|
|
});
|
|
expect(result).toEqual({
|
|
intent: "create",
|
|
ok: true,
|
|
createdTenantId: "tenant-reserved",
|
|
messageKey: "admin.accounts.toast.ownerInvitationSent",
|
|
});
|
|
});
|
|
|
|
it("rotates an owner invitation with a page-stable idempotency key", async () => {
|
|
const issuanceKey = "93923898-e834-41e9-9e2c-0c03080e91df";
|
|
const reissuedDraft = { ...OWNER_INVITATION, issuanceKey };
|
|
vi.mocked(prepareReservedOwnerInvitation).mockResolvedValueOnce(reissuedDraft);
|
|
const form = new FormData();
|
|
form.set("action", "resend-owner-invitation");
|
|
form.set("id", "tenant-reserved");
|
|
form.set("issuanceKey", issuanceKey);
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
|
|
|
expect(getReservedOwnerInvitationReissueTarget).toHaveBeenCalledWith({
|
|
tenantId: "tenant-reserved",
|
|
operatorUserId: "operator_1",
|
|
});
|
|
expect(prepareReservedOwnerInvitation).toHaveBeenCalledWith({
|
|
request,
|
|
issuanceKey,
|
|
tenantName: "Heizkraft GmbH",
|
|
email: "owner@heizkraft.de",
|
|
firstName: "Anna",
|
|
lastName: "Berger",
|
|
issuer: { id: "operator_1", firstName: "Olivia", locale: "de" },
|
|
});
|
|
expect(reissueReservedOwnerInvitation).toHaveBeenCalledWith({
|
|
tenantId: "tenant-reserved",
|
|
operatorUserId: "operator_1",
|
|
sourceInvitationId: "invite-old",
|
|
ownerInvitation: reissuedDraft,
|
|
});
|
|
expect(response).toBeInstanceOf(Response);
|
|
await expect((response as Response).json()).resolves.toEqual({
|
|
intent: "resend-owner-invitation",
|
|
ok: true,
|
|
messageKey: "admin.accounts.toast.ownerInvitationResent",
|
|
});
|
|
});
|
|
|
|
it("rejects a malformed owner-invitation reissue key before loading the reservation", async () => {
|
|
const form = new FormData();
|
|
form.set("action", "resend-owner-invitation");
|
|
form.set("id", "tenant-reserved");
|
|
form.set("issuanceKey", "not-a-uuid");
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(400);
|
|
expect(getReservedOwnerInvitationReissueTarget).not.toHaveBeenCalled();
|
|
expect(prepareReservedOwnerInvitation).not.toHaveBeenCalled();
|
|
expect(reissueReservedOwnerInvitation).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("fails closed when the ownerless reservation changed before invitation rotation", async () => {
|
|
vi.mocked(reissueReservedOwnerInvitation).mockRejectedValueOnce(
|
|
new CatalogError(foundationErrors.idempotencyConflict, { scope: "tenant-owner-invitation-reissue", key: "fixture" })
|
|
);
|
|
const form = new FormData();
|
|
form.set("action", "resend-owner-invitation");
|
|
form.set("id", "tenant-reserved");
|
|
form.set("issuanceKey", "93923898-e834-41e9-9e2c-0c03080e91df");
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(409);
|
|
await expect((response as Response).json()).resolves.toEqual({
|
|
intent: "resend-owner-invitation",
|
|
errorKey: "admin.accounts.actions.ownerInvitationResendFailed",
|
|
});
|
|
});
|
|
|
|
it("does not hide an infrastructure failure as a user conflict", async () => {
|
|
vi.mocked(reissueReservedOwnerInvitation).mockRejectedValueOnce(new Error("database unavailable"));
|
|
const form = new FormData();
|
|
form.set("action", "resend-owner-invitation");
|
|
form.set("id", "tenant-reserved");
|
|
form.set("issuanceKey", "93923898-e834-41e9-9e2c-0c03080e91df");
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
await expect(action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)).rejects.toThrow(
|
|
"database unavailable"
|
|
);
|
|
});
|
|
|
|
it("rejects invalid owner identity before preparing a capability or creating a tenant", async () => {
|
|
vi.mocked(UserValidationUtils.validateEmail).mockReturnValueOnce(false);
|
|
const form = new FormData();
|
|
form.set("action", "create");
|
|
form.set("name", "Heizkraft GmbH");
|
|
form.set("slug", "heizkraft");
|
|
form.set("reservationRequestKey", "d7077797-054b-497a-b1ce-8e4f36257a96");
|
|
form.set("ownerEmail", "not-an-email");
|
|
form.set("ownerFirstName", "Anna");
|
|
form.set("ownerLastName", "Berger");
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(400);
|
|
expect(prepareReservedOwnerInvitation).not.toHaveBeenCalled();
|
|
expect(reserveTenantWithoutOwner).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects a malformed reservation request key before creating a tenant", async () => {
|
|
const form = new FormData();
|
|
form.set("action", "create");
|
|
form.set("name", "Heizkraft GmbH");
|
|
form.set("slug", "heizkraft");
|
|
form.set("reservationRequestKey", "attacker-controlled");
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(400);
|
|
expect(reserveTenantWithoutOwner).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([
|
|
["activate", ""],
|
|
["deactivate", "billing"],
|
|
] as const)("rejects forged %s of an ownerless reservation without changing its marker", async (operation, reason) => {
|
|
vi.mocked(getTenantSimple).mockImplementationOnce(async (tenantId) => {
|
|
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId });
|
|
return { id: tenantId, active: false, deactivatedReason: TENANT_PENDING_OWNER_REASON } as never;
|
|
});
|
|
const form = new FormData();
|
|
form.set("action", operation);
|
|
form.set("id", "tenant-reserved");
|
|
form.set("reason", reason);
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
const response = await runWithRlsContext({ userId: "operator_1" }, () =>
|
|
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
|
);
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(409);
|
|
await expect((response as Response).json()).resolves.toEqual({
|
|
intent: operation,
|
|
errorKey: "admin.accounts.actions.reservationRequiresOwner",
|
|
});
|
|
expect(updateTenantDeactivated).not.toHaveBeenCalled();
|
|
expect(getRlsExecutionContext()).toBeNull();
|
|
});
|
|
|
|
it.each(["activate", "deactivate"] as const)("fails closed when the %s target is not visible through RLS", async (operation) => {
|
|
vi.mocked(getTenantSimple).mockResolvedValueOnce(null);
|
|
const form = new FormData();
|
|
form.set("action", operation);
|
|
form.set("id", "tenant-hidden");
|
|
form.set("reason", "billing");
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
const response = await runWithRlsContext({ userId: "operator_1" }, () =>
|
|
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
|
);
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(409);
|
|
expect(updateTenantDeactivated).not.toHaveBeenCalled();
|
|
expect(getRlsExecutionContext()).toBeNull();
|
|
});
|
|
|
|
it("rejects a forged pending_owner reason on a normal tenant", async () => {
|
|
const form = new FormData();
|
|
form.set("action", "deactivate");
|
|
form.set("id", "tenant-normal");
|
|
form.set("reason", TENANT_PENDING_OWNER_REASON);
|
|
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
|
|
|
const response = await runWithRlsContext({ userId: "operator_1" }, () =>
|
|
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
|
);
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(409);
|
|
expect(getTenantSimple).not.toHaveBeenCalled();
|
|
expect(updateTenantDeactivated).not.toHaveBeenCalled();
|
|
});
|
|
});
|