@nodii/audit-chain
v0.18.0
Published
Tamper-evident audit chain for the Nodii microservice stack — implements `@nodii/telemetry.AuditChainAdapter` per doctrine 02-audit-doctrine.md § 13. v0.3.0 replaces the v0.2.x jsonb-event audit_rows row shape with the rich-column `<service>_audit_event`
Readme
@nodii/audit-chain
Tamper-evident audit chain for the Nodii microservice stack — per-tenant
SHA-256 hash chain over audit_event rows + pluggable DB + KMS signing client
- verifier helpers.
Spec: https://planning.dev.nucleus-cloud.in/api/v1/feature-docs?serviceId=nodii-libs&docKey=audit-chain
v0.1.0 — foundations
import {
initAuditChain,
auditChain,
InMemoryAuditChainDbClient,
HmacKmsClient,
canonicalJson,
computeChainHash,
GENESIS_HASH,
} from "@nodii/audit-chain";
initAuditChain({
db: new InMemoryAuditChainDbClient(), // swap with Drizzle adapter at v0.1.x
signingMode: "hmac",
hmacSecret: process.env.AUDIT_HMAC_SECRET, // KMS adapter at v0.1.x
});
const { row, this_hash, prev_hash, sig } = await auditChain.emit({
tenant_id: "tnt_123",
event: { action: "invoice.create", target_id: "inv_1", amount: 100 },
});
const verdict = await auditChain.verify({ tenant_id: "tnt_123" });
if (!verdict.ok) {
// verdict.brokenAt, .expected, .actual, .reason
}Public surface
initAuditChain({ db?, kmsClient?, signingMode?, hmacSecret? })— bootstrap.auditChain.emit({ tenant_id, event })/auditChain.append({ … })— appends a tamper-evident row to the chain.auditChain.verify({ tenant_id, fromSeq?, toSeq? })— recomputes the chain in-range and asserts each row's hash matches and sig verifies.auditChain.verifyOrThrow(...)— throwsChainBrokenon first mismatch.canonicalJson(event)— exposed for parity-fence verification.computeChainHash({ prev_hash, event })— exposed for tests.appendAuditRowInTx(tx, { tenantId, event, computeHash, nowIso, signHash? })— append a chain row inside a transaction YOU own (see below).- Typed errors:
AuditChainError+AuditChainNotInitialized+ChainBrokenSignatureInvalid+EventNonCanonical+AuditChainSeqConflictAuditChainUnsupportedTx.
Concurrency: the chain head is read under the per-tenant lock
emit allocates a sequence by reading the chain head. That read happens inside
the SAME transaction and pg_advisory_xact_lock(hash_of(tenant_id || 'audit'))
as the INSERT, whenever the configured db client offers an atomic appendRow
(PostgresAuditChainStore does). A concurrent emitter for the same tenant
blocks on the lock and reads the head this transaction committed, so no sequence
is ever allocated twice.
This matters because the in-process per-tenant mutex only orders emitters inside
ONE process. Request 7dc846e5 is what that missed: the head used to be read on
a plain connection, so a second process — or the same process's own facade
append, which reads the head inside the lock — could commit the sequence in the
gap, and the loser's contiguity check threw the row away.
A db client with only insert + fetchLatest + fetchRange cannot hold a lock
across the two calls. It still never LOSES a row: emit retries on a typed,
retryable AuditChainSeqConflict (8 attempts) and throws when the budget
runs out. Nothing is written when it throws. The budget is finite and loud on
purpose — on a tamper-evident log a missing row is indistinguishable from a
deleted one, so a dropped append must never be reported as a warning.
Implement appendRow on any Postgres-backed client you write:
appendRow(args: {
tenantId: string;
event: AuditChainEvent;
computeHash: (prevHash: string) => string;
nowIso: string;
signHash?: (thisHash: string) => Promise<string>;
tx?: unknown;
}): Promise<AuditChainRow>;Read the head, compute the hash, await signHash, and INSERT — all inside one
transaction holding the per-tenant lock. signHash is called after
computeHash so the stored signature is over the hash the row is actually
linked at; holding the lock across the signing call is deliberate, because a
signature computed outside it belongs to a different chain position.
Writing your own audit row in your own transaction
If your service owns a rich <svc>_audit_event table and needs the chain row to
commit in the SAME transaction as the mutation it describes, delegate to
appendAuditRowInTx rather than reimplementing the locked append:
import { appendAuditRowInTx, computeChainHash } from "@nodii/audit-chain";
await sql.begin(async (tx) => {
await tx`UPDATE invoices SET status = 'void' WHERE id = ${id}`;
await appendAuditRowInTx(tx, {
tenantId,
event,
computeHash: (prevHash) => computeChainHash({ prev_hash: prevHash, event }),
nowIso: new Date().toISOString().replace("Z", "000Z"),
signHash: async (h) => sign(h),
});
});The advisory lock is taken on YOUR transaction, so it is held until YOU commit,
and the chain row rolls back with your mutation. A handle it cannot join raises
AuditChainUnsupportedTx: it will never quietly open its own transaction,
because an audit row that outlives a rolled-back mutation asserts something that
never happened.
Deferred to v0.1.x (marked // TODO audit-chain-v0.1.x: in source)
- Real KMS signing (aws-sdk-v3 / boto3 / aws-sdk-go-v2).
- Lambda verifier deployment artifact (spec § 5.5).
- Drizzle / SQLAlchemy / pgx schema migrations for
audit_event_chain. - Range-pagination on
verifyfor very large chains.
Audit cold archiver — WORM archive, 7-year retention (RETENTION-FIX-7)
Audit tables grow forever unless something moves their sealed history out. The
archiver (moved here from nodii-billing-service's auditColdArchiver) archives
each SEALED range — a monthly partition of an AUDT-31 partitioned table, or one
month of an unpartitioned table / of the default partition — older than the live
window (liveRetentionMonths, default 12, AUDT-42) to an Object-Lock bucket,
then removes it from Postgres. Per range, in this order (AUDT-40):
- chain-verify each tenant segment from its archive anchor (a break blocks the
range and logs
audit_archive_chain_broken, AUDT-38); - PUT a
nodii.audit-archive.v1NDJSON object with Object-Lock retain-until = archive date +retentionYears(default 7, minimum 7, COMPLIANCE by default — AUDT-43 / RETN-42) and a SHA-256 checksum; - GET that exact version back: checksum, row count, chain and lock mode / retain-until must all match (RETN-43) — otherwise nothing is deleted;
- legal-hold gate —
heldTenantCount(required) > 0 withholds the delete (AUDT-41); - one transaction, after the lease fence: delete witness links first, then DETACH
- DROP the partition (or DELETE the month), advance
<svc>_audit_archive_anchors, write<svc>_audit_archive_ledger.
- DROP the partition (or DELETE the month), advance
A tenant's newest chained row is never archived: the chain writers find the next
seq and prev_hash in the live table only, so a tenant with no live row would
restart at genesis. A segment that would take that row ends one row short; the
row (and its witness link) stays live, the anchor points at the row before it,
and a partition holding it is emptied by DELETE rather than dropped (outcome
newest_rows_kept when nothing else in the range is archivable). It is archived
by a later run once the tenant has written a newer row.
A table's pass stops at the first range that does not complete, so the live chain never has a hole. Rows already older than 7 years when first archived are archived like any other (never dropped unarchived) and get the full 7-year lock.
Expiry is the bucket's job: the library stamps the retain-until date and the bucket lifecycle rule (infra, RETENTION-FIX-19) must expire object versions once their retention has passed. The bucket must have Object Lock + versioning enabled (the archiver refuses to delete anything if S3 does not echo the lock back).
Verification across the archive boundary. The anchors table records, per
(source table, tenant), the last archived seq and its row_hash. The rich-row
verifier (startAuditRowChainVerifier, TS) seeds its walk from the anchor
automatically when the table exists; verifyLiveChain does the same check on
demand in every language. The archived history verifies from the object alone
(verifyArchivedRange): each object's header records, per tenant, the anchor
the segment continued from and the hash it ended on, so consecutive objects link
and the newest one's last_hash equals the live anchor.
Object format — line 1 is the header (format, service, source_table,
layout, range_lower, range_upper, partition, row_count, rows_sha256,
tenants[] with prev_seq/prev_hash → from_seq..to_seq, last_hash);
each further line is one row (tenant_id, event_id, seq, prev_hash,
row_hash, sig, canonical = the exact bytes the chain hashed, row = the row
exactly as Postgres stored it, every digit — the lossless archived copy). All lines are
canonical JSON; TS, Python and Go build byte-identical objects (parity fence
07-archive-object.json).
Layouts: single (chain columns on the row), witness (separate witness table,
billing's D191 shape — its links are deleted with the rows), none (unchained,
e.g. a *_pii_reveal_audit table — archived and checksummed, no chain walk).
The legacy jsonb audit_rows chain is not archivable.
Sizing. A range (one month of one table, plus its stragglers) is loaded and
built in memory, then PUT as one object (no streaming, no multipart). A range over
maxRowsPerRange (default 1 000 000; checked with a COUNT before anything is
loaded) fails closed with range_too_large and nothing is archived or deleted:
size the worker and the ceiling for your largest monthly partition. heldTenantCount is called
twice: once before the delete, and again INSIDE the delete transaction with the
open transaction handle (tx) — read the hold table through that handle, do
not touch the audit table from another connection, and return quickly (the
transaction holds ACCESS EXCLUSIVE on the audit table at that point).
The job writes no audit event (AUDT-49); counts go to the logger and onRun
(keep metric attributes to table / outcome — TELE-21).
import { S3Client } from "@aws-sdk/client-s3";
import { applyAuditArchiveMigrations, makeAuditArchiveJob } from "@nodii/audit-chain";
await applyAuditArchiveMigrations(ownerSql, { serviceName: "billing" });
const job = makeAuditArchiveJob({
serviceName: "billing",
sql: ownerSql, // OWNER pool (DETACH / DROP / DELETE)
s3: new S3Client({ region }),
bucket: env.AUDIT_ARCHIVE_S3_BUCKET, // Object Lock + versioning
targets: [{ table: "billing_audit_event", profile: "partitioned", layout: "witness", witnessTable: "billing_audit_rows" }],
heldTenantCount: ({ tenantIds }) => countActiveTenantHolds(tenantIds),
signer: hmacSigner, // verifies witness signatures
leaseRedis: redis, // nodii:lease:billing:audit-archive
onRun: (r) => { /* metric */ },
});
scheduler.every(job.intervalMs, job.handler); // { name, intervalMs, pool: "owner", handler }