import { describe, expect, it, vi } from "vitest"; import { AUDIT_EVENT_OUTBOX_TYPE, auditEvent, buildAuditEventCreateData, createAuditEvent, publishAuditEventViaOutbox, sanitizeAuditMetadata, type AuditEventWriterClient } from "./audit-events.server.js"; import type { AuditEvent, OutboxEvent } from "../generated/prisma/client/client.js"; import type { OutboxPublisherTransaction } from "./outbox.js"; function createAuditEventClient(opts: { previousHash?: string | null } = {}): AuditEventWriterClient { return { auditEvent: { create: vi.fn( async ({ data }) => ({ id: "audit_event_1", createdAt: new Date("2026-05-11T12:00:00.000Z"), ...data, }) as AuditEvent ), findFirst: vi.fn(async () => ({ eventHash: opts.previousHash ?? null })), }, }; } describe("audit event persistence", () => { it("normalizes nullable fields and defaults actorType to system", async () => { const client = createAuditEventClient(); await expect( createAuditEvent( { action: "widget.created", }, client ) ).resolves.toMatchObject({ actorType: "system", action: "widget.created", tenantId: null, actorId: null, targetType: null, targetId: null, requestId: null, metadata: null, outcome: "success", dataSensitivity: "internal", regulatoryScope: [], eventHash: expect.stringMatching(/^[0-9a-f]{64}$/), }); const call = (client.auditEvent.create as ReturnType).mock.calls[0]?.[0]; expect(call?.data).toMatchObject({ tenantId: null, actorId: null, actorType: "system", action: "widget.created", targetType: null, targetId: null, requestId: null, metadata: null, outcome: "success", dataSensitivity: "internal", regulatoryScope: [], previousHash: null, }); expect(call?.data?.eventHash).toMatch(/^[0-9a-f]{64}$/); }); it("trims actorType before falling back and preserves provided values", async () => { const client = createAuditEventClient(); await auditEvent( { tenantId: "tenant_1", actorId: "user_1", actorType: " user ", action: "widget.updated", targetType: "widget", targetId: "widget_1", requestId: "request_1", metadata: { changed: true, token: "secret-token" }, }, client ); const call = (client.auditEvent.create as ReturnType).mock.calls[0]?.[0]; expect(call?.data).toMatchObject({ tenantId: "tenant_1", actorId: "user_1", actorType: "user", action: "widget.updated", targetType: "widget", targetId: "widget_1", requestId: "request_1", metadata: { changed: true, token: "[REDACTED]" }, }); }); it("redacts nested secret-like audit metadata without mutating the original object", () => { const metadata = { nested: { authorization: "Bearer secret", kept: "value" }, notes: "token=secret-token" }; expect(sanitizeAuditMetadata(metadata)).toEqual({ nested: { authorization: "[REDACTED]", kept: "value" }, notes: "token=[REDACTED]", }); expect(metadata.nested.authorization).toBe("Bearer secret"); }); it("builds Prisma create data without mutating input objects", () => { const metadata = { value: "kept" }; const input = { action: "thing.changed", actorType: " ", metadata, }; expect(buildAuditEventCreateData(input)).toEqual({ tenantId: null, actorId: null, actorType: "system", actorEmail: null, actorIp: null, actorUserAgent: null, action: "thing.changed", targetType: null, targetId: null, requestId: null, sourceModule: null, outcome: "success", dataSensitivity: "internal", regulatoryScope: [], metadata, }); expect(input).toEqual({ action: "thing.changed", actorType: " ", metadata }); }); it("captures compliance fields (ip, ua, regulatoryScope) and links hash chain", async () => { const client = createAuditEventClient({ previousHash: "deadbeef" }); await createAuditEvent( { tenantId: "tenant_1", actorId: "user_1", actorType: "user", actorIp: "10.0.0.1", actorUserAgent: "vitest/1.0", action: "user.read", targetType: "user", targetId: "user_2", sourceModule: "auth", outcome: "success", dataSensitivity: "pii", regulatoryScope: ["gdpr", "soc2"], metadata: { reason: "login" }, }, client ); const call = (client.auditEvent.create as ReturnType).mock.calls[0]?.[0]; expect(call?.data).toMatchObject({ actorIp: "10.0.0.1", actorUserAgent: "vitest/1.0", sourceModule: "auth", outcome: "success", dataSensitivity: "pii", regulatoryScope: ["gdpr", "soc2"], previousHash: "deadbeef", }); expect(call?.data?.eventHash).toMatch(/^[0-9a-f]{64}$/); }); it("normalizes invalid outcome/sensitivity to safe defaults", () => { const data = buildAuditEventCreateData({ action: "x", outcome: "haxx" as unknown as "success", dataSensitivity: "ULTRA" as unknown as "pii", regulatoryScope: ["GDPR", "gdpr", ""] as unknown as ReadonlyArray<"gdpr">, }); expect(data.outcome).toBe("success"); expect(data.dataSensitivity).toBe("internal"); expect(data.regulatoryScope).toEqual(["gdpr"]); }); }); function makeOutboxTx(): OutboxPublisherTransaction & { outboxEvent: { create: ReturnType; findUnique: ReturnType; }; } { const tx = { outboxEvent: { create: vi.fn(async ({ data }: { data: Record }) => ({ id: "outbox_1", tenantId: (data.tenantId as string | null) ?? null, eventType: data.eventType as string, payload: data.payload, dispatchKey: (data.dispatchKey as string | null) ?? null, retries: 0, createdAt: new Date(), scheduledAt: new Date(), priority: 0, } as unknown as OutboxEvent)), findUnique: vi.fn(async () => null), }, }; return tx as unknown as OutboxPublisherTransaction & { outboxEvent: { create: ReturnType; findUnique: ReturnType; }; }; } describe("publishAuditEventViaOutbox", () => { it("publishes an outbox event with the canonical audit payload", async () => { const tx = makeOutboxTx(); await publishAuditEventViaOutbox(tx, { tenantId: "tenant_1", actorId: "user_1", actorType: "user", action: "widget.created", targetType: "widget", targetId: "widget_1", sourceModule: "crm", outcome: "success", dataSensitivity: "confidential", regulatoryScope: ["soc2"], metadata: { kept: true }, }); expect(tx.outboxEvent.create).toHaveBeenCalledTimes(1); const args = tx.outboxEvent.create.mock.calls[0]?.[0] as { data: Record }; expect(args.data.eventType).toBe(AUDIT_EVENT_OUTBOX_TYPE); expect(args.data.tenantId).toBe("tenant_1"); const payload = args.data.payload as Record; expect(payload).toMatchObject({ tenantId: "tenant_1", actorId: "user_1", actorType: "user", action: "widget.created", targetType: "widget", targetId: "widget_1", sourceModule: "crm", outcome: "success", dataSensitivity: "confidential", regulatoryScope: ["soc2"], metadata: { kept: true }, }); // hash chain fields are NOT in the payload — the worker computes them expect(payload.previousHash).toBeUndefined(); expect(payload.eventHash).toBeUndefined(); }); it("defaults actorType to system and sanitizes metadata", async () => { const tx = makeOutboxTx(); await publishAuditEventViaOutbox(tx, { action: "x.run", metadata: { password: "hunter2", note: "ok" }, }); const args = tx.outboxEvent.create.mock.calls[0]?.[0] as { data: Record }; const payload = args.data.payload as Record; expect(payload.actorType).toBe("system"); expect(payload.metadata).toEqual({ password: "[REDACTED]", note: "ok" }); }); it("routes platform-scope (tenantId=null) events through the outbox unchanged", async () => { const tx = makeOutboxTx(); await publishAuditEventViaOutbox(tx, { tenantId: null, action: "platform.maintenance" }); const args = tx.outboxEvent.create.mock.calls[0]?.[0] as { data: Record }; expect(args.data.tenantId).toBeNull(); expect(args.data.eventType).toBe(AUDIT_EVENT_OUTBOX_TYPE); }); });