diff --git a/.changeset/31908-p4b1-sealer-chain-isolation.md b/.changeset/31908-p4b1-sealer-chain-isolation.md new file mode 100644 index 00000000000..dfe247fe84c --- /dev/null +++ b/.changeset/31908-p4b1-sealer-chain-isolation.md @@ -0,0 +1,13 @@ +--- +'@objectstack/plugin-audit': patch +'@objectstack/cli': patch +--- + +fix(plugin-audit, cli): the audit sealer skips only the chain a chain-local fault belongs to; `os serve` hands its crypto provider to an AuditPlugin the app composed with none + +Clause-②: yes (widening) +Metadata-protocol: none + +**The sealer (ADR-0154 D3, S4).** A fault that belongs to one chain of a sealed object — a row a canonical rule refuses, or a malformed checkpoint of that chain (its head among them) — now skips that chain for the rest of the pass instead of stopping the whole object. Every other chain is still sealed. Each chain now resumes from its own oldest unsealed window, as `window` checkpoints, so a skipped chain catches up once its fault is fixed. No checkpoint's `sealed_through` passes a window a skipped chain leaves unsealed. The sealer reports each skipped chain once at `error`, naming the object, the chain, the fault and the window it is unsealed from, and again each hour while it lasts. A lock lapse, a signer, crypto-provider or storage fault still stops the object's pass, as before. `os audit verify` reads the skipped chain's rows in a window another chain sealed as `late` and unsealed, and fails. + +**An app-supplied AuditPlugin (ADR-0154 D2, D6).** An app that puts its own `AuditPlugin` in its stack `plugins` (to turn on `readAudit`, for example) supersedes the one `os serve` composes, and so lost the host's crypto provider: its sealer sealed nothing and said so at `error`. `os serve` now hands it the host's provider when the app composed it with no `cryptoProvider`, and keeps its sealer off on an `OS_MIGRATE_AND_EXIT=1` boot, as for the instance it composes itself. A provider the app composed is never replaced, an app's `armSealer: false` stays off, and a plugin that only carries the AuditPlugin name is never handed anything. The new `AuditPlugin.adoptHostCryptoProvider(provider, { armSealer })` is the method a host calls to do this. diff --git a/packages/cli/src/commands/serve-audit-registration.contract.test.ts b/packages/cli/src/commands/serve-audit-registration.contract.test.ts index aeae20498f1..eb3785a2786 100644 --- a/packages/cli/src/commands/serve-audit-registration.contract.test.ts +++ b/packages/cli/src/commands/serve-audit-registration.contract.test.ts @@ -249,6 +249,18 @@ describe('os serve registers AuditPlugin with no config-derived options, above t expect(SERVE).toMatch(/cap === 'audit' && hostCrypto\s*\?\s*\{ \.\.\.\(arg \?\? \{\}\), cryptoProvider: hostCrypto\.provider, armSealer: !migrateAndExit \}/); }); + it('hands the host crypto provider to an app-supplied AuditPlugin in the stack `plugins` loop, before the kernel takes it (seat ruling 6884540128 item 3)', () => { + // The app's `plugins` entry supersedes the CLI's instance (last one wins), so without this hand-over an app + // that composed its own AuditPlugin seals nothing. The same provider function, the same one-shot posture. + const HAND = 'handHostCryptoToAppAuditPlugin(pluginToLoad, RealAuditPlugin, () => hostCrypto?.provider, !migrateAndExit)'; + const loop = soleOffset(SERVE, PLUGINS_LOOP, 'stack-plugins-loop'); + const hand = soleOffset(SERVE, HAND, 'app AuditPlugin hand-over'); + expect(hand).toBeGreaterThan(loop); + expect(hand).toBeLessThan(soleOffset(SERVE, 'await kernel.use(pluginToLoad);', 'stack-plugin registration')); + // Judged against the real class, loaded once ahead of the loop: never by name, so a lookalike is never fed. + expect(soleOffset(SERVE, '({ AuditPlugin: RealAuditPlugin } = await import(', 'real AuditPlugin class')).toBeLessThan(loop); + }); + it('arms no sealer on an `OS_MIGRATE_AND_EXIT=1` boot, a one-shot job (ADR-0154 D3)', () => { // One reading of the variable, ahead of both constructions; the exit reads the same constant. const reading = "const migrateAndExit = process.env.OS_MIGRATE_AND_EXIT === '1';"; diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index 609f719fa2b..c1f45d9c7e7 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -10,6 +10,7 @@ import { loadConfig, bundleConfigModule } from '../utils/config.js'; import { mergeBootConfig } from '../utils/merge-boot-config.js'; import { provisionTelemetryDatasource, standaloneTelemetryPrimary } from '../utils/telemetry-datasource.js'; import { isHostConfig, shouldBootWithLibrary } from '../utils/plugin-detection.js'; +import { handHostCryptoToAppAuditPlugin } from '../utils/app-audit-plugin-host-crypto.js'; import { mountsAiServicePlugin, resolveAiServiceLoad, resolveOptionalPluginLoad } from '../utils/ai-service-auto-inject.js'; import { registerInstalledPlugins } from '../utils/installed-plugins-boot.js'; import { readInternalArtifactPath, readInternalConfigOutputPath } from '../utils/internal-artifact-channel.js'; @@ -4978,6 +4979,17 @@ export default class Serve extends Command { // got that far), for `refuseUnloadedCryptoProviderPlugins` below. const unloadedStackPlugins: UnloadedStackPlugin[] = []; if (plugins.length > 0) { + // [ADR-0154 D2, D6; seat ruling 6884540128 item 3] The class an app's + // own AuditPlugin is judged by, loaded as this host loads it: only an + // instance of it is handed the host's crypto provider below, never a + // plugin that merely carries its name. Optional, as at 5d. + let RealAuditPlugin: typeof import('@objectstack/plugin-audit').AuditPlugin | undefined; + try { + const auditPkg = '@objectstack/plugin-audit'; + ({ AuditPlugin: RealAuditPlugin } = await import(/* webpackIgnore: true */ auditPkg)); + } catch { + RealAuditPlugin = undefined; + } let index = -1; for (const plugin of plugins) { index += 1; @@ -5014,6 +5026,14 @@ export default class Serve extends Command { // declared contract (`packages/core/src/plugin-registration.ts`), // with a `warn` naming both versions. That is how an app supplies // options to a plugin this CLI mounts without them. + // + // [ADR-0154 D2, D6; seat ruling 6884540128 item 3] An app's own + // AuditPlugin composed with no crypto provider is handed the + // host's — the same provider function, and the same one-shot + // posture, as the instance at 5d and the `requires: ['audit']` + // resolver — so superseding the CLI's instance does not leave the + // sealed objects unsealed. An explicit provider is never replaced. + handHostCryptoToAppAuditPlugin(pluginToLoad, RealAuditPlugin, () => hostCrypto?.provider, !migrateAndExit); await kernel.use(pluginToLoad); stackMountedPlugins.push(pluginToLoad); const pluginName = plugin.name || plugin.constructor?.name || 'unnamed'; diff --git a/packages/cli/src/utils/app-audit-plugin-host-crypto.test.ts b/packages/cli/src/utils/app-audit-plugin-host-crypto.test.ts new file mode 100644 index 00000000000..f4c74e9b5d2 --- /dev/null +++ b/packages/cli/src/utils/app-audit-plugin-host-crypto.test.ts @@ -0,0 +1,45 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { AuditPlugin } from '@objectstack/plugin-audit'; +import { handHostCryptoToAppAuditPlugin } from './app-audit-plugin-host-crypto.js'; + +/** + * [ADR-0154 D2, D6; seat ruling 6884540128 item 3] `os serve` hands its one + * crypto provider to an AuditPlugin the app put in its stack `plugins`: only + * to an instance of the real class, only when the app composed it with none. + */ +describe('os serve hands its crypto provider to an app-supplied AuditPlugin', () => { + const host = () => ({ label: 'host' }) as never; + + it('hands it to a real AuditPlugin composed with no provider', () => { + const plugin = new AuditPlugin({ readAudit: { objects: [] } }); + expect(handHostCryptoToAppAuditPlugin(plugin, AuditPlugin, host, true)).toBe(true); + expect((plugin as unknown as { hostCryptoProvider: unknown }).hostCryptoProvider).toBe(host); + }); + + it('never overrides a provider the app composed it with', () => { + const own = { label: 'own' } as never; + const plugin = new AuditPlugin({ cryptoProvider: own }); + expect(handHostCryptoToAppAuditPlugin(plugin, AuditPlugin, host, true)).toBe(false); + expect((plugin as unknown as { hostCryptoProvider: unknown }).hostCryptoProvider).toBeUndefined(); + }); + + it('never feeds a same-named lookalike, whatever it answers to', () => { + const calls: unknown[] = []; + const lookalike = { name: 'com.objectstack.audit', adoptHostCryptoProvider: (...args: unknown[]) => (calls.push(args), true) }; + expect(handHostCryptoToAppAuditPlugin(lookalike, AuditPlugin, host, true)).toBe(false); + expect(calls).toEqual([]); + }); + + it('feeds nothing when the class could not be loaded, and never throws', () => { + expect(handHostCryptoToAppAuditPlugin(new AuditPlugin(), undefined, host, true)).toBe(false); + expect(handHostCryptoToAppAuditPlugin(undefined, AuditPlugin, host, true)).toBe(false); + }); + + it("keeps the sealer off on a one-shot boot (`armSealer: false`)", () => { + const plugin = new AuditPlugin(); + expect(handHostCryptoToAppAuditPlugin(plugin, AuditPlugin, host, false)).toBe(true); + expect((plugin as unknown as { hostDisarmsSealer: boolean }).hostDisarmsSealer).toBe(true); + }); +}); diff --git a/packages/cli/src/utils/app-audit-plugin-host-crypto.ts b/packages/cli/src/utils/app-audit-plugin-host-crypto.ts new file mode 100644 index 00000000000..d89cf674c76 --- /dev/null +++ b/packages/cli/src/utils/app-audit-plugin-host-crypto.ts @@ -0,0 +1,32 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { AuditPlugin } from '@objectstack/plugin-audit'; +import type { ICryptoProvider } from '@objectstack/spec/contracts'; + +/** + * [ADR-0154 D2, D6; seat ruling 6884540128 item 3] Hand `os serve`'s one + * crypto provider to an AuditPlugin the app put in its stack `plugins`. + * + * The app's entry supersedes the instance the CLI composes (the declared + * last-one-wins registration), and an app composing its own instance for + * `readAudit` rarely spells a crypto provider, so without this its sealer + * seals nothing. The hand-over matches the capability resolver's + * `requires: ['audit']` path: the same provider, and no sealer on a one-shot + * boot (`armSealer: false`). + * + * Only an instance of the real class (`RealAuditPlugin`, as this host loads + * it) is handed anything — never a plugin that merely carries its name — and + * only one the app composed with no provider of its own (the class's + * `adoptHostCryptoProvider` decides that). Nothing here throws or refuses the + * boot: an instance left without a provider reports that once, at `error`, + * from its sealer (ADR-0154 D3). Resolves whether the provider was handed. + */ +export function handHostCryptoToAppAuditPlugin( + plugin: unknown, + RealAuditPlugin: typeof AuditPlugin | undefined, + provider: () => ICryptoProvider | undefined, + armSealer: boolean, +): boolean { + if (RealAuditPlugin === undefined || !(plugin instanceof RealAuditPlugin)) return false; + return plugin.adoptHostCryptoProvider(provider, { armSealer }); +} diff --git a/packages/plugins/plugin-audit/src/audit-plugin.test.ts b/packages/plugins/plugin-audit/src/audit-plugin.test.ts index ae11b0cfa34..087572071d8 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.test.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.test.ts @@ -580,3 +580,47 @@ describe('AuditPlugin — sys_comment access gates are mounted', () => { expect(denials[0].reason).toMatchObject({ code: 'RECORD_NOT_ACCESSIBLE', status: 403 }); }); }); + +describe('AuditPlugin — a host hands an app-supplied instance its crypto provider (ADR-0154 D2, D6; seat ruling 6884540128 item 3)', () => { + const crypto = (label: string) => ({ label }) as never; + /** The sealer `startSealer` composes over a storage double whose registry holds no sealed object: its pass seals nothing. */ + const sealerOf = async (plugin: AuditPlugin): Promise<{ crypto?: unknown } | null> => { + const engine = { getDriverForObject: () => undefined, registry: { getAllObjects: () => [] } }; + const ctx = { logger: { info() {}, warn() {}, error() {}, debug() {} }, getService: () => undefined }; + (plugin as unknown as { startSealer(e: unknown, c: unknown): void }).startSealer(engine, ctx); + const sealer = (plugin as unknown as { sealer: { options: { crypto?: unknown }; stop(): Promise } | null }).sealer; + await sealer?.stop(); + return sealer && sealer.options; + }; + + it('takes the host provider when it was composed with none, and seals under it', async () => { + const plugin = new AuditPlugin({ readAudit: { objects: [] } }); + const host = crypto('host'); + expect(plugin.adoptHostCryptoProvider(() => host, { armSealer: true })).toBe(true); + expect((await sealerOf(plugin))?.crypto).toBe(host); + }); + + it('never overrides a provider the app composed it with', async () => { + const own = crypto('own'); + const plugin = new AuditPlugin({ cryptoProvider: own }); + expect(plugin.adoptHostCryptoProvider(() => crypto('host'), { armSealer: true })).toBe(false); + expect((await sealerOf(plugin))?.crypto).toBe(own); + }); + + it("keeps the sealer off on a host's one-shot boot, and an app's own `armSealer: false` stands", async () => { + const oneShot = new AuditPlugin(); + expect(oneShot.adoptHostCryptoProvider(() => crypto('host'), { armSealer: false })).toBe(true); + expect(await sealerOf(oneShot)).toBeNull(); + const off = new AuditPlugin({ armSealer: false }); + expect(off.adoptHostCryptoProvider(() => crypto('host'), { armSealer: true })).toBe(true); + expect(await sealerOf(off)).toBeNull(); + }); + + it('composes no provider when the host has none to hand: the sealer reports it once, at error (D3)', async () => { + const plugin = new AuditPlugin(); + expect(plugin.adoptHostCryptoProvider(() => undefined, { armSealer: true })).toBe(true); + const sealer = await sealerOf(plugin); + expect(sealer).not.toBeNull(); + expect(sealer?.crypto).toBeUndefined(); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 543a893a11c..698af38f964 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -325,9 +325,34 @@ export class AuditPlugin implements Plugin { * at `kernel:ready`; the activity door's writer reads it at each call. */ private actorSnapshotOf: ((api: unknown, userId: string) => Promise) | undefined; + /** [ADR-0154 D2, D6] The provider a host handed over, for an instance composed with none. */ + private hostCryptoProvider: (() => ICryptoProvider | undefined) | undefined; + /** [ADR-0154 D3] Set when a host that handed its provider over is a one-shot boot. */ + private hostDisarmsSealer = false; constructor(private readonly options: AuditPluginOptions = {}) {} + /** + * [ADR-0154 D2, D6; seat ruling 6884540128 item 3] A host hands an instance + * the app composed (a stack `plugins` entry) the host's own crypto provider, + * which the sealer then seals under. It is taken only when this instance was + * composed with no `cryptoProvider`: one the app composed is never + * overridden. `armSealer: false` — the host's one-shot boot — keeps the + * sealer off; `true` leaves this instance's own `armSealer` standing, so an + * app's `armSealer: false` is never turned on. + * + * The provider is read when the sealer starts (`kernel:ready`), so a host + * hands it over before then. Resolves whether it was taken. A provider that + * answers `undefined` is an absent one: the sealer reports it once, at + * `error`, and seals nothing; the boot is never refused. + */ + adoptHostCryptoProvider(provider: () => ICryptoProvider | undefined, host: { armSealer: boolean }): boolean { + if (this.options.cryptoProvider !== undefined) return false; + this.hostCryptoProvider = provider; + if (!host.armSealer) this.hostDisarmsSealer = true; + return true; + } + async init(ctx: PluginContext): Promise { // Register audit system objects via the manifest service. ctx.getService<{ register(m: any): void }>('manifest').register({ @@ -768,11 +793,11 @@ export class AuditPlugin implements Plugin { * command's boot (`armSealer: false`). */ private startSealer(engine: IDataEngine, ctx: PluginContext): void { - if (this.options.armSealer === false) return; + if (this.options.armSealer === false || this.hostDisarmsSealer) return; const storage = engine as unknown as Partial; if (typeof storage.getDriverForObject !== 'function' || typeof storage.registry?.getAllObjects !== 'function') return; const sealEngine = storage as AuditSealerEngine; - const option = this.options.cryptoProvider; + const option = this.options.cryptoProvider ?? this.hostCryptoProvider; const crypto = typeof option === 'function' ? option() : option; const localSigner = crypto ? new LocalCheckpointSigner({ engine: sealEngine, crypto }) : undefined; const optional = (name: string): T | undefined => { diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-sealer.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-sealer.test.ts index 995068dcd5d..8c54358618a 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-sealer.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-sealer.test.ts @@ -2,7 +2,7 @@ import type { IAuditCheckpointSigner, IClusterService, LockHandle } from '@objectstack/spec/contracts'; import { describe, expect, it } from 'vitest'; -import { checkpointBodyFromRow, checkpointDigest, signedBodyBytes } from './index.js'; +import { checkpointBodyFromRow, checkpointDigest, signedBodyBytes, verifyAuditLedger } from './index.js'; import { bindingCrypto, memoryEngine, recordingLogger } from './seal-store.testkit.js'; import { AUDIT_SEALER_LOCK, AuditSealer } from './sealer.js'; import { LocalCheckpointSigner } from './signer.js'; @@ -204,6 +204,107 @@ describe('late rows: re-counted and sealed as late, before the pass seals its wi }); }); +describe('per-chain isolation: only a chain-local fault skips a chain, and only that chain (S4, seat ruling 6884540128 item 2)', () => { + /** A row the canonical rule of its `payload` column (text) refuses: a number. */ + const refused = (id: string, created: string, tenant: string | null) => ({ ...row(id, created, tenant), payload: 42 }); + const errors = (s: ReturnType) => s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message); + + it('skips the chain of a row a canonical rule refuses, seals every other chain, and holds sealed_through at the skipped window', async () => { + const s = setup(); + s.hot.table('ledger_probe').push( + row('a1', at(8, 10)), refused('b1', at(8, 20), 'org_b'), row('d1', at(8, 30), null), + row('a2', at(9, 10)), row('b2', at(9, 20), 'org_b'), row('a3', at(10, 10)), + ); + expect(await s.sealer.runPass()).toBe(4); + expect(s.checkpoints().map((c) => [c.window_start, c.tenant_id, c.kind, c.row_ids, c.sealed_through])).toEqual([ + [at(8, 0), null, 'window', ['d1'], at(8, 0)], + [at(8, 0), 'org_a', 'window', ['a1'], at(8, 0)], + // org_b is out for the rest of the pass, so the 09:00 window has a skipped chain: no watermark past 08:00. + [at(9, 0), 'org_a', 'window', ['a2'], at(8, 0)], + [at(10, 0), 'org_a', 'window', ['a3'], at(8, 0)], + ]); + expect(errors(s)).toEqual([expect.stringMatching(/'ledger_probe'.*chain 'org:org_b'.*b1\.payload.*not text.*NOT being sealed/)]); + }); + + it('resumes a skipped chain from its own oldest unsealed window, as window checkpoints and not late ones', async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('a1', at(8, 10)), refused('b1', at(8, 20), 'org_b'), row('a2', at(9, 10)), row('b2', at(9, 20), 'org_b')); + expect(await s.sealer.runPass()).toBe(2); + s.hot.table('ledger_probe').find((r) => r.id === 'b1')!.payload = '{"v":"b1"}'; + expect(await s.sealer.runPass()).toBe(2); + expect(s.checkpoints().slice(2).map((c) => [c.window_start, c.tenant_id, c.kind, c.sequence, c.row_ids, c.sealed_through])).toEqual([ + [at(8, 0), 'org_b', 'window', 0, ['b1'], at(8, 0)], + [at(9, 0), 'org_b', 'window', 1, ['b2'], at(9, 0)], + ]); + expect(await s.sealer.runPass()).toBe(0); + }); + + it('skips the chain whose head checkpoint is malformed, and seals the others past it', async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('a1', at(8, 10)), row('b1', at(8, 20), 'org_b')); + expect(await s.sealer.runPass()).toBe(2); + s.hot.table('sys_audit_checkpoint').find((r) => r.tenant_id === 'org_b')!.root = 'not a digest'; + s.hot.table('ledger_probe').push(row('a2', at(9, 10)), row('b2', at(9, 20), 'org_b'), row('a3', at(10, 10))); + expect(await s.sealer.runPass()).toBe(2); + expect(s.hot.table('sys_audit_checkpoint').slice(2).map((r) => checkpointBodyFromRow(r)).map((c) => [c.tenant_id, c.sequence, c.row_ids, c.sealed_through])) + .toEqual([['org_a', 1, ['a2'], at(9, 0)], ['org_a', 2, ['a3'], at(9, 0)]]); + expect(errors(s)).toEqual([expect.stringMatching(/'ledger_probe'.*chain 'org:org_b'.*root.*NOT being sealed/)]); + }); + + it('seals window-major: on a healthy backlog past the per-pass budget, every chain ends each pass at the same window, a sparse one included', async () => { + const s = setup(); + s.clock.now = DAY0 + 40 * H; // windows up to 39:00 are due + // org_a writes every hour for 30 hours, more windows than one pass seals; org_b only at hours 0, 11, 23 and 29. + for (let h = 0; h < 30; h++) s.hot.table('ledger_probe').push(row(`a${h}`, at(h, 10))); + for (const h of [0, 11, 23, 29]) s.hot.table('ledger_probe').push(row(`b${h}`, at(h, 20), 'org_b')); + const newest = () => { + const by: Record = {}; + for (const c of s.checkpoints()) if (c.kind === 'window' && !(by[String(c.tenant_id)] > c.window_start)) by[String(c.tenant_id)] = c.window_start; + return by; + }; + expect(await s.sealer.runPass()).toBe(24 + 3); + expect(newest()).toEqual({ org_a: at(23, 0), org_b: at(23, 0) }); + expect(await s.sealer.runPass()).toBe(6 + 1); + expect(newest()).toEqual({ org_a: at(29, 0), org_b: at(29, 0) }); + expect(s.checkpoints().filter((c) => c.kind === 'late')).toEqual([]); + }); + + it("never seals a lagging chain's rows as late: skipped where another chain sealed, it recovers into window checkpoints, while that chain's own late row is sealed late", async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('y1', at(8, 10)), refused('x1', at(8, 20), 'org_x'), row('y2', at(9, 10)), row('x2', at(9, 20), 'org_x')); + expect(await s.sealer.runPass()).toBe(2); // org_a seals 08:00 and 09:00; org_x is skipped at 08:00 + s.hot.table('ledger_probe').find((r) => r.id === 'x1')!.payload = '{"v":"x1"}'; + s.hot.table('ledger_probe').push(row('y-late', at(8, 40))); // so the late pass reads the 08:00 window + expect(await s.sealer.runPass()).toBe(3); + expect(s.checkpoints().filter((c) => c.tenant_id === 'org_x').map((c) => [c.kind, c.window_start, c.sequence, c.row_ids])) + .toEqual([['window', at(8, 0), 0, ['x1']], ['window', at(9, 0), 1, ['x2']]]); + expect(s.checkpoints().filter((c) => c.kind === 'late').map((c) => [c.tenant_id, c.window_start, c.row_ids])).toEqual([['org_a', at(8, 0), ['y-late']]]); + }); + + it('still aborts the whole pass on a storage fault: no chain is skipped past it', async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('a1', at(8, 10)), row('b1', at(8, 20), 'org_b'), row('a2', at(9, 10))); + const insert = s.engine.insert.bind(s.engine); + s.engine.insert = async (object, r, o) => { + if (object === 'sys_audit_checkpoint' && r.tenant_id === 'org_a') throw new Error('connection reset'); + return insert(object, r, o); + }; + expect(await s.sealer.runPass()).toBe(0); + expect(s.hot.table('sys_audit_checkpoint')).toEqual([]); + expect(errors(s)).toEqual([expect.stringMatching(/sealing 'ledger_probe' FAILED \(connection reset\)/)]); + }); + + it("keeps verify loud: the skipped chain's rows read unsealed and the verdict is not ok", async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('a1', at(8, 10)), refused('b1', at(8, 20), 'org_b'), row('a2', at(9, 10)), row('b2', at(9, 20), 'org_b')); + await s.sealer.runPass(); + const report = await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); + expect(report.ok).toBe(false); + expect(report.totals).toMatchObject({ unmodified: 2, late: 2, unsealed: 2 }); + expect(report.chains.find((c) => c.chain === 'org:org_b')?.counts).toMatchObject({ late: 2, unsealed: 2 }); + }); +}); + describe('the lock: audit.sealer, its fencing token on each checkpoint (D3, Q2 (a))', () => { const lockedCluster = (token: bigint | null, onAcquire: (key: string) => void = () => {}) => { let held = token !== null; diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index 03594ffc7e9..5e40b5178ea 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -12,6 +12,7 @@ import type { import { isMissingTableError } from '@objectstack/types'; import { AUDIT_SEAL_CANON_VERSION, + CanonicalFormError, canonicalDatetime, leafHash, leafInput, @@ -35,6 +36,7 @@ import { checkpointDigest, checkpointRow, signedBodyBytes, + SignedBodyError, type AuditCheckpointKind, type CheckpointSignedBody, } from './signed-body.js'; @@ -61,6 +63,15 @@ import { dropAuditSealSecret, writeAuditSealSecret, type SealStorageDriver, type * Each checkpoint carries the sealed-through watermark: the end of the last * window the sealer had completed for every chain when it wrote it. * + * S4 (seat ruling 6884540128 item 2): a fault is isolated to the smallest + * thing it belongs to. A chain-local fault — a row a canonical rule refuses, + * or a malformed checkpoint of the chain (its head among them) — skips that + * chain for the rest of the pass; the other chains are sealed, and each chain + * resumes from its own oldest unsealed window, since every chain carries its + * own cursor. The watermark never advances past a window a skipped chain + * leaves unsealed. Every other fault — the lock, the signer, the crypto + * provider, the storage — stops the whole object's pass. + * * Nothing here writes the sealed object, and every secret row is written * below the hooks, so the sealer never seals its own writes. */ @@ -134,6 +145,19 @@ interface ChainLeaves { const iso = (ms: number): string => new Date(ms).toISOString(); +/** + * S4: a fault that belongs to one chain — a row of it a canonical rule + * refuses, or a malformed checkpoint of it. It skips that chain only. + */ +class ChainFault extends Error { + constructor(readonly chainKey: string, readonly fault: unknown) { + super(faultOf(fault)); + } +} + +/** Whether `err` is chain-local when it is thrown reading one chain's row or checkpoint (S4). */ +const isChainLocal = (err: unknown): boolean => err instanceof CanonicalFormError || err instanceof SignedBodyError; + /** * A fault as a report line may quote it: its code and the driver's own reason, * never the statement. A SQL driver's message leads with the statement and its @@ -216,6 +240,23 @@ export class AuditSealer { this.options.logger.error(message()); } + /** + * S4: each chain a chain-local fault skipped, at `error`, once per cause per + * {@link REPORT_REPEAT_MS} while it lasts; a chain sealed again is forgotten. + */ + private reportSkipped(object: string, skipped: ReadonlyMap): void { + for (const cause of this.reported.keys()) { + if (!cause.startsWith(`chain:${object}:`)) continue; + if (![...skipped.keys()].some((key) => cause.startsWith(`chain:${object}:${key}:`))) this.reported.delete(cause); + } + for (const [key, { fault, from }] of skipped) { + this.report(`chain:${object}:${key}:${fault}`, () => + `AuditSealer: '${object}' chain '${key}' is skipped (${fault}) — its rows from the window of ${iso(from)} on are ` + + 'NOT being sealed, and no checkpoint\'s sealed_through passes that window; every other chain is sealed. ' + + 'Each pass retries the chain from that window. Fix the fault named here.'); + } + } + /** The sealed objects the registry holds that can be sealed; each that cannot is reported. */ private plans(): SealPlan[] { const plans: SealPlan[] = []; @@ -301,6 +342,7 @@ export class AuditSealer { 'sealed until a pass gets past it; each pass retries. Fix the fault named here.'); } finally { written += pass?.written ?? 0; + if (pass) this.reportSkipped(plan.name, pass.skipped); } } return written; @@ -317,6 +359,12 @@ class ObjectPass { private readonly archive: SealStorageDriver | undefined; private readonly checkpoints: SealStorageDriver; private watermark: number | null = null; + /** The stored watermark when the pass began: every chain is complete before it. */ + private floor: number | null = null; + /** S4: each chain's own cursor, the start of the window after its last `window` checkpoint. */ + private readonly cursors = new Map(); + /** S4: the chains a chain-local fault put out for the rest of this pass, and the window each stays unsealed from. */ + readonly skipped = new Map(); /** Checkpoints this pass wrote, counted as each lands. */ written = 0; /** The key id the last checkpoint of this pass was signed under: the next body's expectation. */ @@ -351,43 +399,81 @@ class ObjectPass { limit: 1, }); this.watermark = top ? Date.parse(canonicalDatetime(top.sealed_through, 'sealed_through')) : null; - const [last] = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { - where: { sealed_object: this.plan.name, kind: 'window' }, - orderBy: [{ field: 'window_start', order: 'desc' }], - limit: 1, - }); - const lastWindow = last ? Date.parse(canonicalDatetime(last.window_start, 'window_start')) : null; + this.floor = this.watermark; + // S4: each chain's cursor, from its `window` checkpoints at or past the floor. A chain the floor passed with + // none there has the floor as its cursor; the latest `window` checkpoint is never below the floor. + let lastWindow: number | null = null; + if (this.floor !== null) { + const recent = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { + where: { sealed_object: this.plan.name, kind: 'window', window_start: { $gte: iso(this.floor) } }, + }); + for (const row of recent) { + const key = String(row.chain_key); + let start: number; + try { + start = Date.parse(canonicalDatetime(row.window_start, 'window_start')); + } catch (err) { + this.skip(key, err, this.floor); + continue; + } + this.cursors.set(key, Math.max(this.cursors.get(key) ?? start + AUDIT_SEAL_WINDOW_MS, start + AUDIT_SEAL_WINDOW_MS)); + lastWindow = Math.max(lastWindow ?? start, start); + } + } const due = windowOf(this.now - AUDIT_SEAL_SETTLE_MS); - let resumed: Set | null = null; - if (lastWindow !== null) resumed = await this.sealLate(lastWindow); + if (lastWindow !== null) await this.sealLate(lastWindow); - let cursor: number | null = lastWindow; + let cursor: number | null = this.floor; if (cursor === null) { const oldest = await this.firstRowAt(null, due); if (oldest === null) return this.written; cursor = windowOf(oldest); } - for (let n = 0; n < MAX_WINDOWS_PER_PASS; n++) { + // Windows oldest first from the floor; each chain is sealed from its own cursor. A window that only re-reads + // chains already sealed (or skipped) past it does not count toward the pass's windows. + for (let n = 0; n < MAX_WINDOWS_PER_PASS;) { const next = await this.firstRowAt(cursor, due); if (next === null) break; const start = windowOf(next); - const done = start === lastWindow ? resumed : null; - const chains = await this.readWindow(start, (row) => !done?.has(chainKeyOf(tenantOf(row)))); - await this.writeChains(chains, start, 'window', Math.max(this.watermark ?? start, start)); + const chains = await this.readWindow(start, (row) => start >= this.cursorOf(chainKeyOf(tenantOf(row)))); + if (chains.size > 0) n += 1; + await this.writeChains(chains, start, 'window', Math.max(this.watermark ?? Number.NEGATIVE_INFINITY, Math.min(start, this.stuckFrom()))); cursor = start + AUDIT_SEAL_WINDOW_MS; } return this.written; } + /** S4: the first window of chain `key` this pass may seal as a `window`; a row of it before is `late`. */ + private cursorOf(key: string): number { + return Math.max(this.floor ?? Number.NEGATIVE_INFINITY, this.cursors.get(key) ?? Number.NEGATIVE_INFINITY); + } + + /** S4: the earliest window a skipped chain leaves unsealed; no watermark passes it. */ + private stuckFrom(): number { + let from = Number.POSITIVE_INFINITY; + for (const skip of this.skipped.values()) from = Math.min(from, skip.from); + return from; + } + + /** + * S4: put chain `key` out for the rest of the pass over a chain-local fault + * met at window `at`. It stays unsealed from its own oldest unsealed window: + * its cursor, or `at` when the fault was met past it. + */ + private skip(key: string, fault: unknown, at: number): void { + if (this.skipped.has(key)) return; + this.skipped.set(key, { fault: faultOf(fault instanceof ChainFault ? fault.fault : fault), from: Math.max(this.cursorOf(key), at) }); + } + /** * Late rows (D3): each sealed window of the horizon whose stored count * differs from what its checkpoints list is read, and each unlisted row is - * sealed into a `late` checkpoint of its chain. In the last sealed window a - * chain with no `window` checkpoint yet is left to the window pass, which - * resumes it. Resolves to the chains that window already holds. + * sealed into a `late` checkpoint of its chain. A row is late only before its + * chain's own cursor; at or past it, the window pass seals it (S4), which is + * how a chain a stopped pass (or a skip) left behind resumes as `window`. */ - private async sealLate(lastWindow: number): Promise> { + private async sealLate(lastWindow: number): Promise { const from = windowOf(this.now - AUDIT_SEAL_LATE_HORIZON_MS); const to = lastWindow + AUDIT_SEAL_WINDOW_MS; const listed = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { @@ -395,22 +481,34 @@ class ObjectPass { }); const byWindow = new Map(); for (const row of listed) { - const start = Date.parse(canonicalDatetime(row.window_start, 'window_start')); + let start: number; + try { + start = Date.parse(canonicalDatetime(row.window_start, 'window_start')); + } catch (err) { + this.skip(String(row.chain_key), err, this.floor ?? from); + continue; + } byWindow.set(start, [...(byWindow.get(start) ?? []), row]); } - const resumed = new Set((byWindow.get(lastWindow) ?? []).filter((r) => r.kind === 'window').map((r) => String(r.chain_key))); const listedCount = (rows: readonly Row[]) => rows.reduce((sum, r) => sum + Number(r.leaf_count), 0); for (let start = from; start < to; start += AUDIT_SEAL_WINDOW_MS) { // S6: each window re-counted on its own, so a delete in one cannot hide a late row in another. await this.lock.renew(LOCK_TTL_MS); const holders = byWindow.get(start) ?? []; if ((await this.countRows(start, start + AUDIT_SEAL_WINDOW_MS)) === listedCount(holders)) continue; - const ids = new Set(holders.flatMap((r) => checkpointBodyFromRow(r).row_ids)); + const ids = new Set(); + for (const holder of holders) { + try { + for (const id of checkpointBodyFromRow(holder).row_ids) ids.add(id); + } catch (err) { + if (!isChainLocal(err)) throw err; + this.skip(String(holder.chain_key), err, start); // S4: a malformed checkpoint of its chain + } + } const chains = await this.readWindow(start, (row) => - !ids.has(rowIdOf(row)) && (start !== lastWindow || resumed.has(chainKeyOf(tenantOf(row))))); + !ids.has(rowIdOf(row)) && start < this.cursorOf(chainKeyOf(tenantOf(row)))); await this.writeChains(chains, start, 'late', this.watermark ?? start); } - return resumed; } /** The stores a pass reads: the hot store, then the archive. */ @@ -484,19 +582,27 @@ class ObjectPass { limit: PAGE_SIZE, }); for (const row of rows) { - const id = rowIdOf(row); - const at = canonicalDatetime(row.created_at, `${id}.created_at`); - if (seen.has(id) || windowOf(Date.parse(at)) !== start || !accept(row)) continue; - seen.add(id); const tenantId = tenantOf(row); const key = chainKeyOf(tenantId); - let chain = chains.get(key); - if (!chain) { - chain = { tenantId, seed: generateCheckpointSeed(), leaves: [] }; - chains.set(key, chain); + if (this.skipped.has(key)) continue; // S4: out for the rest of the pass + try { + const id = rowIdOf(row); + const at = canonicalDatetime(row.created_at, `${id}.created_at`); + if (seen.has(id) || windowOf(Date.parse(at)) !== start || !accept(row)) continue; + seen.add(id); + let chain = chains.get(key); + if (!chain) { + chain = { tenantId, seed: generateCheckpointSeed(), leaves: [] }; + chains.set(key, chain); + } + const leaf = leafInput(row, this.plan.columns, this.plan.fields, columnSaltsOf(chain.seed, this.plan.name)); + chain.leaves.push({ id, at, hash: leafHash(leaf) }); + } catch (err) { + // S4: a row a canonical rule refuses skips its chain, and only its chain. + if (!(err instanceof CanonicalFormError)) throw err; + this.skip(key, err, start); + chains.delete(key); } - const leaf = leafInput(row, this.plan.columns, this.plan.fields, columnSaltsOf(chain.seed, this.plan.name)); - chain.leaves.push({ id, at, hash: leafHash(leaf) }); } if (rows.length < PAGE_SIZE) break; after = rows[rows.length - 1]; @@ -512,17 +618,35 @@ class ObjectPass { orderBy: [{ field: 'sequence', order: 'desc' }], limit: 1, }); - const head = row ? (() => { - const body = checkpointBodyFromRow(row); - return { sequence: body.sequence, digest: checkpointDigest(body) }; - })() : null; + let head: ChainHead | null = null; + if (row) { + let body: CheckpointSignedBody; + try { + body = checkpointBodyFromRow(row); + } catch (err) { + if (!isChainLocal(err)) throw err; + throw new ChainFault(chainKey, err); // S4: a malformed chain head skips its chain + } + head = { sequence: body.sequence, digest: checkpointDigest(body) }; + } this.heads.set(chainKey, head); return head; } private async writeChains(chains: Map, start: number, kind: AuditCheckpointKind, watermark: number): Promise { // `readWindow` makes a chain only with its first leaf, so no checkpoint is empty (D3). - for (const key of [...chains.keys()].sort()) await this.writeCheckpoint(key, chains.get(key)!, start, kind, watermark); + for (const key of [...chains.keys()].sort()) { + if (this.skipped.has(key)) continue; + try { + await this.writeCheckpoint(key, chains.get(key)!, start, kind, watermark); + } catch (err) { + // S4: only a chain-local fault of this chain skips it; every other fault stops the object's pass. + if (!(err instanceof ChainFault) || err.chainKey !== key) throw err; + this.skip(key, err, start); + continue; + } + if (kind === 'window') this.cursors.set(key, start + AUDIT_SEAL_WINDOW_MS); + } if (kind === 'window') this.watermark = Math.max(this.watermark ?? watermark, watermark); } @@ -554,7 +678,7 @@ class ObjectPass { // N1: the window's checkpoints, re-read once this chain's head is known: a row another sealer listed // since this pass read the window's lists is not sealed twice. One stored after the head was known // takes a sequence at or past this one, so the unique index refuses whichever insert comes second. - const listed = await this.listedIn(start); + const listed = await this.listedIn(start, chainKey); leaves = leaves.filter((leaf) => !listed.has(leaf.id)); if (leaves.length === 0) return; } @@ -625,12 +749,26 @@ class ObjectPass { await this.deliver(body, keyId, signature); } - /** The row ids the stored checkpoints of window `start` list, every chain's, as read now. */ - private async listedIn(start: number): Promise> { + /** + * The row ids the stored checkpoints of window `start` list, every chain's, + * as read now. A malformed one skips its chain (S4): this chain's, with a + * {@link ChainFault}; another's, for the rest of the pass. + */ + private async listedIn(start: number, chainKey: string): Promise> { const rows = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { where: { sealed_object: this.plan.name, window_start: { $gte: iso(start), $lt: iso(start + AUDIT_SEAL_WINDOW_MS) } }, }); - return new Set(rows.flatMap((r) => checkpointBodyFromRow(r).row_ids)); + const ids = new Set(); + for (const row of rows) { + try { + for (const id of checkpointBodyFromRow(row).row_ids) ids.add(id); + } catch (err) { + if (!isChainLocal(err)) throw err; + if (String(row.chain_key) === chainKey) throw new ChainFault(chainKey, err); + this.skip(String(row.chain_key), err, start); + } + } + return ids; } /** This chain's stored checkpoint matching `where`, if any. */