Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+265
@@ -0,0 +1,265 @@
|
||||
// @vitest-environment node
|
||||
//
|
||||
// Pin to the node environment. When the coverage gate runs this suite from the
|
||||
// repo root, the root vitest.config.ts (environment: "jsdom") is loaded instead
|
||||
// of packages/cli/vitest.config.ts (environment: "node"). Under jsdom, vitest's
|
||||
// module interop for the mocked `node:fs/promises` builtin demands a `default`
|
||||
// export the mock does not provide, so the whole suite fails to load. These are
|
||||
// node CLI commands, so this pragma keeps the environment identical regardless
|
||||
// of the working directory the runner is invoked from.
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { AuditPdfEvent } from "@hivegrid/exports/audit-pdf";
|
||||
|
||||
/**
|
||||
* Exercises the citty `run` wrappers of the audit commands — the inline
|
||||
* Prisma wiring (where-building, cursor pagination, chain-event mapping)
|
||||
* that the pure-function tests in verify-chain.test.ts / export-pdf.test.ts
|
||||
* deliberately bypass via injected dependencies.
|
||||
*/
|
||||
|
||||
const findMany = vi.fn<() => Promise<unknown[]>>();
|
||||
const verifyAuditChain = vi.fn();
|
||||
const serializeAuditEventsToPdf = vi.fn<() => Promise<Uint8Array>>();
|
||||
const writeFile = vi.fn<() => Promise<void>>();
|
||||
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getReadDbClient: () => ({ auditEvent: { findMany } }),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-hash", () => ({
|
||||
verifyAuditChain: (...args: unknown[]) => verifyAuditChain(...(args as [])),
|
||||
}));
|
||||
vi.mock("@hivegrid/exports/audit-pdf", () => ({
|
||||
serializeAuditEventsToPdf: (...args: unknown[]) => serializeAuditEventsToPdf(...(args as [])),
|
||||
}));
|
||||
vi.mock("node:fs/promises", () => ({
|
||||
writeFile: (...args: unknown[]) => writeFile(...(args as [])),
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
default: {
|
||||
log: vi.fn(),
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import consola from "consola";
|
||||
import { auditExportPdfCommand } from "./export-pdf.js";
|
||||
import { auditVerifyChainCommand } from "./verify-chain.js";
|
||||
|
||||
const consoleMock = vi.mocked(consola);
|
||||
|
||||
function makeEvent(over: Partial<AuditPdfEvent> = {}): AuditPdfEvent {
|
||||
return {
|
||||
id: "audit_1",
|
||||
createdAt: new Date("2026-05-17T00:00:00.000Z"),
|
||||
tenantId: "tenant_1",
|
||||
actorType: "user",
|
||||
actorId: "user_1",
|
||||
actorEmail: null,
|
||||
actorIp: null,
|
||||
actorUserAgent: null,
|
||||
action: "widget.created",
|
||||
targetType: "widget",
|
||||
targetId: "widget_1",
|
||||
requestId: null,
|
||||
sourceModule: "crm",
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
regulatoryScope: ["soc2"],
|
||||
metadata: null,
|
||||
previousHash: null,
|
||||
eventHash: "h1",
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
describe("audit verify-chain command wrapper", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.exitCode = undefined;
|
||||
findMany.mockResolvedValue([]);
|
||||
verifyAuditChain.mockReturnValue({ ok: true, inspected: 0, firstBreak: undefined });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.exitCode = undefined;
|
||||
});
|
||||
|
||||
it("maps a concrete tenant + date range into the Prisma where clause", async () => {
|
||||
findMany.mockResolvedValueOnce([makeEvent()]);
|
||||
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 1, firstBreak: undefined });
|
||||
|
||||
await auditVerifyChainCommand.run?.({
|
||||
args: { tenant: "tenant_1", from: "2026-05-01T00:00:00Z", to: "2026-06-01T00:00:00Z" },
|
||||
} as never);
|
||||
|
||||
expect(findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
tenantId: "tenant_1",
|
||||
createdAt: { gte: new Date("2026-05-01T00:00:00Z"), lt: new Date("2026-06-01T00:00:00Z") },
|
||||
},
|
||||
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
||||
take: 5_000,
|
||||
}),
|
||||
);
|
||||
expect(consoleMock.success).toHaveBeenCalledWith("audit-chain OK — tenant=tenant_1 inspected=1");
|
||||
expect(process.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it("translates --tenant=__platform__ into a null tenant filter", async () => {
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "__platform__" } } as never);
|
||||
|
||||
expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: null } }));
|
||||
});
|
||||
|
||||
it("follows the cursor across pages until a short final page", async () => {
|
||||
const fullPage = Array.from({ length: 5_000 }, (_v, i) => makeEvent({ id: `evt_${i}` }));
|
||||
findMany.mockResolvedValueOnce(fullPage).mockResolvedValueOnce([makeEvent({ id: "evt_last" })]);
|
||||
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 5_001, firstBreak: undefined });
|
||||
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1" } } as never);
|
||||
|
||||
expect(findMany).toHaveBeenCalledTimes(2);
|
||||
// Second page is requested with a skip+cursor anchored on the last id of page one.
|
||||
expect(findMany).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ skip: 1, cursor: { id: "evt_4999" } }),
|
||||
);
|
||||
expect(verifyAuditChain).toHaveBeenCalledWith(
|
||||
expect.arrayContaining([expect.objectContaining({ id: "evt_last" })]),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a broken chain on stderr with a non-zero exit code", async () => {
|
||||
findMany.mockResolvedValueOnce([makeEvent()]);
|
||||
verifyAuditChain.mockReturnValueOnce({
|
||||
ok: false,
|
||||
inspected: 1,
|
||||
firstBreak: { eventId: "audit_1", reason: "hash-mismatch" },
|
||||
});
|
||||
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1" } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith(
|
||||
"audit-chain BROKEN — tenant=tenant_1 inspected=1 firstBreakId=audit_1 reason=hash-mismatch",
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it("emits a single JSON object in --json mode", async () => {
|
||||
findMany.mockResolvedValueOnce([makeEvent()]);
|
||||
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 1, firstBreak: undefined });
|
||||
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1", json: true } } as never);
|
||||
|
||||
const printed = JSON.parse(String(consoleMock.log.mock.calls[0]?.[0]));
|
||||
expect(printed).toMatchObject({ tenantId: "tenant_1", from: null, to: null, inspected: 1, ok: true });
|
||||
// An intact chain has no firstBreak, so JSON.stringify drops the key entirely.
|
||||
expect(printed).not.toHaveProperty("firstBreak");
|
||||
});
|
||||
|
||||
it("catches an invalid --from value and exits non-zero", async () => {
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1", from: "not-a-date" } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Invalid --from value "not-a-date"'),
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
expect(findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("catches a database failure and exits non-zero", async () => {
|
||||
findMany.mockRejectedValueOnce(new Error("connection reset"));
|
||||
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1" } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("connection reset");
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("audit export-pdf command wrapper", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.exitCode = undefined;
|
||||
findMany.mockResolvedValue([]);
|
||||
verifyAuditChain.mockReturnValue({ ok: true, inspected: 0, firstBreak: undefined });
|
||||
serializeAuditEventsToPdf.mockResolvedValue(new Uint8Array([1, 2, 3, 4]));
|
||||
writeFile.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.exitCode = undefined;
|
||||
});
|
||||
|
||||
it("builds the where filter, renders, and writes the PDF on an intact chain", async () => {
|
||||
findMany.mockResolvedValueOnce([makeEvent()]);
|
||||
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 1, firstBreak: undefined });
|
||||
|
||||
await auditExportPdfCommand.run?.({
|
||||
args: {
|
||||
tenant: "tenant_1",
|
||||
from: "2026-05-01T00:00:00Z",
|
||||
to: "2026-06-01T00:00:00Z",
|
||||
"regulatory-scope": "gdpr",
|
||||
out: "/tmp/audit.pdf",
|
||||
"generated-by": "Ops",
|
||||
},
|
||||
} as never);
|
||||
|
||||
expect(findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
tenantId: "tenant_1",
|
||||
createdAt: { gte: new Date("2026-05-01T00:00:00Z"), lt: new Date("2026-06-01T00:00:00Z") },
|
||||
regulatoryScope: { hasSome: ["gdpr"] },
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: 5_000,
|
||||
}),
|
||||
);
|
||||
expect(serializeAuditEventsToPdf).toHaveBeenCalledTimes(1);
|
||||
expect(writeFile).toHaveBeenCalledWith("/tmp/audit.pdf", new Uint8Array([1, 2, 3, 4]));
|
||||
expect(consoleMock.success).toHaveBeenCalledWith(
|
||||
"audit-pdf written — out=/tmp/audit.pdf rows=1 bytes=4 integrity=ok",
|
||||
);
|
||||
expect(process.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it("maps __platform__ to a null tenant and omits the date range when unset", async () => {
|
||||
await auditExportPdfCommand.run?.({
|
||||
args: { tenant: "__platform__", out: "/tmp/p.pdf" },
|
||||
} as never);
|
||||
|
||||
expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: null } }));
|
||||
});
|
||||
|
||||
it("flags a broken chain in the log line and exits non-zero", async () => {
|
||||
findMany.mockResolvedValueOnce([makeEvent()]);
|
||||
verifyAuditChain.mockReturnValueOnce({
|
||||
ok: false,
|
||||
inspected: 1,
|
||||
firstBreak: { eventId: "audit_1", reason: "hash-mismatch" },
|
||||
});
|
||||
|
||||
await auditExportPdfCommand.run?.({
|
||||
args: { tenant: "tenant_1", out: "/tmp/audit.pdf" },
|
||||
} as never);
|
||||
|
||||
expect(writeFile).toHaveBeenCalledTimes(1);
|
||||
expect(consoleMock.error).toHaveBeenCalledWith(
|
||||
expect.stringContaining("audit-pdf written WITH BROKEN CHAIN"),
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects an empty --out before touching the database", async () => {
|
||||
await auditExportPdfCommand.run?.({ args: { tenant: "tenant_1", out: " " } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("Missing --out.");
|
||||
expect(findMany).not.toHaveBeenCalled();
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@toolctrl/exports/audit-pdf";
|
||||
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@hivegrid/exports/audit-pdf";
|
||||
import { runAuditExportPdf, type AuditExportPdfDependencies } from "./export-pdf.js";
|
||||
|
||||
function makeEvent(over: Partial<AuditPdfEvent> = {}): AuditPdfEvent {
|
||||
@@ -50,7 +50,7 @@ function makeDeps(opts: {
|
||||
render: async (input) => {
|
||||
state.renderInput = input;
|
||||
// Fake PDF bytes — the renderer is unit-tested separately in
|
||||
// @toolctrl/exports.
|
||||
// @hivegrid/exports.
|
||||
return new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x37]); // "%PDF-1.7"
|
||||
},
|
||||
writeOutput: async (path, bytes) => {
|
||||
|
||||
+6
-6
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl audit export-pdf --tenant <id> [--from] [--to] [--regulatory-scope]
|
||||
* `hivegrid audit export-pdf --tenant <id> [--from] [--to] [--regulatory-scope]
|
||||
* --out <path>`
|
||||
*
|
||||
* Renders a tamper-evident PDF compliance report from AuditEvent rows for
|
||||
@@ -7,7 +7,7 @@
|
||||
* `verifyAuditChain` integrity check; the body lists each event in
|
||||
* chronological order with hash + actor + outcome + scope.
|
||||
*
|
||||
* Renders via @react-pdf/renderer through `@toolctrl/exports/audit-pdf`.
|
||||
* Renders via @react-pdf/renderer through `@hivegrid/exports/audit-pdf`.
|
||||
*
|
||||
* See docs/improvement-plan/10-compliance-polish/compliance-audit-export.md.
|
||||
*/
|
||||
@@ -15,7 +15,7 @@ import { writeFile } from "node:fs/promises";
|
||||
import { defineCommand } from "citty";
|
||||
import consola from "consola";
|
||||
|
||||
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@toolctrl/exports/audit-pdf";
|
||||
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@hivegrid/exports/audit-pdf";
|
||||
|
||||
const AUDIT_PDF_QUERY_LIMIT = 5_000;
|
||||
|
||||
@@ -138,9 +138,9 @@ export const auditExportPdfCommand = defineCommand({
|
||||
},
|
||||
async run({ args }) {
|
||||
const [{ getReadDbClient }, { verifyAuditChain }, { serializeAuditEventsToPdf }] = await Promise.all([
|
||||
import("@toolctrl/db/client.server"),
|
||||
import("@toolctrl/db/audit-hash"),
|
||||
import("@toolctrl/exports/audit-pdf"),
|
||||
import("@hivegrid/db/client.server"),
|
||||
import("@hivegrid/db/audit-hash"),
|
||||
import("@hivegrid/exports/audit-pdf"),
|
||||
]);
|
||||
|
||||
const db = getReadDbClient();
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { computeAuditHash, verifyAuditChain } from "@toolctrl/db/audit-hash";
|
||||
import { computeAuditHash, verifyAuditChain } from "@hivegrid/db/audit-hash";
|
||||
import {
|
||||
runAuditVerifyChain,
|
||||
type AuditVerifyChainDependencies,
|
||||
|
||||
+6
-6
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* `toolctrl audit verify-chain --tenant <id> [--from <iso8601>] [--to <iso8601>] [--json]`
|
||||
* `hivegrid audit verify-chain --tenant <id> [--from <iso8601>] [--to <iso8601>] [--json]`
|
||||
*
|
||||
* Thin CLI wrapper around `verifyAuditChain` from @toolctrl/db/audit-hash.
|
||||
* Thin CLI wrapper around `verifyAuditChain` from @hivegrid/db/audit-hash.
|
||||
* Loads the per-tenant AuditEvent chain in chronological order, recomputes
|
||||
* each event's eventHash and compares it against the stored value. Exits
|
||||
* 0 on intact chain, non-zero with first-break diagnostics otherwise.
|
||||
@@ -21,7 +21,7 @@
|
||||
import { defineCommand } from "citty";
|
||||
import consola from "consola";
|
||||
|
||||
import type { AuditChainEvent, VerifyAuditChainResult } from "@toolctrl/db/audit-hash";
|
||||
import type { AuditChainEvent, VerifyAuditChainResult } from "@hivegrid/db/audit-hash";
|
||||
|
||||
const AUDIT_VERIFY_BATCH_SIZE = 5_000;
|
||||
|
||||
@@ -37,7 +37,7 @@ export type AuditVerifyChainRow = AuditChainEvent;
|
||||
export type AuditVerifyChainDependencies = {
|
||||
/** Cursor-iterable read of events ordered by createdAt ascending. */
|
||||
readRows: (args: { tenantId: string; from: Date | null; to: Date | null; batchSize: number }) => AsyncIterable<AuditVerifyChainRow>;
|
||||
/** Chain verifier — usually `verifyAuditChain` from @toolctrl/db/audit-hash. */
|
||||
/** Chain verifier — usually `verifyAuditChain` from @hivegrid/db/audit-hash. */
|
||||
verify: (events: ReadonlyArray<AuditVerifyChainRow>, options?: { secret?: string | null }) => VerifyAuditChainResult;
|
||||
/** Output sink. Tests pass an array collector; production wires consola. */
|
||||
output: { info: (msg: string) => void; json: (obj: unknown) => void; error: (msg: string) => void };
|
||||
@@ -111,8 +111,8 @@ export const auditVerifyChainCommand = defineCommand({
|
||||
json: { type: "boolean", required: false, default: false, description: "Emit a single JSON object instead of human-readable text." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { verifyAuditChain } = await import("@toolctrl/db/audit-hash");
|
||||
const { getReadDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { verifyAuditChain } = await import("@hivegrid/db/audit-hash");
|
||||
const { getReadDbClient } = await import("@hivegrid/db/client.server");
|
||||
const db = getReadDbClient();
|
||||
const tenantId = String(args.tenant);
|
||||
|
||||
|
||||
Reference in new issue
Block a user