Files

1338 lines
55 KiB
TypeScript

// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext, runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
import { TenantUserJoined } from "~/application/enums/tenants/TenantUserJoined";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import type { Tenant } from "@hivegrid/db/prisma-browser";
vi.mock("~/utils/db.server", () => ({
db: {
tenant: {
count: vi.fn(),
create: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
findUnique: vi.fn(),
findUniqueOrThrow: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
},
tenantUser: {
count: vi.fn(),
create: vi.fn(),
delete: vi.fn(),
deleteMany: vi.fn(),
findFirst: vi.fn(),
findFirstOrThrow: vi.fn(),
findMany: vi.fn(),
},
userRole: {
deleteMany: vi.fn(),
},
groupUser: {
deleteMany: vi.fn(),
},
$transaction: vi.fn(),
},
dbRead: {
tenant: {
findMany: vi.fn(),
},
},
}));
vi.mock("../helpers/RowFiltersHelper", () => ({
default: {
getFiltersCondition: vi.fn(),
},
}));
vi.mock("../cache.server", () => ({
cachified: vi.fn((options: { getFreshValue: () => unknown }) => options.getFreshValue()),
clearCacheKey: vi.fn(),
clearCacheKeyPrefix: vi.fn(),
}));
vi.mock("../services/tenantService", () => ({
normalizeTenantSlug: (value: string) =>
value
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, ""),
isReservedTenantSlug: (value: string) => value === "admin",
}));
vi.mock("./permissions/userRoles.db.server", () => ({
createUserRole: vi.fn(),
}));
vi.mock("./tenantSubscriptions.db.server", () => ({
createTenantSubscription: vi.fn(),
}));
vi.mock("~/modules/plugins/services/.server/pluginHookPublisher", () => ({
emitPluginHookFireAndForget: vi.fn(),
}));
import { db, dbRead } from "~/utils/db.server";
import RowFiltersHelper from "../helpers/RowFiltersHelper";
import { cachified, clearCacheKey, clearCacheKeyPrefix } from "../cache.server";
import { createUserRole } from "./permissions/userRoles.db.server";
import { createTenantSubscription } from "./tenantSubscriptions.db.server";
import { TENANT_SNAPSHOT_SAFETY_TTL_SECONDS } from "./tenant-cache.server";
import { emitPluginHookFireAndForget } from "~/modules/plugins/services/.server/pluginHookPublisher";
import {
adminGetAllActiveTenantSimple,
adminGetAllTenants,
adminGetAllTenantsIdsAndNames,
adminGetAllTenantsWithUsage,
createTenant,
createTenantUser,
TenantSlugCollisionError,
emitTenantCreatedHook,
deleteTenant,
deleteTenantUser,
getAllTenantUsers,
getMyTenants,
getInvitationTenantIdentity,
getTenant,
getTenantByIdOrSlug,
getTenantBySlug,
getTenantMember,
getTenantSessionIdentityForUser,
getTenantSimple,
getTenantUser,
getTenantUserByIds,
getTenantUserSimple,
getTenantUserType,
getTenantUsers,
getTenantUsersCount,
getTenantUsersInTenantIds,
getTenantWithProfile,
getTenantWithUsers,
getTenantsInIds,
requireTenant,
updateTenant,
updateTenantAnrede,
updateTenantDeactivated,
} from "./tenants.db.server";
const dbMock = vi.mocked(db);
const dbReadMock = vi.mocked(dbRead);
function adapterPgUniqueConstraintError(
constraint: unknown,
meta: Record<string, unknown> = {},
originalMessage = "duplicate key value violates unique constraint"
): Error {
return Object.assign(new Error("Unique constraint failed"), {
code: "P2002",
meta: {
modelName: "Tenant",
...meta,
driverAdapterError: {
name: "DriverAdapterError",
cause: {
originalCode: "23505",
originalMessage,
kind: "UniqueConstraintViolation",
constraint,
},
},
},
});
}
describe("tenants db wrapper", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) => options.getFreshValue()) as never);
dbMock.$transaction.mockImplementation((async (operations: Promise<unknown>[] | ((tx: typeof db) => Promise<unknown>)) => {
if (Array.isArray(operations)) {
return await Promise.all(operations);
}
return await operations(db);
}) as never);
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue(undefined);
});
it("runs minimal tenant-scoped relation probes before paginating heavy hydration", async () => {
const baseWhere = { name: { contains: "acme" } };
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue(baseWhere as never);
vi.mocked(dbMock.tenant.findMany)
.mockResolvedValueOnce([{ id: "tenant_1" }, { id: "tenant_2" }, { id: "tenant_3" }] as never)
.mockResolvedValueOnce([{ id: "tenant_3" }] as never);
vi.mocked(dbMock.tenant.findFirst).mockImplementation(async ({ where }: { where: { id: string; OR: unknown[] } }) => {
expect(getRlsExecutionContext()?.tenantId).toBe(where.id);
expect(where.OR).toEqual([{ users: { some: { userId: "user_1" } } }]);
return { id: where.id } as never;
});
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce({ id: "tenant_2", users: [] } as never);
const result = await adminGetAllTenantsWithUsage(
{
query: "",
properties: [{ name: "userId", value: "user_1" }],
} as never,
{ page: 2, pageSize: 1 }
);
expect(dbMock.tenant.findMany).toHaveBeenNthCalledWith(1, { select: { id: true }, orderBy: { createdAt: "desc" } });
expect(dbMock.tenant.findMany).toHaveBeenNthCalledWith(2, { where: baseWhere, select: { id: true } });
expect(result.items).toEqual([expect.objectContaining({ id: "tenant_2" })]);
expect(result.pagination).toEqual({ page: 2, pageSize: 1, totalItems: 3, totalPages: 3 });
expect(dbMock.tenant.findFirst).toHaveBeenCalledTimes(2);
expect(dbMock.tenant.findUnique).toHaveBeenCalledTimes(1);
expect(dbMock.tenant.count).not.toHaveBeenCalled();
});
it("paginates root tenant ids before tenant-scoped hydration when no relation filter is active", async () => {
const rootWhere = { name: { contains: "acme" } };
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue(rootWhere as never);
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([{ id: "tenant_2" }, { id: "tenant_3" }] as never);
vi.mocked(dbMock.tenant.count).mockResolvedValueOnce(12);
vi.mocked(dbMock.tenant.findUnique).mockImplementation(async ({ where }: { where: { id: string } }) => {
expect(getRlsExecutionContext()?.tenantId).toBe(where.id);
return { id: where.id, users: [] } as never;
});
const result = await adminGetAllTenantsWithUsage(
{
query: "",
properties: [
{ name: "name", value: "acme" },
{ name: "userId", manual: true },
],
} as never,
{ page: 2, pageSize: 2 }
);
expect(dbMock.tenant.findMany).toHaveBeenCalledWith({
skip: 2,
take: 2,
where: rootWhere,
select: { id: true },
orderBy: { createdAt: "desc" },
});
expect(result.items.map((tenant) => tenant.id)).toEqual(["tenant_2", "tenant_3"]);
expect(result.pagination).toEqual({ page: 2, pageSize: 2, totalItems: 12, totalPages: 6 });
const hydrationArgs = vi.mocked(dbMock.tenant.findUnique).mock.calls[0]?.[0];
expect(hydrationArgs).toMatchObject({
where: { id: "tenant_2" },
select: {
users: { select: { user: { select: { email: true } } } },
_count: { select: { events: true } },
},
});
expect(hydrationArgs).not.toHaveProperty("include");
expect(JSON.stringify(hydrationArgs)).not.toMatch(/inboundAddresses|features|tiers/);
});
it("uses unfiltered, unpaginated defaults when no admin list options are supplied", async () => {
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([] as never);
vi.mocked(dbMock.tenant.count).mockResolvedValueOnce(0);
await expect(adminGetAllTenantsWithUsage()).resolves.toEqual({
items: [],
pagination: { page: 1, pageSize: 10, totalItems: 0, totalPages: 0 },
});
expect(dbMock.tenant.findMany).toHaveBeenCalledWith({
skip: undefined,
take: undefined,
where: {},
select: { id: true },
orderBy: { createdAt: "desc" },
});
expect(dbMock.tenant.count).toHaveBeenCalledWith({ where: {} });
});
it("uses read and write clients for the basic tenant listing helpers", async () => {
vi.mocked(dbMock.tenant.findMany).mockResolvedValue([] as never);
vi.mocked(dbReadMock.tenant.findMany).mockResolvedValue([] as never);
await getTenantsInIds(["tenant_1", "tenant_2"]);
await adminGetAllTenants();
await adminGetAllTenantsIdsAndNames();
await adminGetAllActiveTenantSimple();
expect(dbMock.tenant.findMany).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: { id: { in: ["tenant_1", "tenant_2"] } } }));
expect(dbMock.tenant.findMany).toHaveBeenNthCalledWith(2, {
select: { id: true },
orderBy: { createdAt: "desc" },
});
expect(dbReadMock.tenant.findMany).toHaveBeenNthCalledWith(1, {
select: { id: true, name: true, slug: true },
});
expect(dbReadMock.tenant.findMany).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
where: { active: true },
orderBy: { name: "asc" },
})
);
});
it("hydrates the complete admin tenant list inside each tenant RLS context", async () => {
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([{ id: "tenant_2" }, { id: "tenant_1" }] as never);
vi.mocked(dbMock.tenant.findUnique).mockImplementation(async ({ where }: { where: { id: string } }) => {
expect(getRlsExecutionContext()).toEqual({ userId: "operator_1", tenantId: where.id });
return {
id: where.id,
users: [{ userId: `user_${where.id}` }],
} as never;
});
const result = await runWithRlsContext({ userId: "operator_1" }, () => adminGetAllTenants());
expect(result).toEqual([
expect.objectContaining({ id: "tenant_2", users: [{ userId: "user_tenant_2" }] }),
expect.objectContaining({ id: "tenant_1", users: [{ userId: "user_tenant_1" }] }),
]);
expect(dbMock.tenant.findUnique).toHaveBeenCalledTimes(2);
expect(getRlsExecutionContext()).toBeNull();
});
it("wraps cached tenant identity lookups with stable cache keys", async () => {
vi.mocked(dbMock.tenant.findUnique).mockResolvedValue({ id: "tenant_1" } as never);
vi.mocked(dbMock.tenant.findFirst).mockResolvedValue({ id: "tenant_1" } as never);
await getTenant("tenant_1");
await getTenantSimple("tenant_1");
await getTenantByIdOrSlug("acme");
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "tenant:tenant_1" }));
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "tenantSimple:tenant_1" }));
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "tenantIdOrSlug:acme" }));
expect(dbMock.tenant.findFirst).toHaveBeenCalledWith({
where: { OR: [{ id: "acme" }, { slug: "acme" }] },
include: { subscription: true },
});
});
it("queries direct tenant identity variants without cache wrappers", async () => {
vi.mocked(dbMock.tenant.findUnique).mockResolvedValue({ id: "tenant_1" } as never);
await getTenantBySlug("acme");
await getTenantWithProfile("tenant_1");
await getTenantWithUsers("tenant_1");
expect(dbMock.tenant.findUnique).toHaveBeenNthCalledWith(1, { where: { slug: "acme" } });
expect(dbMock.tenant.findUnique).toHaveBeenNthCalledWith(2, { where: { id: "tenant_1" } });
expect(dbMock.tenant.findUnique).toHaveBeenNthCalledWith(3, { where: { id: "tenant_1" }, include: { users: true } });
});
it("resolves route and login tenant identities only through the authenticated user's active membership", async () => {
vi.mocked(dbMock.tenantUser.findFirst).mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1" });
return {
tenant: { id: "tenant_1", name: "Acme", slug: "acme", active: true, deactivatedReason: null },
} as never;
});
await expect(getTenantSessionIdentityForUser({ userId: "user_1", tenant: "acme" })).resolves.toEqual({
id: "tenant_1",
name: "Acme",
slug: "acme",
active: true,
deactivatedReason: null,
});
expect(dbMock.tenantUser.findFirst).toHaveBeenCalledWith({
where: {
userId: "user_1",
status: TenantUserStatus.ACTIVE,
tenant: { OR: [{ id: "acme" }, { slug: "acme" }], active: true },
},
select: {
tenant: { select: { id: true, name: true, slug: true, active: true, deactivatedReason: true } },
},
orderBy: { tenant: { name: "asc" } },
});
expect(cachified).not.toHaveBeenCalled();
expect(getRlsExecutionContext()).toBeNull();
});
it("rejects blank session identities and resolves an optional inactive tenant inside an existing user context", async () => {
await expect(getTenantSessionIdentityForUser({ userId: " " })).resolves.toBeNull();
await expect(getTenantSessionIdentityForUser({ userId: "user_1", tenant: " " })).resolves.toBeNull();
expect(dbMock.tenantUser.findFirst).not.toHaveBeenCalled();
vi.mocked(dbMock.tenantUser.findFirst).mockResolvedValueOnce(null);
await expect(
runWithRlsContext({ userId: "user_1" }, () => getTenantSessionIdentityForUser({ userId: "user_1", allowInactiveTenant: true }))
).resolves.toBeNull();
expect(dbMock.tenantUser.findFirst).toHaveBeenCalledWith({
where: {
userId: "user_1",
status: TenantUserStatus.ACTIVE,
tenant: {},
},
select: {
tenant: { select: { id: true, name: true, slug: true, active: true, deactivatedReason: true } },
},
orderBy: { tenant: { name: "asc" } },
});
expect(getRlsExecutionContext()).toBeNull();
});
it("fails closed for invitation tenant projections outside the verified capability context", async () => {
await expect(getInvitationTenantIdentity("tenant_1")).resolves.toBeNull();
await expect(runWithRlsContext({ tenantId: "tenant_2" }, () => getInvitationTenantIdentity("tenant_1"))).resolves.toBeNull();
expect(dbMock.tenant.findFirst).not.toHaveBeenCalled();
vi.mocked(dbMock.tenant.findFirst).mockResolvedValueOnce({
id: "tenant_1",
name: "Acme",
slug: "acme",
active: true,
deactivatedReason: null,
} as never);
await expect(runWithRlsContext({ tenantId: "tenant_1" }, () => getInvitationTenantIdentity("tenant_1"))).resolves.toEqual({
id: "tenant_1",
name: "Acme",
slug: "acme",
active: true,
deactivatedReason: null,
});
expect(dbMock.tenant.findFirst).toHaveBeenCalledWith({
where: { id: "tenant_1", active: true },
select: { id: true, name: true, slug: true, active: true, deactivatedReason: true },
});
});
it("reads only the explicitly allowed inactive reservation after the invite bound its tenant context", async () => {
vi.mocked(dbMock.tenant.findFirst).mockResolvedValueOnce({
id: "tenant_1",
name: "Acme",
slug: "acme",
active: false,
deactivatedReason: "pending_owner",
} as never);
await expect(
runWithRlsContext({ tenantId: "tenant_1" }, () => getInvitationTenantIdentity("tenant_1", { allowedInactiveReason: "pending_owner" }))
).resolves.toMatchObject({ id: "tenant_1", active: false, deactivatedReason: "pending_owner" });
expect(dbMock.tenant.findFirst).toHaveBeenCalledWith({
where: {
id: "tenant_1",
OR: [{ active: true }, { active: false, deactivatedReason: "pending_owner" }],
},
select: { id: true, name: true, slug: true, active: true, deactivatedReason: true },
});
});
it("does not broaden invitation visibility for an arbitrary inactive reason at runtime", async () => {
vi.mocked(dbMock.tenant.findFirst).mockResolvedValueOnce(null);
await runWithRlsContext({ tenantId: "tenant_1" }, () => getInvitationTenantIdentity("tenant_1", { allowedInactiveReason: "billing" as never }));
expect(dbMock.tenant.findFirst).toHaveBeenCalledWith({
where: { id: "tenant_1", active: true },
select: { id: true, name: true, slug: true, active: true, deactivatedReason: true },
});
});
it("uses the free-text query as a user filter when no base filter exists", async () => {
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([{ id: "tenant_1" }, { id: "tenant_2" }] as never);
vi.mocked(dbMock.tenant.findFirst)
.mockResolvedValueOnce({ id: "tenant_1" } as never)
.mockResolvedValueOnce({ id: "tenant_2" } as never);
vi.mocked(dbMock.tenant.findUnique)
.mockResolvedValueOnce({ id: "tenant_1", users: [{ userId: "user_query" }] } as never)
.mockResolvedValueOnce({ id: "tenant_2", users: [] } as never);
const result = await adminGetAllTenantsWithUsage({
query: "user_query",
properties: [],
} as never);
expect(dbMock.tenant.findMany).toHaveBeenCalledWith({ select: { id: true }, orderBy: { createdAt: "desc" } });
expect(result.items.map((tenant) => tenant.id)).toEqual(["tenant_1", "tenant_2"]);
expect(result.pagination).toEqual({ page: 1, pageSize: 10, totalItems: 2, totalPages: 1 });
});
it("filters by user and skips tenants that disappear before hydration", async () => {
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([{ id: "tenant_1" }, { id: "tenant_2" }] as never);
vi.mocked(dbMock.tenant.findFirst)
.mockResolvedValueOnce({ id: "tenant_1" } as never)
.mockResolvedValueOnce({ id: "tenant_2" } as never);
vi.mocked(dbMock.tenant.findUnique)
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: "tenant_2", users: [] } as never);
const result = await adminGetAllTenantsWithUsage({ query: "user_query", properties: [] } as never);
expect(result.items.map((tenant) => tenant.id)).toEqual(["tenant_2"]);
expect(result.pagination.totalItems).toBe(2);
expect(dbMock.tenant.findFirst).toHaveBeenCalledTimes(2);
});
it("throws a descriptive error when requireTenant cannot resolve a tenant", async () => {
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce(null);
await expect(requireTenant("tenant_missing")).rejects.toThrow("Tenant not found: tenant_missing");
});
it("returns the resolved tenant when requireTenant finds one", async () => {
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce({ id: "tenant_1" } as never);
await expect(requireTenant("tenant_1")).resolves.toEqual({ id: "tenant_1" });
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "tenant:tenant_1" }));
});
it("returns null early for tenant-with-users and tenant-user lookups without ids", async () => {
await expect(getTenantWithUsers()).resolves.toBeNull();
await expect(getTenantUser()).resolves.toBeNull();
expect(dbMock.tenant.findUnique).not.toHaveBeenCalled();
expect(dbMock.tenantUser.findFirst).not.toHaveBeenCalled();
});
it("returns active member tenants and active tenant-user counts", async () => {
vi.mocked(dbMock.tenant.findMany).mockResolvedValueOnce([{ id: "tenant_1" }] as never);
vi.mocked(dbMock.tenantUser.count).mockResolvedValueOnce(7);
await expect(getMyTenants("user_1")).resolves.toEqual([{ id: "tenant_1" }]);
await expect(getTenantUsersCount("tenant_1")).resolves.toBe(7);
expect(dbMock.tenant.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { active: true, users: { some: { userId: "user_1", status: TenantUserStatus.ACTIVE } } },
orderBy: { name: "asc" },
})
);
expect(dbMock.tenantUser.count).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", status: TenantUserStatus.ACTIVE, user: { active: true } },
});
});
it("scopes tenant users to active members and tenant-local role includes by default", async () => {
vi.mocked(dbMock.tenantUser.findMany).mockResolvedValueOnce([{ id: "tu_1" }] as never);
await expect(getTenantUsers("tenant_1")).resolves.toEqual([{ id: "tu_1" }]);
expect(dbMock.tenantUser.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", status: TenantUserStatus.ACTIVE, user: { active: true } },
include: {
user: {
include: {
roles: { where: { tenantId: "tenant_1" }, include: { role: true } },
},
},
},
});
});
it("skips the active-member status filter when inactive members are requested", async () => {
vi.mocked(dbMock.tenantUser.findMany).mockResolvedValueOnce([] as never);
await getTenantUsers("tenant_1", { includeInactive: true });
expect(dbMock.tenantUser.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: "tenant_1" } }));
});
it("returns an empty member list without touching the database when tenant id is blank", async () => {
await expect(getTenantUsers(null)).resolves.toEqual([]);
expect(dbMock.tenantUser.findMany).not.toHaveBeenCalled();
});
it("adds tenant scope to tenant-user lookup only when a tenant id is provided", async () => {
vi.mocked(dbMock.tenantUser.findFirst).mockResolvedValue({ id: "tu_1" } as never);
await getTenantUser("tu_1");
await getTenantUser("tu_1", "tenant_1");
expect(dbMock.tenantUser.findFirst).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: { id: "tu_1" } }));
expect(dbMock.tenantUser.findFirst).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: { id: "tu_1", tenantId: "tenant_1" } }));
});
it("queries bulk and admin tenant-user projections with tenant-safe includes", async () => {
vi.mocked(dbMock.tenantUser.findMany).mockResolvedValue([] as never);
await getTenantUsersInTenantIds(["tenant_1", "tenant_2"]);
await getAllTenantUsers();
expect(dbMock.tenantUser.findMany).toHaveBeenNthCalledWith(1, {
where: { tenantId: { in: ["tenant_1", "tenant_2"] } },
include: {
tenant: true,
user: { select: expect.any(Object) },
},
});
expect(dbMock.tenantUser.findMany).toHaveBeenNthCalledWith(2, {
include: {
user: {
include: {
roles: { include: { role: true } },
},
},
},
});
});
it("queries tenant-user membership by composite identity and active member predicates", async () => {
vi.mocked(dbMock.tenantUser.findFirst).mockResolvedValue({ id: "tu_1" } as never);
await getTenantUserByIds("tenant_1", "user_1");
await getTenantMember("user_1", "tenant_1");
await getTenantUserType("user_1", "tenant_1");
expect(dbMock.tenantUser.findFirst).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: { tenantId: "tenant_1", userId: "user_1" } }));
expect(dbMock.tenantUser.findFirst).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
where: { userId: "user_1", tenantId: "tenant_1", status: TenantUserStatus.ACTIVE, tenant: { active: true } },
})
);
expect(dbMock.tenantUser.findFirst).toHaveBeenNthCalledWith(3, {
where: { userId: "user_1", tenantId: "tenant_1", status: TenantUserStatus.ACTIVE, tenant: { active: true } },
select: { status: true, type: true },
});
});
it("caches tenant-user simple lookups and converts missing rows to null", async () => {
vi.mocked(dbMock.tenantUser.findFirstOrThrow).mockRejectedValueOnce(new Error("not found"));
await expect(getTenantUserSimple({ tenantId: "tenant_1", userId: "user_1" })).resolves.toBeNull();
expect(cachified).toHaveBeenCalledWith(
expect.objectContaining({
key: "tenantUserSimple:tenant_1:user_1",
ttl: TENANT_SNAPSHOT_SAFETY_TTL_SECONDS * 1_000,
})
);
expect(dbMock.tenantUser.findFirstOrThrow).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", userId: "user_1", status: TenantUserStatus.ACTIVE, tenant: { active: true } },
select: { id: true, type: true },
});
});
it("updates tenant profile data and all slug/id cache keys", async () => {
vi.mocked(dbMock.tenant.update).mockResolvedValueOnce({ id: "tenant_1", slug: "new-slug" } as never);
await updateTenant({ id: "tenant_1", slug: "old-slug" } as never, { name: "Acme", icon: "icon", slug: "new-slug" });
expect(dbMock.tenant.update).toHaveBeenCalledWith({
where: { id: "tenant_1" },
data: {
name: "Acme",
icon: "icon",
slug: "new-slug",
},
});
expect(clearCacheKey).toHaveBeenCalledWith("tenant:old-slug");
expect(clearCacheKey).toHaveBeenCalledWith("tenant:tenant_1");
expect(clearCacheKey).toHaveBeenCalledWith("tenantIdOrSlug:old-slug");
expect(clearCacheKey).toHaveBeenCalledWith("tenantSimple:tenant_1");
});
it("updates the tenant Anrede (du/Sie) without evicting unrelated API-key auth caches", async () => {
vi.mocked(dbMock.tenant.update).mockResolvedValueOnce({ id: "tenant_1", slug: "acme" } as never);
await updateTenantAnrede("tenant_1", "du");
expect(dbMock.tenant.update).toHaveBeenCalledWith({
where: { id: "tenant_1" },
data: { anrede: "du" },
});
expect(clearCacheKey).toHaveBeenCalledWith("tenant:acme");
expect(clearCacheKey).toHaveBeenCalledWith("tenant:tenant_1");
expect(clearCacheKey).toHaveBeenCalledWith("tenantIdOrSlug:tenant_1");
expect(clearCacheKey).toHaveBeenCalledWith("tenantIdOrSlug:acme");
expect(clearCacheKey).toHaveBeenCalledWith("tenantSimple:tenant_1");
expect(clearCacheKeyPrefix).not.toHaveBeenCalledWith("apiKeyHash:");
});
it("creates tenants inactive when requested and emits the tenant-created plugin hook", async () => {
const createdAt = new Date("2026-05-25T12:00:00.000Z");
let tenantContext: string | undefined;
vi.mocked(dbMock.tenant.create).mockImplementationOnce(async () => {
tenantContext = getRlsExecutionContext()?.tenantId;
return { id: "tenant_1", slug: "acme", createdAt } as never;
});
await createTenant({ name: "Acme", icon: "icon", active: false, slug: "acme" });
expect(dbMock.tenant.create).toHaveBeenCalledWith({
data: {
id: expect.any(String),
name: "Acme",
slug: "acme",
icon: "icon",
active: false,
inboundAddresses: { create: [{ address: "acme" }] },
},
});
expect(tenantContext).toBe(dbMock.tenant.create.mock.calls[0][0].data.id);
expect(createTenantSubscription).not.toHaveBeenCalled();
expect(emitPluginHookFireAndForget).toHaveBeenCalledWith(
expect.objectContaining({ name: "tenant.created" }),
{
tenantId: "tenant_1",
slug: "acme",
ownerEmail: null,
plan: null,
createdAt: "2026-05-25T12:00:00.000Z",
},
{ tenantId: "tenant_1", dispatchKey: "tenant:tenant_1:created" }
);
});
it("defaults new tenants active and creates a subscription when a customer id is present", async () => {
vi.mocked(dbMock.tenant.create).mockResolvedValueOnce({
id: "tenant_1",
slug: "acme",
createdAt: new Date("2026-05-25T12:00:00.000Z"),
} as never);
await createTenant({ name: "Acme", subscriptionCustomerId: "cus_1" });
expect(dbMock.tenant.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ active: true }) }));
expect(createTenantSubscription).toHaveBeenCalledWith("tenant_1", "cus_1");
});
it("uses deterministic safe fallbacks for empty and reserved tenant identifiers", async () => {
const createdAt = new Date("2026-07-15T08:00:00.000Z");
vi.mocked(dbMock.tenant.create)
.mockResolvedValueOnce({ id: "tenant_1", slug: "workspace", createdAt } as never)
.mockResolvedValueOnce({ id: "tenant_2", slug: "acme", createdAt } as never)
.mockResolvedValueOnce({ id: "tenant_3", slug: "acme1", createdAt } as never);
await createTenant({ name: "!!!" });
await createTenant({ name: "Acme", slug: "!!!" });
await createTenant({ name: "Acme", slug: "admin" });
expect(dbMock.tenant.create).toHaveBeenNthCalledWith(1, { data: expect.objectContaining({ slug: "workspace" }) });
expect(dbMock.tenant.create).toHaveBeenNthCalledWith(2, { data: expect.objectContaining({ slug: "acme" }) });
expect(dbMock.tenant.create).toHaveBeenNthCalledWith(3, { data: expect.objectContaining({ slug: "acme1" }) });
});
it("runs required tenant setup in the same tenant-scoped transaction and does not emit a hook after rollback", async () => {
vi.mocked(dbMock.tenant.create).mockImplementationOnce(
async ({ data }: { data: { id: string } }) =>
({
id: data.id,
slug: "acme",
createdAt: new Date("2026-05-25T12:00:00.000Z"),
}) as never
);
const setup = vi.fn(async (tenant: Tenant, tx: unknown) => {
expect(getRlsExecutionContext()?.tenantId).toBe(tenant.id);
expect(tx).toBe(db);
throw new Error("provisioning failed");
});
await expect(createTenant({ name: "Acme", setup })).rejects.toThrow("provisioning failed");
expect(setup).toHaveBeenCalledTimes(1);
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
expect(clearCacheKey).toHaveBeenCalledWith("tenant:acme");
expect(emitPluginHookFireAndForget).not.toHaveBeenCalled();
});
it("binds the owner identity before the transaction, returns the setup-updated tenant, and keeps activation as the final setup write", async () => {
const createdAt = new Date("2026-07-15T08:00:00.000Z");
const callOrder: string[] = [];
vi.mocked(dbMock.$transaction).mockImplementationOnce((async (callback: (tx: typeof db) => Promise<unknown>) => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: expect.any(String), userId: "user_owner" });
callOrder.push("transaction");
return await callback(db);
}) as never);
vi.mocked(dbMock.tenant.create).mockImplementationOnce(async ({ data }: { data: { id: string } }) => {
callOrder.push("create-inactive");
return { id: data.id, slug: "acme", active: false, deactivatedReason: "bootstrap_pending", createdAt } as never;
});
vi.mocked(dbMock.tenant.update).mockImplementationOnce(async () => {
callOrder.push("activate");
return { id: "tenant_1", active: true } as never;
});
vi.mocked(dbMock.tenant.findUniqueOrThrow).mockImplementationOnce(async () => {
callOrder.push("reload-final");
return {
id: "tenant_1",
slug: "acme",
active: true,
deactivatedReason: null,
createdAt,
} as never;
});
const result = await createTenant({
name: "Acme",
active: false,
deactivatedReason: "bootstrap_pending",
rlsUserId: "user_owner",
setup: async (tenant, tx) => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: tenant.id, userId: "user_owner" });
expect(tx).toBe(db);
await tx.tenant.update({
where: { id: tenant.id },
data: { active: true, deactivatedReason: null },
});
},
});
expect(dbMock.tenant.create).toHaveBeenCalledWith({
data: expect.objectContaining({ active: false, deactivatedReason: "bootstrap_pending" }),
});
expect(callOrder).toEqual(["transaction", "create-inactive", "activate", "reload-final"]);
expect(result).toMatchObject({ active: true, deactivatedReason: null });
expect(emitPluginHookFireAndForget).toHaveBeenCalledWith(
expect.objectContaining({ name: "tenant.created" }),
expect.objectContaining({ tenantId: "tenant_1" }),
expect.objectContaining({ tenantId: "tenant_1" })
);
});
it("uses a tenant returned by setup without an extra reload", async () => {
const createdAt = new Date("2026-07-15T08:00:00.000Z");
vi.mocked(dbMock.tenant.create).mockResolvedValueOnce({
id: "tenant_1",
slug: "acme",
active: false,
createdAt,
} as never);
vi.mocked(dbMock.tenant.update).mockResolvedValueOnce({
id: "tenant_1",
slug: "acme",
active: true,
createdAt,
} as never);
const result = await createTenant({
name: "Acme",
active: false,
setup: async (tenant, tx) =>
await tx.tenant.update({
where: { id: tenant.id },
data: { active: true },
}),
});
expect(result).toMatchObject({ id: "tenant_1", active: true });
expect(dbMock.tenant.findUniqueOrThrow).not.toHaveBeenCalled();
});
it("isolates an existing matching user from the old tenant and transaction for create and post-commit hook", async () => {
const createdAt = new Date("2026-07-15T08:00:00.000Z");
const oldTransaction = {};
vi.mocked(dbMock.$transaction).mockImplementationOnce((async (callback: (tx: typeof db) => Promise<unknown>) => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: expect.any(String), userId: "user_owner" });
expect(getRlsExecutionContext()?.tenantId).not.toBe("tenant_old");
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
return await callback(db);
}) as never);
vi.mocked(dbMock.tenant.create).mockImplementationOnce(
async ({ data }: { data: { id: string } }) =>
({
id: data.id,
slug: "acme",
active: true,
createdAt,
}) as never
);
vi.mocked(emitPluginHookFireAndForget).mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: expect.any(String), userId: "user_owner" });
expect(getRlsExecutionContext()?.tenantId).not.toBe("tenant_old");
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
});
await runWithRlsContext({ tenantId: "tenant_old", userId: "user_owner" }, () =>
runWithRlsTransaction(oldTransaction, () => createTenant({ name: "Acme", rlsUserId: "user_owner" }))
);
expect(emitPluginHookFireAndForget).toHaveBeenCalledTimes(1);
});
it("isolates a matching user-only transaction before tenant creation and the post-commit hook", async () => {
const createdAt = new Date("2026-07-15T08:00:00.000Z");
const oldTransaction = {};
vi.mocked(dbMock.$transaction).mockImplementationOnce((async (callback: (tx: typeof db) => Promise<unknown>) => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: expect.any(String), userId: "user_owner" });
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
return await callback(db);
}) as never);
vi.mocked(dbMock.tenant.create).mockImplementationOnce(
async ({ data }: { data: { id: string } }) =>
({
id: data.id,
slug: "acme",
active: true,
createdAt,
}) as never
);
vi.mocked(emitPluginHookFireAndForget).mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: expect.any(String), userId: "user_owner" });
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
});
await runWithRlsContext({ userId: "user_owner" }, () =>
runWithRlsTransaction(oldTransaction, () => createTenant({ name: "Acme", rlsUserId: "user_owner" }))
);
expect(emitPluginHookFireAndForget).toHaveBeenCalledTimes(1);
});
it("suppresses the tenant-created hook for ownerless reservations", async () => {
const createdAt = new Date("2026-07-15T08:00:00.000Z");
vi.mocked(dbMock.tenant.create).mockResolvedValueOnce({
id: "tenant_reserved",
slug: "reserved",
active: false,
deactivatedReason: "pending_owner",
createdAt,
} as never);
await createTenant({
name: "Reserved",
active: false,
deactivatedReason: "pending_owner",
emitCreatedHook: false,
});
expect(emitPluginHookFireAndForget).not.toHaveBeenCalled();
});
it("exports the tenant-created hook for an owner claim", async () => {
const tenant = {
id: "tenant_reserved",
slug: "reserved",
createdAt: new Date("2026-07-15T08:00:00.000Z"),
} as Tenant;
await emitTenantCreatedHook(tenant, "user_owner");
expect(emitPluginHookFireAndForget).toHaveBeenCalledWith(
expect.objectContaining({ name: "tenant.created" }),
expect.objectContaining({ tenantId: "tenant_reserved" }),
{ tenantId: "tenant_reserved", dispatchKey: "tenant:tenant_reserved:created" }
);
});
it("retries globally unique tenant identifiers without needing cross-tenant reads", async () => {
const createdAt = new Date("2026-05-25T12:00:00.000Z");
vi.mocked(dbMock.tenant.create)
.mockRejectedValueOnce(Object.assign(new Error("Unique constraint failed"), { code: "P2002", meta: { target: ["slug"] } }))
.mockResolvedValueOnce({ id: "tenant_2", slug: "acme1", createdAt } as never);
await expect(createTenant({ name: "Acme" })).resolves.toMatchObject({ id: "tenant_2", slug: "acme1" });
expect(dbMock.tenant.create).toHaveBeenCalledTimes(2);
expect(dbMock.tenant.create.mock.calls[0][0].data).toMatchObject({
slug: "acme",
inboundAddresses: { create: [{ address: "acme" }] },
});
expect(dbMock.tenant.create.mock.calls[1][0].data).toMatchObject({
slug: "acme1",
inboundAddresses: { create: [{ address: "acme" }] },
});
expect(clearCacheKey).not.toHaveBeenCalledWith("tenant:acme");
});
it("rejects a colliding user-selected slug instead of silently suffixing it", async () => {
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(
Object.assign(new Error("Unique constraint failed"), {
code: "P2002",
meta: { target: ["slug"] },
})
);
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).rejects.toBeInstanceOf(TenantSlugCollisionError);
expect(dbMock.tenant.create).toHaveBeenCalledTimes(1);
expect(dbMock.tenant.create).toHaveBeenCalledWith({ data: expect.objectContaining({ slug: "chosen" }) });
});
it("classifies an adapter-pg slug field collision for an explicit tenant slug", async () => {
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(adapterPgUniqueConstraintError({ fields: ["slug"] }));
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).rejects.toBeInstanceOf(TenantSlugCollisionError);
expect(dbMock.tenant.create).toHaveBeenCalledTimes(1);
});
it("classifies an adapter-pg constraint name for an explicit tenant slug", async () => {
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(adapterPgUniqueConstraintError({ name: "Tenant_slug_key" }));
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).rejects.toBeInstanceOf(TenantSlugCollisionError);
expect(dbMock.tenant.create).toHaveBeenCalledTimes(1);
});
it("uses the exact PostgreSQL constraint name when adapter-pg omits its parsed constraint", async () => {
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(
adapterPgUniqueConstraintError(undefined, {}, 'duplicate key value violates unique constraint "Tenant_slug_key"')
);
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).rejects.toBeInstanceOf(TenantSlugCollisionError);
expect(dbMock.tenant.create).toHaveBeenCalledTimes(1);
});
it("fails closed when an unparsed adapter-pg message does not name an exact known constraint", async () => {
const collision = adapterPgUniqueConstraintError(undefined, {}, 'duplicate key value violates unique constraint "Other_slug_key"');
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(collision);
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).rejects.toMatchObject({
name: "TenantIdentifierCollisionError",
cause: collision,
});
expect(dbMock.tenant.create).toHaveBeenCalledTimes(1);
});
it("keeps a user-selected slug while retrying an inbound-address collision", async () => {
const createdAt = new Date("2026-05-25T12:00:00.000Z");
vi.mocked(dbMock.tenant.create)
.mockRejectedValueOnce(
Object.assign(new Error("Unique constraint failed"), {
code: "P2002",
meta: { target: "TenantInboundAddress_address_key" },
})
)
.mockResolvedValueOnce({ id: "tenant_2", slug: "chosen", createdAt } as never);
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).resolves.toMatchObject({
slug: "chosen",
});
expect(dbMock.tenant.create.mock.calls[0][0].data).toMatchObject({
slug: "chosen",
inboundAddresses: { create: [{ address: "acme" }] },
});
expect(dbMock.tenant.create.mock.calls[1][0].data).toMatchObject({
slug: "chosen",
inboundAddresses: { create: [{ address: "acme1" }] },
});
});
it("only suffixes the inbound address for an adapter-pg address field collision", async () => {
const createdAt = new Date("2026-05-25T12:00:00.000Z");
vi.mocked(dbMock.tenant.create)
.mockRejectedValueOnce(adapterPgUniqueConstraintError({ fields: ["address"] }))
.mockResolvedValueOnce({ id: "tenant_2", slug: "chosen", createdAt } as never);
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).resolves.toMatchObject({
slug: "chosen",
});
expect(dbMock.tenant.create.mock.calls[0][0].data).toMatchObject({
slug: "chosen",
inboundAddresses: { create: [{ address: "acme" }] },
});
expect(dbMock.tenant.create.mock.calls[1][0].data).toMatchObject({
slug: "chosen",
inboundAddresses: { create: [{ address: "acme1" }] },
});
});
it("allocates a new tenant id for an adapter-pg id field collision", async () => {
const createdAt = new Date("2026-05-25T12:00:00.000Z");
vi.mocked(dbMock.tenant.create)
.mockRejectedValueOnce(adapterPgUniqueConstraintError({ fields: ["id"] }))
.mockResolvedValueOnce({ id: "tenant_2", slug: "acme", createdAt } as never);
await expect(createTenant({ name: "Acme" })).resolves.toMatchObject({ id: "tenant_2" });
expect(dbMock.tenant.create).toHaveBeenCalledTimes(2);
expect(dbMock.tenant.create.mock.calls[0][0].data.id).not.toBe(dbMock.tenant.create.mock.calls[1][0].data.id);
expect(dbMock.tenant.create.mock.calls[1][0].data).toMatchObject({
slug: "acme",
inboundAddresses: { create: [{ address: "acme" }] },
});
});
it("fails closed for an unknown unique constraint instead of rewriting identifiers", async () => {
const collision = Object.assign(new Error("Unique constraint failed"), {
code: "P2002",
meta: { target: ["unexpectedUniqueField"] },
});
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(collision);
await expect(createTenant({ name: "Acme" })).rejects.toMatchObject({
name: "TenantIdentifierCollisionError",
cause: collision,
});
expect(dbMock.tenant.create).toHaveBeenCalledTimes(1);
});
it("fails closed for an unknown adapter-pg constraint even when legacy metadata names a slug", async () => {
const collision = adapterPgUniqueConstraintError({ fields: ["billingAddress"] }, { target: ["slug"] });
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(collision);
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).rejects.toMatchObject({
name: "TenantIdentifierCollisionError",
cause: collision,
});
expect(dbMock.tenant.create).toHaveBeenCalledTimes(1);
});
it("fails closed when adapter-pg constraint fields and name disagree", async () => {
const collision = adapterPgUniqueConstraintError({
fields: ["slug"],
name: "TenantInboundAddress_address_key",
});
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(collision);
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).rejects.toMatchObject({
name: "TenantIdentifierCollisionError",
cause: collision,
});
expect(dbMock.tenant.create).toHaveBeenCalledTimes(1);
});
it.each([
[
"a non-unique driver error",
() =>
Object.assign(new Error("Unique constraint failed"), {
code: "P2002",
meta: { driverAdapterError: { cause: { kind: "ForeignKeyConstraintViolation", constraint: "Tenant_slug_key" } } },
}),
],
[
"an invalid original PostgreSQL code",
() =>
Object.assign(new Error("Unique constraint failed"), {
code: "P2002",
meta: {
driverAdapterError: {
cause: {
kind: "UniqueConstraintViolation",
originalCode: "23503",
originalMessage: 'duplicate key value violates unique constraint "Tenant_slug_key"',
},
},
},
}),
],
["an empty driver constraint record", () => adapterPgUniqueConstraintError({})],
["empty driver constraint fields", () => adapterPgUniqueConstraintError({ fields: [] })],
["a non-string driver constraint name", () => adapterPgUniqueConstraintError({ name: 42 })],
["a malformed legacy target", () => Object.assign(new Error("Unique constraint failed"), { code: "P2002", meta: { target: [] } })],
])("fails closed for %s", async (_label, createCollision) => {
const collision = createCollision();
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(collision);
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).rejects.toMatchObject({
name: "TenantIdentifierCollisionError",
cause: collision,
});
expect(dbMock.tenant.create).toHaveBeenCalledTimes(1);
});
it("classifies a direct adapter-pg constraint string", async () => {
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(adapterPgUniqueConstraintError("Tenant_slug_key"));
await expect(createTenant({ name: "Acme", slug: "chosen", rejectSlugCollision: true })).rejects.toBeInstanceOf(TenantSlugCollisionError);
});
it("replays setup for a visible preallocated tenant instead of creating a duplicate", async () => {
const tenantId = "7ee71103-e2be-5a5d-921c-b2d6d22c9435";
const existing = {
id: tenantId,
slug: "acme",
active: true,
createdAt: new Date("2026-07-15T08:00:00.000Z"),
} as Tenant;
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(Object.assign(new Error("Unique constraint failed"), { code: "P2002" }));
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce(existing as never);
const setup = vi.fn(async (tenant: Tenant) => tenant);
const validateExistingReplay = vi.fn(async () => undefined);
await expect(
createTenant({
name: "Acme",
tenantId,
rlsUserId: "user_owner",
setup,
validateExistingReplay,
})
).resolves.toBe(existing);
expect(dbMock.tenant.create).toHaveBeenCalledTimes(1);
expect(dbMock.tenant.create).toHaveBeenCalledWith({ data: expect.objectContaining({ id: tenantId }) });
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { id: tenantId } });
expect(validateExistingReplay).toHaveBeenCalledWith(existing, db);
expect(setup).toHaveBeenCalledWith(existing, db);
expect(clearCacheKey).not.toHaveBeenCalledWith("tenant:acme");
expect(emitPluginHookFireAndForget).not.toHaveBeenCalled();
});
it("never runs setup when a preallocated tenant fails replay validation", async () => {
const tenantId = "7ee71103-e2be-5a5d-921c-b2d6d22c9435";
const existing = {
id: tenantId,
slug: "foreign",
active: true,
createdAt: new Date("2026-07-15T08:00:00.000Z"),
} as Tenant;
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(Object.assign(new Error("Unique constraint failed"), { code: "P2002" }));
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce(existing as never);
const setup = vi.fn();
await expect(
createTenant({
name: "Acme",
tenantId,
rlsUserId: "user_owner",
setup,
validateExistingReplay: async () => {
throw new Error("invalid creation replay");
},
})
).rejects.toThrow("invalid creation replay");
expect(setup).not.toHaveBeenCalled();
expect(emitPluginHookFireAndForget).not.toHaveBeenCalled();
});
it("fails closed when a colliding preallocated tenant is not visible", async () => {
const collision = Object.assign(new Error("Unique constraint failed"), { code: "P2002" });
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(collision);
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce(null);
await expect(
createTenant({
name: "Acme",
tenantId: "7ee71103-e2be-5a5d-921c-b2d6d22c9435",
rlsUserId: "user_owner",
validateExistingReplay: async () => undefined,
})
).rejects.toMatchObject({ name: "TenantIdentifierCollisionError", cause: collision });
});
it("requires explicit replay validation for an existing preallocated tenant", async () => {
const existing = { id: "7ee71103-e2be-5a5d-921c-b2d6d22c9435", slug: "acme" } as Tenant;
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(Object.assign(new Error("Unique constraint failed"), { code: "P2002" }));
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce(existing as never);
await expect(createTenant({ name: "Acme", tenantId: existing.id, rlsUserId: "user_owner" })).rejects.toThrow(
"Preallocated tenant replay requires explicit validation"
);
});
it("returns a validated preallocated tenant without rerunning optional setup", async () => {
const existing = { id: "7ee71103-e2be-5a5d-921c-b2d6d22c9435", slug: "acme" } as Tenant;
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(Object.assign(new Error("Unique constraint failed"), { code: "P2002" }));
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce(existing as never);
await expect(createTenant({ name: "Acme", tenantId: existing.id, rlsUserId: "user_owner", validateExistingReplay: async () => undefined })).resolves.toBe(
existing
);
});
it("reloads a validated preallocated tenant when replay setup returns no row", async () => {
const existing = { id: "7ee71103-e2be-5a5d-921c-b2d6d22c9435", slug: "acme", active: false } as Tenant;
const activated = { ...existing, active: true } as Tenant;
vi.mocked(dbMock.tenant.create).mockRejectedValueOnce(Object.assign(new Error("Unique constraint failed"), { code: "P2002" }));
vi.mocked(dbMock.tenant.findUnique).mockResolvedValueOnce(existing as never);
vi.mocked(dbMock.tenant.findUniqueOrThrow).mockResolvedValueOnce(activated as never);
await expect(
createTenant({
name: "Acme",
tenantId: existing.id,
rlsUserId: "user_owner",
validateExistingReplay: async () => undefined,
setup: async () => undefined,
})
).resolves.toBe(activated);
});
it("creates tenant users as active invited members and assigns each requested role", async () => {
vi.mocked(dbMock.tenantUser.create).mockResolvedValueOnce({ id: "tu_1", tenantId: "tenant_1", userId: "user_1" } as never);
await createTenantUser({ tenantId: "tenant_1", userId: "user_1", type: 0 }, [{ id: "role_admin" }, { id: "role_member" }] as never);
expect(dbMock.tenantUser.create).toHaveBeenCalledWith({
data: {
tenantId: "tenant_1",
userId: "user_1",
type: 0,
joined: TenantUserJoined.JOINED_BY_INVITATION,
status: TenantUserStatus.ACTIVE,
},
});
expect(createUserRole).toHaveBeenCalledWith("user_1", "role_admin", "tenant_1");
expect(createUserRole).toHaveBeenCalledWith("user_1", "role_member", "tenant_1");
});
it("does not delete cross-tenant membership when a tenant-scoped delete misses", async () => {
vi.mocked(dbMock.tenantUser.findFirst).mockResolvedValueOnce(null);
await expect(deleteTenantUser("tu_1", "tenant_1")).resolves.toEqual({ count: 0 });
expect(dbMock.tenantUser.deleteMany).not.toHaveBeenCalled();
expect(dbMock.$transaction).not.toHaveBeenCalled();
});
it("deletes tenant-scoped membership, roles, groups, and user-role cache together", async () => {
vi.mocked(dbMock.tenantUser.findFirst).mockResolvedValueOnce({ tenantId: "tenant_1", userId: "user_1" } as never);
vi.mocked(dbMock.tenantUser.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
vi.mocked(dbMock.userRole.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 3 } as never);
await expect(deleteTenantUser("tu_1", "tenant_1")).resolves.toEqual({ count: 1 });
expect(dbMock.tenantUser.deleteMany).toHaveBeenCalledWith({ where: { id: "tu_1", tenantId: "tenant_1" } });
expect(dbMock.userRole.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", userId: "user_1" } });
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({
where: { userId: "user_1", group: { tenantId: "tenant_1" } },
});
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
});
it("cleans role and group links after an unscoped tenant-user delete when the deleted row has a tenant", async () => {
vi.mocked(dbMock.tenantUser.delete).mockResolvedValueOnce({ id: "tu_1", tenantId: "tenant_1", userId: "user_1" } as never);
vi.mocked(dbMock.userRole.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 3 } as never);
await deleteTenantUser("tu_1");
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
});
it("returns an unscoped tenant-user delete without cleanup when the deleted row has no tenant", async () => {
vi.mocked(dbMock.tenantUser.delete).mockResolvedValueOnce({ id: "tu_1", tenantId: null, userId: "user_1" } as never);
await expect(deleteTenantUser("tu_1")).resolves.toEqual({ id: "tu_1", tenantId: null, userId: "user_1" });
expect(dbMock.$transaction).not.toHaveBeenCalled();
expect(clearCacheKey).not.toHaveBeenCalledWith("userRoles:user_1:null");
});
it("deletes tenants with dependent records included", async () => {
vi.mocked(dbMock.tenant.delete).mockResolvedValueOnce({ id: "tenant_1", slug: "acme" } as never);
await deleteTenant("tenant_1");
expect(dbMock.tenant.delete).toHaveBeenCalledWith({
where: { id: "tenant_1" },
include: {
subscription: true,
users: true,
invitations: true,
logs: true,
apiKeys: true,
userRoles: true,
},
});
});
it("updates deactivation state and clears tenant identity cache keys", async () => {
vi.mocked(dbMock.tenant.update).mockResolvedValueOnce({ id: "tenant_1", slug: "acme" } as never);
await updateTenantDeactivated("tenant_1", { active: false, deactivatedReason: "billing" });
expect(dbMock.tenant.update).toHaveBeenCalledWith({
where: { id: "tenant_1" },
data: { active: false, deactivatedReason: "billing" },
});
expect(clearCacheKey).toHaveBeenCalledWith("tenant:acme");
expect(clearCacheKey).toHaveBeenCalledWith("tenant:tenant_1");
expect(clearCacheKey).toHaveBeenCalledWith("tenantIdOrSlug:acme");
expect(clearCacheKey).toHaveBeenCalledWith("tenantSimple:tenant_1");
});
});