diff --git a/.changeset/34170-export-signed-body-readers.md b/.changeset/34170-export-signed-body-readers.md new file mode 100644 index 00000000000..1506b0f1ac3 --- /dev/null +++ b/.changeset/34170-export-signed-body-readers.md @@ -0,0 +1,16 @@ +--- +'@objectstack/plugin-audit': patch +--- + +feat(plugin-audit): export the readers that rebuild a stored checkpoint or amendment row into its signed body + +Clause-②: yes +Metadata-protocol: none + +`@objectstack/plugin-audit` now exports `checkpointBodyFromRow` and `amendmentBodyFromRow` from its package entry, with the two body types they answer, `CheckpointSignedBody` and `AmendmentSignedBody` (ADR-0154 D11). + +A checkpoint sink (`audit.checkpointSink`) is handed each signed checkpoint and amendment once, and re-delivers what a failed call missed by re-reading the stored records. Read from an unaltered stored `sys_audit_checkpoint` or `sys_audit_amendment` row, these readers answer the body the sink was handed: its RFC 8785 serialization is the bytes the row's `signature` covers, so a sink outside the package can rebuild and re-send a record without copying the body's shape or its parsing. A malformed row is refused with an error whose `name` is `SignedBodyError` and whose message names the field. + +The readers validate and normalize; they never verify the signature. A row whose signed columns were rewritten reads back into a body that fails verification (a rewrite of an unsigned column, `id`, `chain_key` or a checkpoint's `leaf_hashes`, reads back into the same body, and a malformed one is refused with a `SignedBodyError`). A row rewritten and re-signed under a key planted on the host fails under a key the sink trusts itself. A row rewritten and re-signed by whoever holds the genuine signing key verifies, and only the copies already off the host can catch it: a later checkpoint's signed `previous_digest` no longer matches a rewritten checkpoint, while no later record carries an amendment's digest at all. So a sink verifies the row's `signature` over the rebuilt body, under a key it trusts itself, before it treats the row as delivered. + +A sink assembles the entry it re-delivers itself: `kind` is `checkpoint` or `amendment`, from the table it read; `keyId` is `body.signing_key_id`; and `signature` is the row's `signature` column. The signed bytes are the body's RFC 8785 (JCS) serialization, which the sink computes with its own serializer: this package does not export one. diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-signed-body-readers-34170.integration.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-signed-body-readers-34170.integration.test.ts new file mode 100644 index 00000000000..b21236dc3c4 --- /dev/null +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-signed-body-readers-34170.integration.test.ts @@ -0,0 +1,128 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { createPublicKey, verify } from 'node:crypto'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import { SysSecret } from '@objectstack/platform-objects/system'; +import { AUDIT_CHECKPOINT_SINK_SERVICE, type AuditCheckpointSinkEntry, type IAuditCheckpointSink } from '@objectstack/spec/contracts'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { AuditPlugin } from '../audit-plugin.js'; +import { installDefaultOrganization } from '../default-organization.testkit.js'; +// The subject, through the package entry: what a sink outside this package imports. +import { amendmentBodyFromRow, checkpointBodyFromRow } from '../index.js'; +import { migrateMailLogBodyCopies } from '../mail-log-body-migration.js'; +import { SysAuditLog } from '../objects/sys-audit-log.object.js'; +import { canonicalJsonBytes } from './jcs.js'; +import { bindingCrypto, recordingLogger } from './seal-store.testkit.js'; +import type { AuditSealer } from './sealer.js'; +import { signedBodyBytes } from './signed-body.js'; +import { trustedSigningKey } from './signer.js'; + +/** + * #34170 on a real kernel: a checkpoint sink off the host (ADR-0154 D11) is + * handed each signed record once, and re-delivers what a failed call missed by + * re-reading the stored rows (the `IAuditCheckpointSink` contract). The two + * readers the package entry exports rebuild a stored `sys_audit_checkpoint` + * row and a stored `sys_audit_amendment` row into the body the sealer and the + * amendment writer handed the sink: the same RFC 8785 bytes, and a signature + * that verifies over them under the stored signing key. + * + * The rows carry sentinels, never a real body, key or hash. + */ + +const H = 60 * 60 * 1000; +const SYS = { isSystem: true } as const; +const LOG = 'sys_audit_log'; +const MAIL_BODY = 'mail-body-sentinel'; + +type Row = Record; + +/** The ledger, sealed: its three value columns committed. */ +const sealedLog = { ...SysAuditLog, lifecycle: { ...SysAuditLog.lifecycle, seal: { valueFields: ['metadata', 'new_value', 'old_value'] } } }; + +describe('a stored checkpoint or amendment row reads back, through the package entry, into the body the sink was handed (#34170)', () => { + const crypto = bindingCrypto(); + const delivered: AuditCheckpointSinkEntry[] = []; + const sink: IAuditCheckpointSink = { deliver: async (entry) => { delivered.push(entry); } }; + const plugin = new AuditPlugin({ cryptoProvider: crypto }); + let kernel: ObjectKernel; + let engine: ObjectQL; + + /** Does `signature` (base64) verify over `bytes` under the stored, trusted signing key `keyId`? */ + const verifiesUnderStoredKey = async (bytes: Buffer, keyId: string, signature: string): Promise => { + const publicKey = await trustedSigningKey(engine as never, crypto, keyId); + if (publicKey === null) throw new Error(`no stored signing key is trusted under ${keyId}`); + const key = createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: Buffer.from(publicKey, 'base64').toString('base64url') }, format: 'jwk' }); + return verify(null, bytes, key, Buffer.from(signature, 'base64')); + }; + + beforeAll(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } }); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(plugin); + kernel.registerService(AUDIT_CHECKPOINT_SINK_SERVICE, sink); + await kernel.bootstrap(); + engine = kernel.getService('objectql'); + const sqlite = new SqliteWasmDriver({ filename: ':memory:' }); + await sqlite.connect(); + engine.registerDriver(sqlite, true); + engine.registry.registerObject(sealedLog as never, 'com.objectstack.audit'); + engine.registry.registerObject(SysSecret as never, 'com.objectstack.audit.test.signed-body-readers'); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + + // One mail-log copy at rest in a settled window: one checkpoint, then one redaction amendment. + const past = Math.floor(Date.now() / H) * H - 3 * H; + const hot = engine.getDriverForObject(LOG) as unknown as { create(o: string, r: Row): Promise }; + await hot.create(LOG, { + id: 'mail', created_at: new Date(past + 60_000).toISOString(), action: 'create', object_name: 'sys_email', + record_id: 'mail_rec', tenant_id: 'org_a', new_value: JSON.stringify({ id: 'em_1', subject: 'kept', body_text: MAIL_BODY }), + }); + const sealer = (plugin as unknown as { sealer: AuditSealer }).sealer; + await sealer.stop(); // drive the pass here, not on the loop's clock + expect(await sealer.runPass()).toBe(1); + const report = await migrateMailLogBodyCopies(engine as never, recordingLogger(), { + apply: true, seal: { engine: engine as never, crypto, sink }, objects: [LOG], + }); + expect(report).toMatchObject({ rewritten: 1, refused: 0, failures: 0 }); + expect(delivered.map((e) => e.kind)).toEqual(['checkpoint', 'amendment']); + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + it('a checkpoint: the stored row rebuilds the delivered body byte for byte, and its signature verifies under the stored key', async () => { + const entry = delivered.find((e) => e.kind === 'checkpoint')!; + const rows = (await engine.find('sys_audit_checkpoint', { context: SYS })) as Row[]; + expect(rows).toHaveLength(1); + const [row] = rows; + // The stored row is not the body: its JSON columns are text, and it carries `id`, `chain_key`, `leaf_hashes`, `signature`. + expect(row).not.toEqual(entry.body); + + const body = checkpointBodyFromRow(row); + expect(body).toEqual(entry.body); + expect(signedBodyBytes(body).equals(canonicalJsonBytes(entry.body))).toBe(true); + expect(row.signature).toBe(entry.signature); + expect(body.signing_key_id).toBe(entry.keyId); + expect(await verifiesUnderStoredKey(signedBodyBytes(body), body.signing_key_id, String(row.signature))).toBe(true); + }); + + it('an amendment: the stored row rebuilds the delivered body byte for byte, and its signature verifies under the stored key', async () => { + const entry = delivered.find((e) => e.kind === 'amendment')!; + const rows = (await engine.find('sys_audit_amendment', { context: SYS })) as Row[]; + expect(rows).toHaveLength(1); + const [row] = rows; + // The stored row is not the body: it carries the other kind's columns as NULL, and `id`, `chain_key`, `signature`. + expect(row).not.toEqual(entry.body); + + const body = amendmentBodyFromRow(row); + expect(body).toMatchObject({ kind: 'redaction', sealed_object: LOG, row_id: 'mail', column_name: 'new_value' }); + expect(body).toEqual(entry.body); + expect(signedBodyBytes(body).equals(canonicalJsonBytes(entry.body))).toBe(true); + expect(row.signature).toBe(entry.signature); + expect(body.signing_key_id).toBe(entry.keyId); + expect(await verifiesUnderStoredKey(signedBodyBytes(body), body.signing_key_id, String(row.signature))).toBe(true); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts b/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts index 98300a1d73a..2d816ebe3ca 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts @@ -283,6 +283,31 @@ function columnSet(value: unknown): SealedColumnSet { * A checkpoint's signed body, validated and in canonical form. Accepts a body * or a stored row (whose JSON columns are text); anything outside the body — * `id`, `chain_key`, `signature` — is ignored here. + * + * Exported from the package entry for a checkpoint sink off the host (D11): + * read from an unaltered stored `sys_audit_checkpoint` row, it answers the + * body the sink was handed, whose RFC 8785 form is the bytes the row's + * `signature` covers. + * + * It validates and normalizes; it never verifies the signature. A row whose + * signed columns were rewritten reads back into a body that fails + * verification (a rewrite of `id`, `chain_key` or `leaf_hashes` reads back + * into the same body, and a malformed one is refused with a + * `SignedBodyError`). A row rewritten and re-signed under a key planted on + * the host fails under a key the sink trusts itself. A row rewritten and + * re-signed by whoever holds the genuine signing key verifies; only the + * copies already off the host catch it, because a later checkpoint's signed + * `previous_digest` no longer matches. So a sink verifies the row's + * `signature` over the rebuilt body, under a key it trusts itself, before it + * treats the row as delivered. + * + * A sink assembles the entry it re-delivers itself: `kind` is `'checkpoint'` + * (the table it read), `keyId` is `body.signing_key_id`, and `signature` is + * the row's `signature` column. The signed bytes are the body's RFC 8785 + * (JCS) serialization, which the sink computes with its own serializer: this + * package does not export one. + * + * @public */ export function checkpointBodyFromRow(row: Readonly>): CheckpointSignedBody { const rowIds = json(row, 'row_ids'); @@ -373,7 +398,33 @@ export function checkpointLeafHashesFromRow(row: Readonly>): AmendmentSignedBody { const common = { sealed_object: text(row, 'sealed_object'), diff --git a/packages/plugins/plugin-audit/src/index.ts b/packages/plugins/plugin-audit/src/index.ts index dfa8500200f..51f6525fbc9 100644 --- a/packages/plugins/plugin-audit/src/index.ts +++ b/packages/plugins/plugin-audit/src/index.ts @@ -237,7 +237,11 @@ export type { // the two sealing contexts, and `os audit verify` runs the live check (D9), // writes its proof bundle, and checks one offline. The `os migrate audit-*` // rewrites hold the audit seal lock for their whole `--apply` run (D3 as -// amended by seat ruling 6885005594). +// amended by seat ruling 6885005594). A checkpoint sink off the host (D11) +// rebuilds a stored checkpoint or amendment row into the exact body it was +// handed, so it can re-deliver what a failed call missed +// (`checkpointBodyFromRow`, `amendmentBodyFromRow`, and the two body types +// they answer). // The rest of the pure core (`./audit-seal/`) is reached by path inside this // package. export { @@ -246,7 +250,9 @@ export { AUDIT_SEAL_LOCK_NAME, AUDIT_SEAL_LOCK_WAIT_MS, AUDIT_SEAL_SECRET_HOLDERS, + amendmentBodyFromRow, AuditProofBundleError, + checkpointBodyFromRow, checkpointSeedContext, holdAuditSealLock, isAuditSealSecretCoordinate, @@ -255,10 +261,12 @@ export { verifyAuditProofBundle, } from './audit-seal/index.js'; export type { + AmendmentSignedBody, AuditProofBundle, AuditRowVerdict, AuditSealLockEngine, AuditSealLockFinish, AuditSealLockHold, AuditVerifyReport, + CheckpointSignedBody, } from './audit-seal/index.js';