import { describe, expect, it, vi } from "vitest"; import { computeAuditHash, type AuditHashPayload } from "./audit-hash.js"; import { acquireAuditChainLock, auditChainKey, computeAuditChainHeadMac, computeAuditCheckpointMac, loadAuditVerificationContext, pruneAuditChainBatch, verifyAuditCheckpoint, verifyAuditChainHead, type AuditChainCheckpointRecord, } from "./audit-chain-checkpoint.server.js"; const SECRET = "audit-chain-test-secret-32-bytes-minimum"; function payload(id: string, createdAt: Date, previousHash: string | null, action: string): AuditHashPayload & { previousHash: string | null; eventHash: string; } { const value: AuditHashPayload = { id, createdAt: createdAt.toISOString(), tenantId: null, actorType: "system", actorId: null, actorEmail: null, actorIp: null, actorUserAgent: null, action, targetType: "AuditEvent", targetId: null, requestId: null, sourceModule: "audit", outcome: "success", dataSensitivity: "internal", regulatoryScope: [], metadata: null, }; return { ...value, previousHash, eventHash: computeAuditHash({ previousHash, payload: value, secret: SECRET, version: "hmac-v2" }), }; } describe("audit checkpoint authentication", () => { it("casts the advisory-lock result away from PostgreSQL void for Prisma adapters", async () => { const queryRaw = vi.fn(async (strings: TemplateStringsArray, ..._values: unknown[]): Promise => { expect(strings.join("?")).toContain('pg_advisory_xact_lock(hashtextextended(?, 0))::text AS "lock"'); return [{ lock: "" }] as T; }); await acquireAuditChainLock( { $queryRaw: async (strings: TemplateStringsArray, ...values: unknown[]): Promise => queryRaw(strings, ...values) as Promise, }, "tenant-1", ); expect(queryRaw).toHaveBeenCalledOnce(); }); it("authenticates the mutable O(1) chain head, including its timestamp", () => { const headWithoutMac = { chainKey: "tenant:tenant-1", tenantId: "tenant-1", eventId: "event-1", eventHash: "v2:event", eventCreatedAt: new Date("2026-01-01T00:00:00.000Z"), }; const head = { ...headWithoutMac, headMac: computeAuditChainHeadMac(headWithoutMac, SECRET) }; expect(verifyAuditChainHead(head, SECRET)).toBe(true); expect(verifyAuditChainHead({ ...head, eventCreatedAt: new Date("2099-01-01T00:00:00.000Z") }, SECRET)).toBe(false); }); it("binds the deletion anchor and checkpoint history with an HMAC", () => { const withoutMac: Omit = { id: "checkpoint-1", createdAt: new Date("2026-01-01T00:00:00.000Z"), chainKey: auditChainKey(null), tenantId: null, deletedThroughAt: new Date("2016-01-01T00:00:00.000Z"), lastDeletedEventId: "event-1", lastDeletedEventHash: "v2:abc", deletedCount: 1_000, previousCheckpointMac: null, }; const checkpoint = { ...withoutMac, checkpointMac: computeAuditCheckpointMac(withoutMac, SECRET) }; expect(verifyAuditCheckpoint(checkpoint, SECRET)).toBe(true); expect(verifyAuditCheckpoint({ ...checkpoint, deletedCount: 999 }, SECRET)).toBe(false); expect(verifyAuditCheckpoint({ ...checkpoint, lastDeletedEventHash: "v2:forged" }, SECRET)).toBe(false); }); it("loads one authenticated anchor for retained full-chain verification", async () => { const withoutMac: Omit = { id: "checkpoint-1", createdAt: new Date("2026-01-01T00:00:00.000Z"), chainKey: auditChainKey("tenant-1"), tenantId: "tenant-1", deletedThroughAt: new Date("2016-01-01T00:00:00.000Z"), lastDeletedEventId: "old", lastDeletedEventHash: "v2:anchor", deletedCount: 10, previousCheckpointMac: null, }; const checkpoint = { ...withoutMac, checkpointMac: computeAuditCheckpointMac(withoutMac, SECRET) }; const findMany = vi.fn(async () => [checkpoint]); const findHeads = vi.fn(async () => [{ chainKey: "tenant:tenant-1", checkpointId: checkpoint.id }]); const context = await loadAuditVerificationContext( { auditChainCheckpoint: { findMany }, auditChainCheckpointHead: { findMany: findHeads } }, [{ id: "retained", createdAt: new Date(), tenantId: "tenant-1", previousHash: "v2:anchor", eventHash: "v2:event" }], { secret: SECRET }, ); expect(findMany).toHaveBeenCalledTimes(1); expect(findMany).toHaveBeenCalledWith({ where: { id: { in: [checkpoint.id] } } }); expect(findHeads).toHaveBeenCalledTimes(1); expect(context.initialPreviousHashes.get("tenant:tenant-1")).toBe("v2:anchor"); expect(context.invalidCheckpointChains.size).toBe(0); }); }); describe("pruneAuditChainBatch", () => { it("locks, verifies, checkpoints, and deletes a bounded platform-chain prefix", async () => { const firstDate = new Date("2010-01-01T00:00:00.000Z"); const secondDate = new Date("2010-01-02T00:00:00.000Z"); const retainedDate = new Date("2020-01-01T00:00:00.000Z"); const first = { ...payload("event-1", firstDate, null, "one"), createdAt: firstDate }; const second = { ...payload("event-2", secondDate, first.eventHash, "two"), createdAt: secondDate }; const retained = { ...payload("event-3", retainedDate, second.eventHash, "three"), createdAt: retainedDate }; const checkpointCreate = vi.fn(async ({ data }) => data); const deleteMany = vi.fn(async () => ({ count: 2 })); const queryRaw = vi.fn(async () => []); let retainedLookup = 0; const tx = { $queryRaw: queryRaw, auditEvent: { findMany: vi.fn(async () => [first, second]), findFirst: vi.fn(async () => { retainedLookup += 1; return retainedLookup === 1 ? { id: retained.id, previousHash: retained.previousHash, eventHash: retained.eventHash } : null; }), deleteMany, }, auditChainCheckpoint: { findFirst: vi.fn(async () => null), findUnique: vi.fn(async () => null), findMany: vi.fn(async () => []), create: checkpointCreate, }, auditChainCheckpointHead: { findUnique: vi.fn(async () => null), upsert: vi.fn(async () => undefined), }, }; const client = { $transaction: async (runner: (value: typeof tx) => Promise) => runner(tx) }; const result = await pruneAuditChainBatch(null, new Date("2019-01-01T00:00:00.000Z"), { client: client as never, secret: SECRET, batchSize: 2, now: new Date("2026-01-01T00:00:00.000Z"), }); expect(queryRaw).toHaveBeenCalledTimes(1); expect(tx.auditEvent.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: 2, select: expect.not.objectContaining({ beforeDiff: expect.anything(), afterDiff: expect.anything() }), })); expect(deleteMany).toHaveBeenCalledWith({ where: { id: { in: ["event-1", "event-2"] } } }); expect(result).toMatchObject({ tenantId: null, deletedCount: 2, hasMore: false }); const checkpoint = checkpointCreate.mock.calls[0]?.[0].data as AuditChainCheckpointRecord; expect(checkpoint.chainKey).toBe("platform"); expect(checkpoint.lastDeletedEventHash).toBe(second.eventHash); expect(verifyAuditCheckpoint(checkpoint, SECRET)).toBe(true); }); });