// @vitest-environment node import { createHash } from "node:crypto"; import { beforeEach, describe, expect, it, vi } from "vitest"; import type { Prisma, TenantUserInvitation } from "@hivegrid/db/prisma-browser"; import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { hashWorkspaceOwnerInvitationMailContent } from "@hivegrid/db/workspace-owner-invite-mail-contract.server"; import { TenantUserType } from "~/application/enums/tenants/TenantUserType"; const dbMock = vi.hoisted(() => ({ $transaction: vi.fn() })); const issuanceMock = vi.hoisted(() => ({ issueReservedOwnerInvitationWithTx: vi.fn() })); vi.mock("~/utils/db.server", () => ({ db: dbMock })); vi.mock("./ownerInvitationIssuance.server", async (importOriginal) => { const original = await importOriginal(); return { ...original, issueReservedOwnerInvitationWithTx: issuanceMock.issueReservedOwnerInvitationWithTx }; }); import { hashOwnerInvitationIssuanceKey, type ReservedOwnerInvitationDraft } from "./ownerInvitationIssuance.server"; import { getReservedOwnerInvitationReissueTarget, reissueReservedOwnerInvitation } from "./ownerInvitationReissue.server"; const TENANT_ID = "tenant_reserved"; const OPERATOR_ID = "operator_1"; const SOURCE_ID = "invite_001"; const ISSUANCE_KEY = "93923898-e834-41e9-9e2c-0c03080e91df"; const TOKEN = "r".repeat(43); type TestOutbox = { tenantId: string; eventType: string; payload: Prisma.JsonValue; status: string; }; function ownerInvitation(overrides: Partial = {}): TenantUserInvitation { const token = "s".repeat(43); return { id: SOURCE_ID, tenantId: TENANT_ID, email: "owner@heizkraft.example", firstName: "Mara", lastName: "König", type: TenantUserType.OWNER, pending: true, status: "pending", tokenHash: createHash("sha256").update(token).digest("hex"), tokenPrefix: token.slice(0, 12), expiresAt: new Date("2099-01-01T00:00:00.000Z"), acceptedAt: null, revokedAt: null, createdUserId: null, fromUserId: "operator_initial", acceptedByUserId: null, revokedByUserId: null, ...overrides, }; } function draft(overrides: Partial = {}): ReservedOwnerInvitationDraft { return { issuanceKey: ISSUANCE_KEY, email: "owner@heizkraft.example", firstName: "Mara", lastName: "König", fromUserId: OPERATOR_ID, token: TOKEN, mail: { subject: "Einladung", html: `Einladung annehmen`, }, ...overrides, }; } function ownerOutbox( invitation: TenantUserInvitation, issuanceKey: string, mail: { rawToken: string; subject: string; html: string } = { rawToken: "s".repeat(43), subject: "Einladung", html: `Einladung annehmen`, } ): TestOutbox { return { tenantId: TENANT_ID, eventType: "mail.transactional.send", status: "PENDING", payload: { tenantId: TENANT_ID, to: [invitation.email], subject: mail.subject, html: mail.html, metadata: { source: "workspace-owner-invitation", alias: "user-invitation", invitationId: invitation.id, invitationTokenHash: invitation.tokenHash, issuanceKeyHash: hashOwnerInvitationIssuanceKey(issuanceKey), mailContentHash: hashWorkspaceOwnerInvitationMailContent({ recipient: invitation.email, subject: mail.subject, html: mail.html, rawToken: mail.rawToken, invitationTokenHash: invitation.tokenHash!, }), }, }, }; } function buildHarness( options: { tenant?: { id: string; name: string; active: boolean; deactivatedReason: string | null; _count: { users: number } } | null; invitations?: TenantUserInvitation[]; outboxes?: Map; } = {} ) { const tenant = options.tenant === undefined ? { id: TENANT_ID, name: "Heizkraft GmbH", active: false, deactivatedReason: "pending_owner", _count: { users: 0 } } : options.tenant; const invitations = options.invitations ?? [ownerInvitation()]; const outboxes = options.outboxes ?? new Map(); const tx = { $executeRaw: vi.fn().mockResolvedValue(1), tenant: { findUnique: vi.fn().mockImplementation(async () => { expect(getRlsExecutionContext()).toMatchObject({ tenantId: TENANT_ID, userId: OPERATOR_ID }); return tenant; }), }, tenantUserInvitation: { findMany: vi.fn().mockImplementation(async () => [...invitations].sort((left, right) => right.id.localeCompare(left.id))), updateMany: vi.fn().mockImplementation(async ({ where, data }: { where: Record; data: Record }) => { const invitation = invitations.find((candidate) => candidate.id === where.id); if ( !invitation || invitation.tenantId !== where.tenantId || invitation.status !== "pending" || !invitation.pending || invitation.acceptedAt !== null || invitation.revokedAt !== null || invitation.createdUserId !== null ) { return { count: 0 }; } Object.assign(invitation, data); return { count: 1 }; }), }, outboxEvent: { findUnique: vi.fn().mockImplementation(async ({ where }: { where: { dispatchKey: string } }) => outboxes.get(where.dispatchKey) ?? null), }, }; return { tx, tenant, invitations, outboxes }; } function installTransactionHarness(tx: ReturnType["tx"]): void { let tail = Promise.resolve(); dbMock.$transaction.mockImplementation((callback: (transaction: typeof tx) => Promise) => { const result = tail.then(() => callback(tx)); tail = result.then( () => undefined, () => undefined ); return result; }); } function runAsOperator(callback: () => T): T { return runWithRlsContext({ userId: OPERATOR_ID }, callback); } describe("reserved OWNER invitation reissue", () => { beforeEach(() => { vi.clearAllMocks(); issuanceMock.issueReservedOwnerInvitationWithTx.mockResolvedValue({ invitationId: "invite_002", replayed: false }); }); it("resolves one case-normalized identity while isolating an unrelated tenant context", async () => { const harness = buildHarness({ invitations: [ownerInvitation({ email: " Owner@Heizkraft.Example " })] }); installTransactionHarness(harness.tx); const target = await runWithRlsContext({ userId: OPERATOR_ID, tenantId: "tenant_previous" }, async () => { const result = await getReservedOwnerInvitationReissueTarget({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID }); expect(getRlsExecutionContext()).toMatchObject({ userId: OPERATOR_ID, tenantId: "tenant_previous" }); return result; }); expect(target).toEqual({ invitationId: SOURCE_ID, tenantName: "Heizkraft GmbH", email: "owner@heizkraft.example", firstName: "Mara", lastName: "König", }); expect(harness.tx.tenantUserInvitation.findMany).toHaveBeenCalledWith( expect.objectContaining({ where: { tenantId: TENANT_ID, type: TenantUserType.OWNER }, take: 3 }) ); }); it("requires the current RLS user to be the exact operator", async () => { const harness = buildHarness(); installTransactionHarness(harness.tx); await expect(getReservedOwnerInvitationReissueTarget({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID })).rejects.toMatchObject({ code: "foundation.not_found", }); await expect( runWithRlsContext({ userId: "operator_other" }, () => reissueReservedOwnerInvitation({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID, sourceInvitationId: SOURCE_ID, ownerInvitation: draft(), }) ) ).rejects.toMatchObject({ code: "foundation.not_found" }); expect(dbMock.$transaction).not.toHaveBeenCalled(); }); it.each([ ["active", { id: TENANT_ID, name: "Heizkraft GmbH", active: true, deactivatedReason: null, _count: { users: 0 } }], ["wrong reason", { id: TENANT_ID, name: "Heizkraft GmbH", active: false, deactivatedReason: "billing", _count: { users: 0 } }], ["membership exists", { id: TENANT_ID, name: "Heizkraft GmbH", active: false, deactivatedReason: "pending_owner", _count: { users: 1 } }], ])("refuses an ownerless reservation whose tenant is %s", async (_label, tenant) => { const harness = buildHarness({ tenant }); installTransactionHarness(harness.tx); await expect( runAsOperator(() => reissueReservedOwnerInvitation({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID, sourceInvitationId: SOURCE_ID, ownerInvitation: draft(), }) ) ).rejects.toMatchObject({ code: "foundation.not_found" }); expect(harness.tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled(); expect(issuanceMock.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled(); }); it("fails closed for ambiguous identities or a capability already bound to a user", async () => { const ambiguous = buildHarness({ invitations: [ownerInvitation({ id: "invite_002", email: "other@heizkraft.example" }), ownerInvitation()], }); installTransactionHarness(ambiguous.tx); await expect(runAsOperator(() => getReservedOwnerInvitationReissueTarget({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID }))).rejects.toMatchObject({ code: "foundation.not_found", }); const bound = buildHarness({ invitations: [ownerInvitation({ createdUserId: "owner_user" })] }); installTransactionHarness(bound.tx); await expect(runAsOperator(() => getReservedOwnerInvitationReissueTarget({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID }))).rejects.toMatchObject({ code: "foundation.not_found", }); }); it("locks the reservation, conditionally revokes an active source, and then issues the replacement", async () => { const harness = buildHarness(); installTransactionHarness(harness.tx); await expect( runAsOperator(() => reissueReservedOwnerInvitation({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID, sourceInvitationId: SOURCE_ID, ownerInvitation: draft(), }) ) ).resolves.toEqual({ invitationId: "invite_002", replayed: false }); expect(harness.tx.$executeRaw).toHaveBeenCalledOnce(); expect(String(harness.tx.$executeRaw.mock.calls[0]?.[0])).toContain("pg_advisory_xact_lock"); expect(harness.tx.tenantUserInvitation.updateMany).toHaveBeenCalledWith({ where: expect.objectContaining({ id: SOURCE_ID, tenantId: TENANT_ID, type: TenantUserType.OWNER, pending: true, status: "pending", createdUserId: null, acceptedAt: null, revokedAt: null, }), data: expect.objectContaining({ pending: false, status: "revoked", revokedByUserId: OPERATOR_ID }), }); expect(issuanceMock.issueReservedOwnerInvitationWithTx).toHaveBeenCalledWith(harness.tx, { tenantId: TENANT_ID, ...draft(), }); expect(harness.tx.tenantUserInvitation.updateMany.mock.invocationCallOrder[0]).toBeLessThan( issuanceMock.issueReservedOwnerInvitationWithTx.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY ); }); it("rotates an expired source and does not depend on it still being active", async () => { const harness = buildHarness({ invitations: [ownerInvitation({ expiresAt: new Date("2000-01-01T00:00:00.000Z") })] }); installTransactionHarness(harness.tx); await expect( runAsOperator(() => reissueReservedOwnerInvitation({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID, sourceInvitationId: SOURCE_ID, ownerInvitation: draft(), }) ) ).resolves.toEqual({ invitationId: "invite_002", replayed: false }); expect(harness.tx.tenantUserInvitation.updateMany).toHaveBeenCalledOnce(); expect(issuanceMock.issueReservedOwnerInvitationWithTx).toHaveBeenCalledOnce(); }); it("rotates a delivery-failed source only through a fresh OWNER capability", async () => { const harness = buildHarness({ invitations: [ ownerInvitation({ pending: false, status: "delivery_failed", revokedAt: new Date("2026-07-15T10:00:00.000Z"), revokedByUserId: null, }), ], }); installTransactionHarness(harness.tx); await expect( runAsOperator(() => reissueReservedOwnerInvitation({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID, sourceInvitationId: SOURCE_ID, ownerInvitation: draft(), }) ) ).resolves.toEqual({ invitationId: "invite_002", replayed: false }); expect(harness.tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled(); expect(issuanceMock.issueReservedOwnerInvitationWithTx).toHaveBeenCalledOnce(); }); it("accepts a stale source only when the active replacement proves the same issuance key", async () => { const oldSource = ownerInvitation({ pending: false, status: "revoked", revokedAt: new Date("2026-07-15T10:00:00.000Z"), revokedByUserId: OPERATOR_ID, }); const replacement = ownerInvitation({ id: "invite_002", fromUserId: OPERATOR_ID }); const outboxes = new Map([["mail:workspace-owner-invite:invite_002", ownerOutbox(replacement, ISSUANCE_KEY)]]); const harness = buildHarness({ invitations: [replacement, oldSource], outboxes }); installTransactionHarness(harness.tx); await expect( runAsOperator(() => reissueReservedOwnerInvitation({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID, sourceInvitationId: SOURCE_ID, ownerInvitation: draft(), }) ) ).resolves.toEqual({ invitationId: replacement.id, replayed: true }); expect(harness.tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled(); expect(issuanceMock.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled(); }); it("replays an HTTP response-loss retry with a freshly rendered token without rotating the active replacement", async () => { const oldSource = ownerInvitation({ pending: false, status: "revoked", revokedAt: new Date("2026-07-15T10:00:00.000Z"), revokedByUserId: OPERATOR_ID, }); const replacement = ownerInvitation({ id: "invite_002", fromUserId: OPERATOR_ID }); const outboxes = new Map([["mail:workspace-owner-invite:invite_002", ownerOutbox(replacement, ISSUANCE_KEY)]]); const harness = buildHarness({ invitations: [replacement, oldSource], outboxes }); installTransactionHarness(harness.tx); const freshlyRenderedDraft = draft({ token: "fresh-response-loss-token".padEnd(43, "x"), mail: { subject: "Einladung", html: `Einladung annehmen`, }, }); await expect( runAsOperator(() => reissueReservedOwnerInvitation({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID, sourceInvitationId: replacement.id, ownerInvitation: freshlyRenderedDraft, }) ) ).resolves.toEqual({ invitationId: replacement.id, replayed: true }); expect(harness.tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled(); expect(issuanceMock.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled(); }); it("fails closed when a stale source races with a different issuance key", async () => { const oldSource = ownerInvitation({ pending: false, status: "revoked", revokedAt: new Date("2026-07-15T10:00:00.000Z"), revokedByUserId: OPERATOR_ID, }); const replacement = ownerInvitation({ id: "invite_002", fromUserId: OPERATOR_ID }); const outboxes = new Map([["mail:workspace-owner-invite:invite_002", ownerOutbox(replacement, "different-key")]]); const harness = buildHarness({ invitations: [replacement, oldSource], outboxes }); installTransactionHarness(harness.tx); await expect( runAsOperator(() => reissueReservedOwnerInvitation({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID, sourceInvitationId: SOURCE_ID, ownerInvitation: draft(), }) ) ).rejects.toMatchObject({ code: "foundation.idempotency_conflict" }); expect(harness.tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled(); expect(issuanceMock.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled(); }); it("serializes concurrent same-key rotations and replays the one replacement", async () => { const harness = buildHarness(); installTransactionHarness(harness.tx); issuanceMock.issueReservedOwnerInvitationWithTx.mockImplementation(async (_tx, input) => { const existing = harness.invitations.find((invitation) => invitation.id === "invite_002"); if (existing) { return { invitationId: existing.id, replayed: true }; } const replacement = ownerInvitation({ id: "invite_002", email: input.email, firstName: input.firstName, lastName: input.lastName, fromUserId: input.fromUserId, tokenHash: createHash("sha256").update(input.token).digest("hex"), tokenPrefix: input.token.slice(0, 12), }); harness.invitations.push(replacement); harness.outboxes.set( "mail:workspace-owner-invite:invite_002", ownerOutbox(replacement, input.issuanceKey, { rawToken: input.token, subject: input.mail.subject, html: input.mail.html, }) ); return { invitationId: replacement.id, replayed: false }; }); const request = () => runAsOperator(() => reissueReservedOwnerInvitation({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID, sourceInvitationId: SOURCE_ID, ownerInvitation: draft(), }) ); const results = await Promise.all([request(), request()]); expect(results).toEqual( expect.arrayContaining([ { invitationId: "invite_002", replayed: false }, { invitationId: "invite_002", replayed: true }, ]) ); expect(harness.tx.tenantUserInvitation.updateMany).toHaveBeenCalledOnce(); expect(issuanceMock.issueReservedOwnerInvitationWithTx).toHaveBeenCalledOnce(); }); });