Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/cli/src/commands/audit/verify-chain.test.ts
T

151 lines
5.0 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { computeAuditHash, verifyAuditChain } from "@toolctrl/db/audit-hash";
import {
runAuditVerifyChain,
type AuditVerifyChainDependencies,
type AuditVerifyChainRow,
} from "./verify-chain.js";
function makeOutput() {
return {
info: vi.fn<(msg: string) => void>(),
error: vi.fn<(msg: string) => void>(),
json: vi.fn<(obj: unknown) => void>(),
};
}
function basePayload(over: Partial<AuditVerifyChainRow> = {}): AuditVerifyChainRow {
return {
id: "audit_1",
createdAt: "2026-05-17T00:00:00.000Z",
tenantId: "tenant_1",
actorType: "user",
actorId: "user_1",
actorEmail: null,
actorIp: null,
actorUserAgent: null,
action: "x.do",
targetType: null,
targetId: null,
requestId: null,
sourceModule: null,
outcome: "success",
dataSensitivity: "internal",
regulatoryScope: [],
metadata: null,
previousHash: null,
eventHash: null,
...over,
};
}
function hashFor(row: AuditVerifyChainRow): string {
return computeAuditHash({
previousHash: row.previousHash,
payload: {
id: row.id,
createdAt: row.createdAt,
tenantId: row.tenantId,
actorType: row.actorType,
actorId: row.actorId,
actorEmail: row.actorEmail,
actorIp: row.actorIp,
actorUserAgent: row.actorUserAgent,
action: row.action,
targetType: row.targetType,
targetId: row.targetId,
requestId: row.requestId,
sourceModule: row.sourceModule,
outcome: row.outcome,
dataSensitivity: row.dataSensitivity,
regulatoryScope: row.regulatoryScope,
metadata: row.metadata,
},
});
}
function makeDeps(rows: AuditVerifyChainRow[]): AuditVerifyChainDependencies & { output: ReturnType<typeof makeOutput> } {
const output = makeOutput();
return {
output,
verify: verifyAuditChain,
async *readRows() {
for (const row of rows) yield row;
},
};
}
describe("runAuditVerifyChain", () => {
it("returns exit code 0 + prints OK message for an intact chain", async () => {
const r1 = basePayload();
r1.eventHash = hashFor(r1);
const r2 = basePayload({ id: "audit_2", action: "x.do2", previousHash: r1.eventHash });
r2.eventHash = hashFor(r2);
const deps = makeDeps([r1, r2]);
const result = await runAuditVerifyChain({ tenant: "tenant_1" }, deps);
expect(result.exitCode).toBe(0);
expect(result.ok).toBe(true);
expect(result.inspected).toBe(2);
expect(deps.output.info).toHaveBeenCalledWith(expect.stringContaining("audit-chain OK"));
});
it("returns exit code 1 with a diagnostic on hash mismatch", async () => {
const r1 = basePayload();
r1.eventHash = hashFor(r1);
// tamper: change metadata but keep stored hash
const tampered = { ...r1, metadata: { tampered: true } };
const deps = makeDeps([tampered]);
const result = await runAuditVerifyChain({ tenant: "tenant_1" }, deps);
expect(result.exitCode).toBe(1);
expect(result.ok).toBe(false);
expect(deps.output.error).toHaveBeenCalledWith(expect.stringContaining("audit-chain BROKEN"));
expect(deps.output.error).toHaveBeenCalledWith(expect.stringContaining("hash-mismatch"));
});
it("emits a single JSON object when --json is set", async () => {
const r1 = basePayload();
r1.eventHash = hashFor(r1);
const deps = makeDeps([r1]);
const result = await runAuditVerifyChain({ tenant: "tenant_1", json: true }, deps);
expect(result.exitCode).toBe(0);
expect(deps.output.info).not.toHaveBeenCalled();
expect(deps.output.json).toHaveBeenCalledTimes(1);
const arg = deps.output.json.mock.calls[0]?.[0] as Record<string, unknown>;
expect(arg).toMatchObject({ tenantId: "tenant_1", ok: true, inspected: 1 });
});
it("rejects an empty tenant arg", async () => {
const deps = makeDeps([]);
const result = await runAuditVerifyChain({ tenant: " " }, deps);
expect(result.exitCode).toBe(1);
expect(deps.output.error).toHaveBeenCalledWith(expect.stringContaining("Missing --tenant"));
});
it("parses ISO-8601 --from/--to and propagates them to the reader", async () => {
const captured: { from: Date | null; to: Date | null }[] = [];
const deps: AuditVerifyChainDependencies & { output: ReturnType<typeof makeOutput> } = {
output: makeOutput(),
verify: () => ({ ok: true, inspected: 0, firstBreak: null }),
async *readRows(opts) {
captured.push({ from: opts.from, to: opts.to });
return;
},
};
await runAuditVerifyChain({ tenant: "t1", from: "2026-01-01T00:00:00.000Z", to: "2026-05-17T00:00:00.000Z" }, deps);
expect(captured[0]?.from?.toISOString()).toBe("2026-01-01T00:00:00.000Z");
expect(captured[0]?.to?.toISOString()).toBe("2026-05-17T00:00:00.000Z");
});
it("throws when --from is not parseable", async () => {
const deps = makeDeps([]);
await expect(runAuditVerifyChain({ tenant: "t1", from: "not-a-date" }, deps)).rejects.toThrow(/Invalid --from/);
});
});