From 130e4f34ab725258d9b8ec1dfb58679c70886b62 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:19:23 +0000 Subject: [PATCH 01/16] wip(objectql): sealed-object expiry seam beside the reap guard (ADR-0154 D8) Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt Co-authored-by: Claude --- packages/objectql/src/index.ts | 4 + .../src/lifecycle/lifecycle-service.ts | 254 +++++++++++++++++- 2 files changed, 254 insertions(+), 4 deletions(-) diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 1f7c4966b2f..ff3621c42db 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -801,6 +801,10 @@ export type { LifecycleSettingsLike, LifecycleGovernanceAlert, LifecycleReapGuard, + // [ADR-0154 D8] The sealed-object expiry seam beside the reap guard. + LifecycleSealedExpiry, + LifecycleSealedExpiryRequest, + LifecycleSealedExpiryRun, // [#5195] Consumer-declared floors on settings-driven window overrides. LifecycleRetentionFloor, LifecycleFloorViolation, diff --git a/packages/objectql/src/lifecycle/lifecycle-service.ts b/packages/objectql/src/lifecycle/lifecycle-service.ts index a53a1b393c8..35f244bfd6f 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.ts @@ -411,7 +411,8 @@ export interface LifecycleFloorViolation { export interface LifecycleSweepEntry { object: string; class: string; - policy: 'ttl' | 'retention' | 'rotation' | 'rotation-fallback' | 'archive'; + /** `expiry`: [ADR-0154 D8] a sealed object's whole checkpoints, through {@link LifecycleSealedExpiry}. */ + policy: 'ttl' | 'retention' | 'rotation' | 'rotation-fallback' | 'archive' | 'expiry'; cutoff: string; /** `undefined` when the driver doesn't report a count. */ deleted?: number; @@ -522,6 +523,45 @@ export type LifecycleReapGuard = ( rows: Array>, ) => Promise>; +/** + * [ADR-0154 D8] What the sweep asks the sealed-object expiry for, once per + * sweep and policy of an object that declares `lifecycle.seal`. + */ +export interface LifecycleSealedExpiryRequest { + readonly object: string; + /** The policy whose window expires the rows. */ + readonly policy: 'archive.keep' | 'retention.maxAge' | 'ttl.expireAfter'; + /** Its duration literal as this sweep applies it (`'7y'`): what the expiry amendment signs. */ + readonly policyValue: string; + /** Rows of windows that ended at or before this instant may expire (ISO-8601, UTC). */ + readonly cutoff: string; +} + +/** One chain's expiry, planned and signed: the rows the sweep deletes, then {@link complete}. */ +export interface LifecycleSealedExpiryRun { + /** The chain, for the report. */ + readonly chain: string; + /** Exactly the rows the removed checkpoints list. The sweep deletes these and no other. */ + readonly rowIds: readonly string[]; + /** Called once every listed row is gone from every store: removes the checkpoints and their seeds. */ + complete(): Promise; +} + +/** + * [ADR-0154 D8] The expiry of a sealed object, the seam beside + * {@link LifecycleReapGuard}. A sealed object's rows never go by a row-granular + * cutoff, which would cut a sealed window in half and make an honest expiry + * read as `missing`. The sealer's owner (`@objectstack/plugin-audit`) answers + * which whole checkpoints of each chain have expired and writes the signed + * `expiry` amendment for them before it answers; the sweep then deletes + * exactly the rows they list and only then calls {@link LifecycleSealedExpiryRun.complete}. + * A plan that throws keeps every row for the next sweep, as a vetoing reap + * guard does. + */ +export interface LifecycleSealedExpiry { + plan(request: LifecycleSealedExpiryRequest): Promise; +} + export class LifecycleService { private readonly now: () => number; private timer: ReturnType | undefined; @@ -544,6 +584,10 @@ export class LifecycleService { * {@link registerRetentionFloor} keys by registrar rather than overwriting. */ private readonly reapGuards = new Map(); + /** [ADR-0154 D8] The one sealed-object expiry, when the sealer's owner registered it. */ + private sealedExpiry: LifecycleSealedExpiry | undefined; + /** [ADR-0154 D8] Sealed objects already said about, by cause, so a standing state is said once. */ + private readonly sealedSaid = new Set(); /** * [#5195] Registered retention floors, keyed `object::policy::declaredBy` so * a re-registration replaces rather than accumulates, while two independent @@ -857,6 +901,33 @@ export class LifecycleService { if (!guards.includes(guard)) guards.push(guard); } + /** + * [ADR-0154 D8] Register the expiry every object declaring `lifecycle.seal` + * expires through. One slot: the sealer's owner registers it, and a later + * registration replaces it (a re-initialised plugin). Answers the + * unregistration, which clears the slot only while it still holds this one. + * + * Until one is registered, a sealed object's expiring rows are KEPT: the + * sweep never deletes a sealed row by its own cutoff (see {@link sweepSealed}). + */ + registerSealedExpiry(expiry: LifecycleSealedExpiry): () => void { + if (!expiry || typeof expiry.plan !== 'function') { + throw new Error('[lifecycle] registerSealedExpiry requires an object with a plan(request) method'); + } + this.sealedExpiry = expiry; + this.sealedSaid.clear(); + return () => { + if (this.sealedExpiry === expiry) this.sealedExpiry = undefined; + }; + } + + /** Say a standing sealed-object state once, at `warn`; a changed one speaks again. */ + private saySealedOnce(cause: string, message: string): void { + if (this.sealedSaid.has(cause)) return; + this.sealedSaid.add(cause); + this.opts.logger.warn(message); + } + /** Snapshot of the guards governing `object`, in registration order — a copy, * so a registration mid-sweep cannot change the set a reap in flight is * consulting. */ @@ -1482,6 +1553,8 @@ export class LifecycleService { if (lc.archive) { return this.archiveObject(engine, obj, lc, report); } + // [ADR-0154 D8] A sealed object expires by whole checkpoints, never by a row cutoff. + if (lc.seal) return this.reapSealed(engine, obj, lc, report); const outcomes: Array = []; // Governance overrides (P4): a configured window beats the declared one. @@ -1582,6 +1655,149 @@ export class LifecycleService { return outcomes; } + /** + * [ADR-0154 D8] The reap of a sealed object that declares no archive: each + * declared window (`ttl` on `created_at`, `retention`) expires whole + * checkpoints through {@link sweepSealed}. The spec refuses every other + * policy beside `seal` (`onlyWhen`, a `ttl` on another field, rotation). + * + * A settings override of the window applies as on any object, through the + * same floors, and the value applied is the one the amendment signs. A + * tenant-scoped override does not: a sealed chain's expiry is signed with one + * policy value per sweep, so it is said once and the global window stands. + */ + private async reapSealed( + engine: LifecycleEngineLike, + obj: LifecycleObjectLike, + lc: Lifecycle, + report: LifecycleSweepReport, + ): Promise> { + const object = obj.name; + const ov = this.governance.overrides[object] ?? {}; + const legs: Array<{ + policy: LifecycleSealedExpiryRequest['policy']; + kind: 'ttl' | 'retention'; + key: 'expireAfter' | 'maxAge'; + declared: string; + }> = []; + if (lc.ttl) legs.push({ policy: 'ttl.expireAfter', kind: 'ttl', key: 'expireAfter', declared: lc.ttl.expireAfter }); + if (lc.retention) legs.push({ policy: 'retention.maxAge', kind: 'retention', key: 'maxAge', declared: lc.retention.maxAge }); + const outcomes: Array = []; + for (const leg of legs) { + const tenants = (this.governance.tenantOverrides.get(object) ?? []).filter((t) => typeof t[leg.key] === 'string'); + if (tenants.length > 0) { + this.saySealedOnce( + `tenant-override:${object}:${leg.key}`, + `[lifecycle] ${object} declares lifecycle.seal, so its tenant-scoped ${leg.key} override(s) ` + + `(${tenants.map((t) => t.tenantId).join(', ')}) do not apply: a sealed chain expires by whole checkpoints ` + + `under one signed policy value, and the global ${leg.policy} window stands for every organization.`, + ); + } + const override = ov[leg.key]; + const windowMs = this.effectiveWindowMs(override, parseLifecycleDuration(leg.declared), object, leg.kind, 'global', report); + outcomes.push( + await this.sweepSealed( + engine, + obj, + lc, + { policy: leg.policy, policyValue: appliedLiteral(override, leg.declared, windowMs), cutoffMs: this.now() - windowMs }, + report, + null, + ), + ); + } + return outcomes; + } + + /** + * [ADR-0154 D8] One policy's expiry of a sealed object. The registered + * {@link LifecycleSealedExpiry} plans it and signs each chain's `expiry` + * amendment first; then exactly the rows each run lists are deleted — from + * `stores` (the hot store and the archive, by id) when the object archives, + * else through the engine like any reap, its guards asked — and only then + * is the run completed, which removes its checkpoints and seeds. A run whose + * rows are not all gone (a guard kept one) is not completed: the next sweep + * resumes it. + * + * No expiry registered ⇒ nothing is deleted, and that is said once. + */ + private async sweepSealed( + engine: LifecycleEngineLike, + obj: LifecycleObjectLike, + lc: Lifecycle, + leg: { policy: LifecycleSealedExpiryRequest['policy']; policyValue: string; cutoffMs: number }, + report: LifecycleSweepReport, + stores: readonly ArchiveCapableDriver[] | null, + ): Promise { + const object = obj.name; + const cutoff = new Date(leg.cutoffMs).toISOString(); + const expiry = this.sealedExpiry; + if (!expiry) { + if (!report.skipped.some((s) => s.object === object && s.reason === 'seal-expiry-pending')) { + report.skipped.push({ object, reason: 'seal-expiry-pending' }); + } + this.saySealedOnce( + `pending:${object}`, + `[lifecycle] ${object} declares lifecycle.seal, but no sealed-object expiry is registered — the audit ` + + `sealer does not run in this process — so its rows past ${leg.policy} ${leg.policyValue} are KEPT: a ` + + 'sealed row is never deleted by a row cutoff, which would read as missing in os audit verify. Fix: ' + + 'compose AuditPlugin with a crypto provider so its sealer runs, or remove lifecycle.seal.', + ); + return 0; + } + const runs = await expiry.plan({ object, policy: leg.policy, policyValue: leg.policyValue, cutoff }); + let deleted = 0; + for (const run of runs) { + // [#4747] Leg boundary: a run not yet begun is the next sweep's; its amendment is already signed and it resumes. + if (this.abort.aborted) break; + if (!(await this.deleteSealedRows(engine, object, run.rowIds, stores))) continue; + await run.complete(); + deleted += run.rowIds.length; + } + report.swept.push({ object, class: lc.class, policy: 'expiry', cutoff, deleted }); + return deleted; + } + + /** + * [ADR-0154 D8] Delete exactly `ids` of a sealed object, in batches of + * {@link REAP_BATCH_SIZE}. Answers whether every one is gone. With `stores` + * (an archiving object) each batch is deleted by id on the hot store and on + * the archive. Without, through the engine one row at a time, as + * {@link batchedReap} deletes, each registered guard asked first; a batch a + * guard does not confirm whole answers `false`. + */ + private async deleteSealedRows( + engine: LifecycleEngineLike, + object: string, + ids: readonly string[], + stores: readonly ArchiveCapableDriver[] | null, + ): Promise { + const guards = this.reapGuardsFor(object); + for (let at = 0; at < ids.length; at += REAP_BATCH_SIZE) { + const batch = ids.slice(at, at + REAP_BATCH_SIZE); + if (stores) { + for (const store of stores) await store.bulkDelete(object, batch); + continue; + } + if (typeof engine.find !== 'function') { + if (guards.length > 0) return false; // a guarded object is never blind-deleted + await engine.delete(object, { where: { id: { $in: batch } }, multi: true, context: { ...SYSTEM_CTX } }); + continue; + } + const rows = await engine.find(object, { where: { id: { $in: batch } }, limit: batch.length, context: { ...SYSTEM_CTX } }); + let confirmed = (rows ?? []).filter((row) => idKey(row?.id) !== undefined); + for (const guard of guards) { + const kept = new Set((await guard(object, confirmed)).map(idKey).filter((k): k is string => k !== undefined)); + confirmed = confirmed.filter((row) => kept.has(idKey(row.id)!)); + } + for (const row of confirmed) { + await engine.delete(object, { where: { id: row.id }, multi: true, context: { ...SYSTEM_CTX } }); + } + if (confirmed.length < (rows ?? []).length) return false; + } + return true; + } + /** * A governance override window beats the declared one — unless it fails to * parse, in which case the declared window stands (never fail open into @@ -1942,9 +2158,25 @@ export class LifecycleService { // finish so the Archiver never hot-deletes a row the cold store has not // taken, nothing is left inconsistent by skipping it. The next sweep // re-derives the same cutoff from the same `keep` and prunes the same rows. - if (!this.abort.aborted && archive.keep && typeof cold.deleteMany === 'function') { - const keepCutoff = new Date(this.now() - parseLifecycleDuration(archive.keep)).toISOString(); - await cold.deleteMany(object, { where: { created_at: { $lt: keepCutoff } } }); + // + // [ADR-0154 D8] On a sealed object `keep` expires whole checkpoints instead, + // through the sealed-object expiry, on both stores: a row the Archiver has + // not moved yet is listed by the same checkpoint as its archived siblings. + if (!this.abort.aborted && archive.keep) { + const keepCutoffMs = this.now() - parseLifecycleDuration(archive.keep); + if (lc.seal) { + await this.sweepSealed( + engine, + obj, + lc, + { policy: 'archive.keep', policyValue: archive.keep, cutoffMs: keepCutoffMs }, + report, + [hot, cold], + ); + } else if (typeof cold.deleteMany === 'function') { + const keepCutoff = new Date(keepCutoffMs).toISOString(); + await cold.deleteMany(object, { where: { created_at: { $lt: keepCutoff } } }); + } } report.swept.push({ object, class: lc.class, policy: 'archive', cutoff, archived }); @@ -2193,6 +2425,20 @@ function idKey(id: unknown): string | undefined { return id === null || id === undefined ? undefined : String(id); } +/** + * [ADR-0154 D8] The duration literal behind the window a sweep applied: the + * override when it is the one that stood, else the declaration. A sealed + * object's expiry amendment signs it, and the verifier judges the expiry by it. + */ +function appliedLiteral(override: string | undefined, declared: string, appliedMs: number): string { + if (typeof override !== 'string') return declared; + try { + return parseLifecycleDuration(override) === appliedMs ? override : declared; + } catch { + return declared; + } +} + /** Best-effort row-count extraction from a driver's delete result. */ function countDeleted(res: unknown): number | undefined { if (typeof res === 'number') return res; From 32555e548acd3f0b2a5efab0726e7fa46afc5719 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:29:05 +0000 Subject: [PATCH 02/16] feat(plugin-audit): expire sealed rows by whole checkpoints under signed expiry amendments (WIP) ADR-0154 D8/D10 P4c: sys_audit_log seals by default; the sealer writes an expiry amendment before the lifecycle service deletes a covered prefix. Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt Co-authored-by: Claude --- content/docs/data-modeling/objects.mdx | 6 +- content/docs/references/data/object.mdx | 4 +- .../plugins/plugin-audit/src/audit-plugin.ts | 29 ++ .../plugin-audit/src/audit-seal/expiry.ts | 359 ++++++++++++++++++ .../plugin-audit/src/audit-seal/sealer.ts | 111 ++++++ .../plugin-audit/src/audit-seal/verifier.ts | 22 +- .../src/objects/sys-audit-log.object.ts | 13 +- packages/spec/src/data/object.zod.ts | 7 +- packages/verify/src/harness.ts | 19 + 9 files changed, 557 insertions(+), 13 deletions(-) create mode 100644 packages/plugins/plugin-audit/src/audit-seal/expiry.ts diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 4243eccfdb7..14f4fea42d4 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -274,8 +274,10 @@ lifecycle: { - Refused at parse time beside `seal`: a `class` other than `audit`, `retention.onlyWhen`, `ttl.onlyWhen`, a `ttl` on a field other than `created_at`, and rotation `storage`. Each deletes part of a sealed hour. - Until expiry amendments ship (ADR-0154 P4), the retention sweeper still - deletes sealed rows, which then read as missing. + Sealed rows past their `retention`, `ttl` or `archive.keep` window leave + only by whole checkpoints: the sealer first writes a signed expiry + amendment naming them, so the verifier reads them as `expired` rather than + missing. While no sealer is running, the sweeper keeps them. - Sealing needs a crypto provider, which the host passes to `AuditPlugin` as `cryptoProvider`. `os serve` passes the one it seals every secret with; an app that puts its own `AuditPlugin` in `plugins` passes one itself. Without diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index b93aac552d6..dbf611f3938 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -82,7 +82,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Until expiry amendments ship (ADR-0154 P4), the retention sweeper still deletes sealed rows, which then read as missing. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing; while no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Lifecycle.retention` @@ -384,7 +384,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Until expiry amendments ship (ADR-0154 P4), the retention sweeper still deletes sealed rows, which then read as missing. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing; while no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Object.activityMilestones[number]` diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 85f025b9c3d..d168cc07adf 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -21,6 +21,7 @@ import type { ISharingService, } from '@objectstack/spec/contracts'; import { AUDIT_CHECKPOINT_SIGNER_SERVICE, AUDIT_CHECKPOINT_SINK_SERVICE } from '@objectstack/spec/contracts'; +import type { AuditExpiryRequest, AuditExpiryRun } from './audit-seal/expiry.js'; import { AuditSealer, type AuditSealerEngine } from './audit-seal/sealer.js'; import { LocalCheckpointSigner } from './audit-seal/signer.js'; import { @@ -349,6 +350,8 @@ export class AuditPlugin implements Plugin { private datasetQueryWriter: DatasetQueryAuditWriter | null = null; /** [ADR-0154 D3] The sealer, started at `kernel:ready` and stopped by `destroy()`. */ private sealer: AuditSealer | null = null; + /** [ADR-0154 D8] Takes the sealer's expiry back off the lifecycle service, on `destroy()`. */ + private unregisterSealedExpiry: (() => void) | null = null; /** * [#31796] The credential-use writer, built in `init()` (the `audit` slot @@ -920,6 +923,30 @@ export class AuditPlugin implements Plugin { logger: ctx.logger, }); this.sealer.start(); + this.registerSealedExpiry(this.sealer, ctx); + } + + /** + * [ADR-0154 D8] Hand the sealer's expiry to the lifecycle service, which + * then expires each sealed object by whole checkpoints, each run's signed + * `expiry` amendment written first. Reached duck-typed, as every reap guard + * is (`ctx.getService('lifecycle')`). No lifecycle service ⇒ nothing sweeps, + * so nothing expires. A lifecycle service with no sealed expiry keeps a + * sealed object's rows past their policy and says so. + */ + private registerSealedExpiry(sealer: AuditSealer, ctx: PluginContext): void { + type LifecycleLike = { + registerSealedExpiry?: (expiry: { plan(request: AuditExpiryRequest): Promise }) => () => void; + }; + let lifecycle: LifecycleLike | undefined; + try { + lifecycle = ctx.getService('lifecycle'); + } catch { + return; + } + if (!lifecycle || typeof lifecycle.registerSealedExpiry !== 'function') return; + // Called as a method: the service's registration reads its own state. + this.unregisterSealedExpiry = lifecycle.registerSealedExpiry({ plan: (request) => sealer.expire(request) }); } /** @@ -1143,6 +1170,8 @@ export class AuditPlugin implements Plugin { // before the process lets go, and never starts again. const sealer = this.sealer; this.sealer = null; + this.unregisterSealedExpiry?.(); + this.unregisterSealedExpiry = null; await sealer?.stop(); const writer = this.readAuditWriter; this.readAuditWriter = null; diff --git a/packages/plugins/plugin-audit/src/audit-seal/expiry.ts b/packages/plugins/plugin-audit/src/audit-seal/expiry.ts new file mode 100644 index 00000000000..7b68c94cb2e --- /dev/null +++ b/packages/plugins/plugin-audit/src/audit-seal/expiry.ts @@ -0,0 +1,359 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { randomUUID } from 'node:crypto'; +import type { IAuditCheckpointSigner, IAuditCheckpointSink } from '@objectstack/spec/contracts'; +import { isMissingTableError } from '@objectstack/types'; +import { canonicalDatetime } from './canonical.js'; +import { AUDIT_AMENDMENT_OBJECT, AUDIT_CHECKPOINT_OBJECT } from './seed.js'; +import { + amendmentBodyFromRow, + amendmentRow, + checkpointBodyFromRow, + checkpointDigest, + signedBodyBytes, + type CheckpointSignedBody, + type ExpiryAmendmentBody, +} from './signed-body.js'; +import { dropAuditSealSecret, type SealStorageDriver, type SealStorageEngine } from './signer.js'; +import type { SigningKeyTrust } from './verifier.js'; + +/** + * ADR-0154 D8 — expiry removes a sealed prefix of each chain and writes a + * signed amendment. This is the audit plugin's half of the seam the + * LifecycleService calls (`LifecycleSealedExpiry` in `@objectstack/objectql`): + * it answers, per chain, the run of whole checkpoints that expired and the + * rows they list, having signed and stored the chain's `expiry` amendment + * first. The sweep then deletes exactly those rows, and only after them + * {@link AuditExpiryRun.complete} removes the run's checkpoints and seeds. + * + * Per chain, the run starts at the chain's first remaining sequence, which + * must be the sequence right after the chain's last admitted expiry (or 0): + * the verifier honours an expiry only there. It takes consecutive checkpoints + * while each covers a window that ended at or before the cutoff, each is + * admitted under the trust rule of D6 (its signature verifies under a trusted + * key), and the rows of one sweep stay within {@link AUDIT_EXPIRY_MAX_ROWS_PER_SWEEP}. + * A chain whose first remaining sequence is not that one — a checkpoint + * deleted outside the platform — is not expired, and is said once: an expiry + * there would never be honoured, and `os audit verify` reports the gap. + * + * A sweep interrupted after the amendment was stored resumes it: when the + * chain's last admitted expiry still covers its first remaining checkpoint, + * that range's remaining rows and checkpoints are answered again, and no new + * amendment is written before it is done. A stored amendment that is not + * admitted is never acted on: it deletes nothing. + * + * Two bounds, both of this file's own: + * - **The cutoff is aligned down to a UTC day.** A chain then gains at most + * one expiry amendment a day in step with the clock, where an hourly sweep + * would sign one an hour, forever: amendments are never removed. It keeps + * rows at most one day past their policy, on top of D8's own bound. + * - **At most {@link AUDIT_EXPIRY_MAX_ROWS_PER_SWEEP} rows a sweep**, the + * Archiver's own bound (500 rows × 20 batches): the backlog drains across + * sweeps, and a run cut there continues in the next amendment, which starts + * at the sequence directly after it. + */ + +type Row = Record; + +/** Rows one sweep expires per sealed object at most — the Archiver's bound per sweep. */ +export const AUDIT_EXPIRY_MAX_ROWS_PER_SWEEP = 10_000; + +const DAY_MS = 24 * 60 * 60 * 1000; +/** Checkpoints read per page of one chain's run. A checkpoint lists up to 10,000 row ids, so pages stay small. */ +const PAGE_SIZE = 20; +/** Expiry amendments read from the top of a chain to find its last admitted one. */ +const LATEST_EXPIRY_SCAN = 10; +const MAX_SIGN_ATTEMPTS = 3; +const NO_KEY_YET = 'unknown'; + +const iso = (ms: number): string => new Date(ms).toISOString(); + +/** The cutoff an expiry judges windows by: the policy's, aligned down to a UTC day (see the module header). */ +export function auditExpiryCutoff(cutoffMs: number): number { + return Math.floor(cutoffMs / DAY_MS) * DAY_MS; +} + +/** What the sweep asks (`LifecycleSealedExpiryRequest`, `@objectstack/objectql`). */ +export interface AuditExpiryRequest { + readonly object: string; + readonly policy: string; + readonly policyValue: string; + readonly cutoff: string; +} + +/** One chain's planned expiry (`LifecycleSealedExpiryRun`, `@objectstack/objectql`). */ +export interface AuditExpiryRun { + readonly chain: string; + readonly rowIds: readonly string[]; + complete(): Promise; +} + +/** What one object's expiry needs, resolved by the sealer for one call. */ +export interface ObjectExpiryOptions { + readonly engine: SealStorageEngine; + readonly object: string; + readonly signer: IAuditCheckpointSigner & { activeKeyId?(): Promise }; + readonly sink?: IAuditCheckpointSink; + readonly trust: SigningKeyTrust; + /** Said once per cause by the sealer: a chain that cannot be expired, and why. */ + readonly say: (cause: string, message: string) => void; + readonly warn: (message: string) => void; + readonly now: () => number; +} + +interface Taken { + readonly stored: Row; + readonly body: CheckpointSignedBody; +} + +const messageOf = (err: unknown): string => String((err as Error)?.message ?? err); + +/** One sealed object's expiry for one sweep. */ +export class ObjectExpiry { + private readonly checkpoints: SealStorageDriver; + private readonly amendments: SealStorageDriver | undefined; + private keyId: string | null = null; + /** Whether the plan reached every chain that has an expired window, or stopped on its row bound. */ + drained = true; + + constructor(private readonly options: ObjectExpiryOptions) { + const checkpoints = options.engine.getDriverForObject(AUDIT_CHECKPOINT_OBJECT); + if (!checkpoints) throw new Error(`no driver resolves for '${AUDIT_CHECKPOINT_OBJECT}'`); + if (typeof checkpoints.delete !== 'function') { + throw new Error(`the driver of '${AUDIT_CHECKPOINT_OBJECT}' cannot delete a row, so no checkpoint can be expired`); + } + this.checkpoints = checkpoints; + this.amendments = options.engine.getDriverForObject(AUDIT_AMENDMENT_OBJECT); + } + + private get object(): string { + return this.options.object; + } + + /** The runs of this sweep, each chain's amendment stored before it is answered. */ + async plan(request: AuditExpiryRequest): Promise { + const cutoffMs = auditExpiryCutoff(Date.parse(request.cutoff)); + if (!Number.isFinite(cutoffMs)) throw new Error(`the expiry cutoff '${request.cutoff}' is not an instant`); + const runs: AuditExpiryRun[] = []; + let budget = AUDIT_EXPIRY_MAX_ROWS_PER_SWEEP; + // Chains in `chain_key` order, each found by one checkpoint of an expired window: a keyset walk, one row a step. + for (let after: string | undefined; ;) { + if (budget <= 0) { + this.drained = false; + break; + } + const where: Row = { sealed_object: this.object, window_end: { $lte: iso(cutoffMs) } }; + if (after !== undefined) where.chain_key = { $gt: after }; + const [candidate] = await this.find(this.checkpoints, AUDIT_CHECKPOINT_OBJECT, { + where, + orderBy: [{ field: 'chain_key', order: 'asc' }], + limit: 1, + }); + if (!candidate) break; + const key = String(candidate.chain_key); + after = key; + const run = await this.chainRun(key, cutoffMs, budget, request); + if (!run) continue; + runs.push(run.run); + budget -= run.run.rowIds.length; + if (run.cut) this.drained = false; + } + return runs; + } + + private async find(driver: SealStorageDriver, object: string, query: Row): Promise { + try { + return await driver.find(object, query); + } catch (err) { + if (isMissingTableError(err, object)) return []; + throw err; + } + } + + private parse(key: string, stored: Row): CheckpointSignedBody | null { + try { + return checkpointBodyFromRow(stored); + } catch (err) { + this.options.say( + `expiry:malformed:${this.object}:${key}`, + `AuditSealer: '${this.object}' chain '${key}' is NOT expired: its checkpoint ${String(stored.sequence)} is ` + + `malformed (${messageOf(err)}), so its rows past the policy are kept. os audit verify reports it.`, + ); + return null; + } + } + + /** The chain's last expiry that is admitted (its signature verifies under a trusted key), if any. */ + private async latestExpiry(key: string): Promise { + if (!this.amendments) return undefined; + const rows = await this.find(this.amendments, AUDIT_AMENDMENT_OBJECT, { + where: { sealed_object: this.object, chain_key: key, kind: 'expiry' }, + orderBy: [{ field: 'last_sequence', order: 'desc' }], + limit: LATEST_EXPIRY_SCAN, + }); + for (const stored of rows) { + let body; + try { + body = amendmentBodyFromRow(stored); + } catch { + continue; + } + if (body.kind !== 'expiry' || body.sealed_object !== this.object) continue; + if ((await this.options.trust.signature(body.signing_key_id, signedBodyBytes(body), stored.signature)) === 'ok') return body; + } + return undefined; + } + + private async chainRun( + key: string, + cutoffMs: number, + budget: number, + request: AuditExpiryRequest, + ): Promise<{ run: AuditExpiryRun; cut: boolean } | null> { + const [firstRow] = await this.find(this.checkpoints, AUDIT_CHECKPOINT_OBJECT, { + where: { sealed_object: this.object, chain_key: key }, + orderBy: [{ field: 'sequence', order: 'asc' }], + limit: 1, + }); + if (!firstRow) return null; + const first = this.parse(key, firstRow); + if (!first) return null; + const latest = await this.latestExpiry(key); + + // A sweep that stopped after the amendment was stored: its range is finished first. + if (latest && latest.last_sequence >= first.sequence) { + const taken: Taken[] = []; + for (const stored of await this.find(this.checkpoints, AUDIT_CHECKPOINT_OBJECT, { + where: { sealed_object: this.object, chain_key: key, sequence: { $lte: latest.last_sequence } }, + })) { + const body = this.parse(key, stored); + if (!body) return null; + taken.push({ stored, body }); + } + return taken.length === 0 ? null : { run: this.runOf(key, taken), cut: false }; + } + + const expected = latest ? latest.last_sequence + 1 : 0; + if (first.sequence !== expected) { + this.options.say( + `expiry:gap:${this.object}:${key}`, + `AuditSealer: '${this.object}' chain '${key}' is NOT expired: its first remaining checkpoint is sequence ` + + `${first.sequence}, where its expiries end before ${expected} — checkpoints were removed outside the ` + + 'platform, and an expiry here would not be honoured. Its rows past the policy are kept; os audit verify ' + + 'reports the gap.', + ); + return null; + } + + const taken: Taken[] = []; + let rows = 0; + let cut = false; + let next = first.sequence; + walk: for (;;) { + const page = await this.find(this.checkpoints, AUDIT_CHECKPOINT_OBJECT, { + where: { sealed_object: this.object, chain_key: key, sequence: { $gte: next } }, + orderBy: [{ field: 'sequence', order: 'asc' }], + limit: PAGE_SIZE, + }); + for (const stored of page) { + const body = this.parse(key, stored); + if (!body || body.sequence !== next) break walk; // a malformed checkpoint or a gap ends the run + if (Date.parse(canonicalDatetime(body.window_end, 'window_end')) > cutoffMs) break walk; + if (taken.length > 0 && rows + body.row_ids.length > budget) { + cut = true; + break walk; + } + if ((await this.options.trust.signature(body.signing_key_id, signedBodyBytes(body), stored.signature)) !== 'ok') { + this.options.say( + `expiry:untrusted:${this.object}:${key}:${body.sequence}`, + `AuditSealer: '${this.object}' chain '${key}' is expired only up to its checkpoint ${body.sequence}, ` + + 'whose signature does not verify under a trusted signing key: an expiry signs only what it can show ' + + 'the platform sealed. Its rows past the policy are kept; os audit verify reports the checkpoint.', + ); + break walk; + } + taken.push({ stored, body }); + rows += body.row_ids.length; + next += 1; + } + if (page.length < PAGE_SIZE) break; + } + if (taken.length === 0) return null; + await this.writeExpiry(taken, request); + return { run: this.runOf(key, taken), cut }; + } + + /** Sign and store the chain's `expiry` amendment over `taken` (D8), then hand it to the sink. */ + private async writeExpiry(taken: readonly Taken[], request: AuditExpiryRequest): Promise { + const first = taken[0].body; + const last = taken[taken.length - 1].body; + let from = first.window_start; + let to = first.window_end; + for (const { body } of taken) { + if (body.window_start < from) from = body.window_start; + if (body.window_end > to) to = body.window_end; + } + const amendedAt = iso(this.options.now()); + const build = (signingKeyId: string): ExpiryAmendmentBody => ({ + kind: 'expiry', + sealed_object: this.object, + tenant_id: first.tenant_id, + amended_at: amendedAt, + signing_key_id: signingKeyId, + first_sequence: first.sequence, + last_sequence: last.sequence, + covered_from: from, + covered_to: to, + last_removed_digest: checkpointDigest(last), + policy: request.policy, + policy_value: request.policyValue, + }); + const { signer } = this.options; + // The S1 loop: a signature whose key id differs from the one its bytes name is never stored. + let expected = this.keyId ?? (await signer.activeKeyId?.()) ?? NO_KEY_YET; + let signed: { body: ExpiryAmendmentBody; signature: string } | undefined; + for (let attempt = 0; attempt < MAX_SIGN_ATTEMPTS && !signed; attempt++) { + const body = build(expected); + const { keyId, signature } = await signer.sign(signedBodyBytes(body)); + if (keyId === expected) signed = { body, signature }; + else expected = keyId; + } + if (!signed) throw new Error(`the checkpoint signer answered a different key id on each of ${MAX_SIGN_ATTEMPTS} attempts`); + this.keyId = expected; + await this.options.engine.insert( + AUDIT_AMENDMENT_OBJECT, + amendmentRow(signed.body, { id: randomUUID(), signature: signed.signature }), + { context: { isSystem: true } }, + ); + try { + await this.options.sink?.deliver({ + kind: 'amendment', + body: signed.body as unknown as Record, + keyId: expected, + signature: signed.signature, + }); + } catch (err) { + // The amendment stays stored on the host; a sink that failed to take it never stops the expiry. + this.options.warn( + `AuditSealer: the checkpoint sink failed to take the expiry amendment of '${this.object}' sequences ` + + `${first.sequence}–${last.sequence}; it stays stored on the host (${messageOf(err)})`, + ); + } + } + + /** The rows `taken` list, and the removal of its checkpoints and then their seeds, once the rows are gone. */ + private runOf(key: string, taken: readonly Taken[]): AuditExpiryRun { + const ids = new Set(); + for (const { body } of taken) for (const id of body.row_ids) ids.add(id); + const { engine } = this.options; + const checkpoints = this.checkpoints; + return { + chain: key, + rowIds: [...ids], + async complete() { + for (const { stored } of taken) await checkpoints.delete!(AUDIT_CHECKPOINT_OBJECT, String(stored.id)); + for (const { body } of taken) await dropAuditSealSecret(engine, body.seed_handle); + }, + }; + } +} diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index 65069d82ee5..fe7ae86de12 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -26,7 +26,9 @@ import { type SealedFieldTypes, } from './canonical.js'; import { merkleRoot } from './merkle.js'; +import { auditExpiryCutoff, ObjectExpiry, type AuditExpiryRequest, type AuditExpiryRun } from './expiry.js'; import { + AUDIT_AMENDMENT_OBJECT, AUDIT_CHECKPOINT_OBJECT, checkpointSeedContext, columnSaltsOf, @@ -34,6 +36,7 @@ import { generateCheckpointSeed, } from './seed.js'; import { + amendmentBodyFromRow, chainKeyOf, checkpointBodyFromRow, checkpointDigest, @@ -43,6 +46,7 @@ import { SignedBodyError, type AuditCheckpointKind, type CheckpointSignedBody, + type ExpiryAmendmentBody, } from './signed-body.js'; import { dropAuditSealSecret, writeAuditSealSecret, type SealStorageDriver, type SealStorageEngine } from './signer.js'; import { @@ -51,6 +55,7 @@ import { trySealPassLocks, type AuditSealPassLocks, } from './seal-lock.js'; +import { anchoredPublicKeyOf, SigningKeyTrust } from './verifier.js'; /** * ADR-0154 D3 — the sealer: after a settle lag, one window at a time, under @@ -306,6 +311,12 @@ export class AuditSealer { private loop: DispatchLoop | undefined; /** When each cause was last reported, by cause. */ private readonly reported = new Map(); + /** + * D8: the expiry each sealed object last planned and found nothing to expire + * — its day-aligned cutoff, policy and value. Asked again with the same + * three, it reads nothing until the cutoff moves to the next day. + */ + private readonly drainedAt = new Map(); private readonly now: () => number; constructor(private readonly options: AuditSealerOptions) { @@ -522,6 +533,65 @@ export class AuditSealer { } } + /** + * ADR-0154 D8: plan one sweep's expiry of sealed object `request.object` + * (`expiry.ts`), the LifecycleService's `LifecycleSealedExpiry`. It holds the + * pass's locks while it plans and signs — `audit.sealer` and the audit seal + * lock on the object's database — so two replicas' sweeps never sign two + * expiries over one range, and a sealer pass never reads a chain head the + * expiry is moving. While another holds either, it answers no run: the rows + * wait for the next sweep. With no crypto provider or no signer it throws, + * and the sweep keeps every row. + */ + async expire(request: AuditExpiryRequest): Promise { + const plan = this.plans().find((p) => p.name === request.object); + if (!plan) return []; + const memo = `${auditExpiryCutoff(Date.parse(request.cutoff))}|${request.policy}|${request.policyValue}`; + if (this.drainedAt.get(plan.name) === memo) return []; + const seams = await this.resolveSeams(); + if (!seams) throw new Error('a host seam the sealer needs is registered but could not be resolved (reported at error)'); + const { signer } = seams; + const crypto = this.options.crypto; + if (!crypto || !signer) { + throw new Error(`this deployment has no ${crypto ? 'checkpoint signer' : 'crypto provider'}, so no expiry amendment can be signed`); + } + const lock = await this.acquireLock(seams.cluster); + if (!lock) return []; + try { + const session = await trySealPassLocks(this.options.engine, [plan.name]); + if (session.held) return []; + try { + const expiry = new ObjectExpiry({ + engine: this.options.engine, + object: plan.name, + signer, + ...(seams.sink ? { sink: seams.sink } : {}), + trust: new SigningKeyTrust(anchoredPublicKeyOf(this.options.engine, crypto, signer)), + say: (cause, message) => this.warnOnce(cause, message), + warn: (message) => this.options.logger.warn(message), + now: this.now, + }); + const runs = await expiry.plan(request); + // Only a plan that found nothing at all is remembered: a run the sweep then fails to finish resumes next sweep. + if (runs.length === 0 && expiry.drained) this.drainedAt.set(plan.name, memo); + else this.drainedAt.delete(plan.name); + return runs; + } finally { + for (const held of session.locks) await held.lock.release(); + } + } finally { + await lock.release(); + } + } + + /** Say a standing state at `warn`, once per cause per {@link REPORT_REPEAT_MS} while it lasts. */ + private warnOnce(cause: string, message: string): void { + const last = this.reported.get(cause); + if (last !== undefined && this.now() - last < REPORT_REPEAT_MS) return; + this.reported.set(cause, this.now()); + this.options.logger.warn(message); + } + /** * D3 amended (E): another session holds the audit seal lock, so the pass was * skipped. Expected while an `os migrate audit-*` run lasts (or another @@ -593,6 +663,14 @@ class ObjectPass { limit: 1, }); this.watermark = top ? Date.parse(canonicalDatetime(top.sealed_through, 'sealed_through')) : null; + if (this.watermark === null) { + // D8: every checkpoint expired. The windows the last expiry covered stay sealed: nothing is walked again below it. + const expiry = await this.lastExpiry({}, 'covered_to').catch((err: unknown) => { + if (err instanceof ChainFault) return undefined; + throw err; + }); + if (expiry) this.watermark = Date.parse(expiry.covered_to); + } 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. @@ -843,11 +921,44 @@ class ObjectPass { throw new ChainFault(chainKey, err); // S4: a malformed chain head skips its chain } head = { sequence: body.sequence, digest: checkpointDigest(body) }; + } else { + // D8: a chain whose every checkpoint expired goes on from its last expiry, linking to the digest it carries. + const expiry = await this.lastExpiry({ chain_key: chainKey }, 'last_sequence'); + if (expiry) head = { sequence: expiry.last_sequence, digest: expiry.last_removed_digest }; } this.heads.set(chainKey, head); return head; } + /** + * D8: the stored `expiry` amendment of this object (narrowed by `where`) that + * is highest by `field`, or `undefined`. A malformed one is a chain-local + * fault of its chain (S4). It is read only where no checkpoint answers: a + * chain's head, and the floor of an object whose every checkpoint expired. + */ + private async lastExpiry(where: Row, field: 'last_sequence' | 'covered_to'): Promise { + const driver = this.options.engine.getDriverForObject(AUDIT_AMENDMENT_OBJECT); + if (!driver) return undefined; + let rows: Row[]; + try { + rows = await driver.find(AUDIT_AMENDMENT_OBJECT, { + where: { sealed_object: this.plan.name, kind: 'expiry', ...where }, + orderBy: [{ field, order: 'desc' }], + limit: 1, + }); + } catch (err) { + if (isMissingTableError(err, AUDIT_AMENDMENT_OBJECT)) return undefined; + throw err; + } + if (!rows[0]) return undefined; + try { + const body = amendmentBodyFromRow(rows[0]); + return body.kind === 'expiry' ? body : undefined; + } catch (err) { + throw new ChainFault(String(rows[0].chain_key), err); + } + } + private async writeChains(chains: Map, start: number, kind: AuditCheckpointKind, watermark: number): Promise { // `readWindow` makes a chain only with its first row, so no checkpoint is empty (D3). for (const key of [...chains.keys()].sort()) { diff --git a/packages/plugins/plugin-audit/src/audit-seal/verifier.ts b/packages/plugins/plugin-audit/src/audit-seal/verifier.ts index 9653f9baa64..0afbe93d65c 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/verifier.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/verifier.ts @@ -52,8 +52,9 @@ const SECRET_OBJECT = 'sys_secret'; * checkpoint lists, or that only a checkpoint holding nothing lists, is * `late` and unsealed: on the host it cannot be told from a forged insert. * A window is sealed once a trusted `window` checkpoint of the object names - * it, or it ends at or before the object's highest trusted - * `sealed_through`. + * it, it starts at or before the newest window such a checkpoint names + * (so a chain a fault left behind reads unsealed), or it ends at or before + * the object's highest trusted `sealed_through`. * * The report passes ({@link AuditVerifyReport.ok}) when no chain fault was * found and no row is `modified`, `missing` or `late` unsealed. Nothing here @@ -1074,7 +1075,9 @@ class ObjectCheck extends ChainCheck { .filter((c): c is { row: Row; head: CheckpointHead } => c.head !== undefined && this.check.inScope(c.head.chain)) .sort((a, b) => judgingOrder(a.head, b.head)); for (const { row, head } of ordered) await this.judgeCheckpoint(row, head, (body) => this.readLeaves(body, head, rows)); - const sealedWindow = start + AUDIT_SEAL_WINDOW_MS <= this.watermark || this.sealedWindows.has(start); + const sealedWindow = start + AUDIT_SEAL_WINDOW_MS <= this.watermark + || this.sealedWindows.has(start) + || start <= this.newestSealedWindow(); for (const [id, row] of rows) { const chain = chainKeyOf(chainValueOf(row, this.chainField)); if (!this.check.inScope(chain) || this.held.has(id)) continue; @@ -1082,6 +1085,19 @@ class ObjectCheck extends ChainCheck { } } + /** + * The highest `window_start` among the object's trusted `window` checkpoints + * (seat ruling 6885452378; ADR-0154 D3 as amended). The sealer pass is + * window-major, so a chain trails it only through a fault: a row of a window + * at or before it that no trusted checkpoint holds reads `late` and unsealed + * instead of going unjudged. + */ + private newestSealedWindow(): number { + let newest = Number.NEGATIVE_INFINITY; + for (const start of this.sealedWindows) newest = Math.max(newest, start); + return newest; + } + /** The leaf input of each row `body` lists, as the stores hold it now, under the checkpoint's own seed. */ private async readLeaves(body: CheckpointSignedBody, head: CheckpointHead, rows: Map): Promise { const seed = await this.openSeed(body); diff --git a/packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts b/packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts index 0698b68a3be..0ddf8271295 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts @@ -67,9 +67,11 @@ export const AUDIT_LOG_SETTINGS_STORE_OBJECTS: readonly string[] = Object.freeze * * Audit trail for all significant platform events: who did what, when, and * the before/after state. The platform writes these rows, and they are - * read-only through the data API and in Setup. Platform code running in a - * system context (retention archive-then-delete, redaction migrations) can - * still change or delete them, and nothing records that it did. + * read-only through the data API and in Setup. The rows are sealed + * (ADR-0154): each hour's rows are signed into a per-organization checkpoint, + * a redaction leaves a signed redaction amendment, and rows past `archive.keep` + * leave only by whole checkpoints after a signed expiry amendment, so a change + * or delete made outside the platform shows in `os audit verify`. * * Every field is `readonly: true` — audit logs are written only by * internal system hooks, never via UI forms. API exposes only `get` + `list`. @@ -101,6 +103,11 @@ export const SysAuditLog = ObjectSchema.create({ class: 'audit', retention: { maxAge: '90d' }, archive: { after: '90d', to: 'archive', keep: '7y' }, + // [ADR-0154 D10] Tamper evidence. The before/after state and metadata + // enter each checkpoint as salted commitments, so a checkpoint never + // carries them; every other column enters in clear. The chain column is + // the default `tenant_id` (a lookup, so one text value on every store). + seal: { valueFields: ['old_value', 'new_value', 'metadata'] }, }, description: 'Audit trail of platform events. Rows are written only by the platform and are read-only through the data API and in Setup.', displayNameField: 'action', diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 43430a869b5..5df6951a0a5 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1174,9 +1174,10 @@ export const LifecycleSchema = lazySchema(() => strictObject({ }).optional().describe( 'Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside ' + "the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` " + - "`onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Until expiry amendments " + - 'ship (ADR-0154 P4), the retention sweeper still deletes sealed rows, which then read as missing. A ' + - 'deployment with no crypto provider seals nothing and reports that at error.', + "`onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their " + + '`retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry ' + + 'amendment names them, so the verifier reads them as expired rather than missing; while no sealer is ' + + 'running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error.', ), reclaim: z.boolean().optional().describe('Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes.'), }).superRefine((lc, ctx) => { diff --git a/packages/verify/src/harness.ts b/packages/verify/src/harness.ts index 01ee2cecf33..41206c47612 100644 --- a/packages/verify/src/harness.ts +++ b/packages/verify/src/harness.ts @@ -76,6 +76,7 @@ import { SettingsServicePlugin, LocalCryptoProvider } from '@objectstack/service import { AnalyticsServicePlugin } from '@objectstack/service-analytics'; import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; import { MetadataPlugin } from '@objectstack/metadata'; +import { AuditPlugin } from '@objectstack/plugin-audit'; // Node-only subpath (#4700). Optional packages supplied by the app under // verification — `@objectstack/organizations` above all — must be resolved from // THAT app, not from `packages/verify`'s own realpath inside this workspace. @@ -200,6 +201,21 @@ function harnessCryptoProvider(): LocalCryptoProvider { return processCryptoProvider; } +/** + * [ADR-0154 D2, D6; seat ruling 6884540128 item 4] Hand {@link harnessCryptoProvider} + * — the one provider settings and the engine get — to an `AuditPlugin` this + * boot mounts: a caller's `extraPlugins` entry, a stack `plugins` entry, or the + * provider `requires: ['audit']` constructs. Its sealer then seals, and expires + * sealed rows, under the boot's own key, as `objectstack serve` hands its host + * provider over. ⛔ Never a bare `new LocalCryptoProvider()`, which would read + * the host key or mint a key file (#21499 custody). Only an instance of the + * real class is handed anything, and only one composed with no provider of its + * own (`adoptHostCryptoProvider` decides that); anything else is untouched. + */ +function handHarnessCryptoToAuditPlugin(plugin: unknown, provider: LocalCryptoProvider): void { + if (plugin instanceof AuditPlugin) plugin.adoptHostCryptoProvider(() => provider, { armSealer: true }); +} + /** This process's auth signing secret; created on the first boot, never persisted. */ let processAuthSecret: string | undefined; @@ -1340,6 +1356,7 @@ async function bootClaimed( // Caller-supplied optional service pairs (see BootOptions.extraPlugins). // Before SecurityPlugin, mirroring the CLI's ordering for service pairs. for (const plugin of opts.extraPlugins ?? []) { + handHarnessCryptoToAuditPlugin(plugin, cryptoProvider); await kernel.use(plugin as any); } @@ -1387,6 +1404,7 @@ async function bootClaimed( packageRoot: hostRoot, }); for (const plugin of servedProviders) { + handHarnessCryptoToAuditPlugin(plugin, cryptoProvider); await kernel.use(plugin as any); } } catch (e) { @@ -1419,6 +1437,7 @@ async function bootClaimed( // boot that went on without a plugin the app declares would pass green on a // composition production never runs, so here the boot stops, with the remedy. for (const { plugin, label } of appPlugins) { + handHarnessCryptoToAuditPlugin(plugin, cryptoProvider); try { await kernel.use(plugin as any); } catch (e) { From 3e6fc7a2c90c34af1de4be7708676b7c37d2c7ff Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:37:08 +0000 Subject: [PATCH 03/16] test(plugin-audit): sealed expiry pins and the S4 verifier arm (WIP) Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt Co-authored-by: Claude --- .../lifecycle-service.sealed-expiry.test.ts | 246 +++++++++++++++ .../audit-seal-chain-field-34164.test.ts | 4 +- ...audit-seal-expiry-live.integration.test.ts | 285 ++++++++++++++++++ ...ost-seam-resolve-34280.integration.test.ts | 3 + .../src/audit-seal/audit-seal-sealer.test.ts | 11 + 5 files changed, 548 insertions(+), 1 deletion(-) create mode 100644 packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts create mode 100644 packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-live.integration.test.ts diff --git a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts new file mode 100644 index 00000000000..257e863c622 --- /dev/null +++ b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts @@ -0,0 +1,246 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, vi } from 'vitest'; +import { + LifecycleService, + type LifecycleObjectLike, + type LifecycleSealedExpiry, + type LifecycleSealedExpiryRequest, + type LifecycleSealedExpiryRun, +} from './lifecycle-service.js'; +import { parseLifecycleDuration } from './duration.js'; + +/** + * [ADR-0154 D8] A sealed object (`lifecycle.seal`) never loses rows to a row + * cutoff: the sweep hands each policy to the registered sealed expiry, which + * plans whole checkpoints and signs their expiry amendment first, and deletes + * exactly the rows each run names, completing a run only once every one is + * gone. With no expiry registered the rows are kept, and that is said once. + */ + +const FIXED_NOW = 1_700_000_000_000; +const isoCutoff = (literal: string) => new Date(FIXED_NOW - parseLifecycleDuration(literal)).toISOString(); + +function recordingLogger() { + const warns: string[] = []; + return { warns, logger: { info: () => {}, debug: () => {}, warn: (m: string) => void warns.push(m), error: () => {} } }; +} + +const SEAL = { valueFields: ['new_value'] }; + +const ARCHIVING: LifecycleObjectLike = { + name: 'sys_audit_log', + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, archive: { after: '90d', to: 'archive', keep: '7y' }, seal: SEAL } as any, +}; +const RETAINED: LifecycleObjectLike = { + name: 'app_ledger', + lifecycle: { class: 'audit', retention: { maxAge: '30d' }, seal: SEAL } as any, +}; +const TTL: LifecycleObjectLike = { + name: 'app_receipt', + lifecycle: { class: 'audit', ttl: { field: 'created_at', expireAfter: '7d' }, seal: SEAL } as any, +}; + +/** A store that remembers what each call did. */ +function store(name: string, rows: Array> = []) { + let remaining = [...rows]; + const bulkDeleted: string[][] = []; + const deleteMany = vi.fn(async () => 0); + return { + bulkDeleted, + deleteMany, + remaining: () => remaining.map((r) => r.id), + driver: { + name, + syncSchema: vi.fn(async () => {}), + find: async (_o: string, q: any) => remaining.slice(0, q?.limit ?? remaining.length), + upsert: async (_o: string, row: Record) => row, + bulkDelete: async (_o: string, ids: string[]) => { + bulkDeleted.push([...ids]); + remaining = remaining.filter((r) => !ids.includes(r.id as string)); + }, + deleteMany, + }, + }; +} + +function engineOver(objects: LifecycleObjectLike[], opts: { hot?: ReturnType; cold?: ReturnType; rows?: Array> } = {}) { + const deletes: any[] = []; + const finds: any[] = []; + let rows = [...(opts.rows ?? [])]; + const engine: any = { + registry: { getAllObjects: () => objects }, + getDriverForObject: () => opts.hot?.driver, + datasource(name: string) { + if (name === 'archive' && opts.cold) return opts.cold.driver; + throw new Error(`[ObjectQL] Datasource '${name}' not found`); + }, + async find(object: string, q: any) { + finds.push({ object, where: q?.where }); + const ids: string[] = q?.where?.id?.$in ?? []; + return rows.filter((r) => ids.includes(r.id as string)); + }, + async delete(object: string, q: any) { + deletes.push({ object, where: q?.where, context: q?.context }); + rows = rows.filter((r) => r.id !== q?.where?.id); + return { deletedCount: 1 }; + }, + }; + return { engine, deletes, finds, rowsLeft: () => rows.map((r) => r.id) }; +} + +function service(engine: any, logger = recordingLogger().logger) { + return new LifecycleService({ getEngine: () => engine, logger, now: () => FIXED_NOW, initialDelayMs: 1, sweepIntervalMs: 10 }); +} + +function expiryOf(runs: Array<{ chain: string; rowIds: string[] }>) { + const completed: string[] = []; + const requests: LifecycleSealedExpiryRequest[] = []; + const expiry: LifecycleSealedExpiry = { + plan: vi.fn(async (request: LifecycleSealedExpiryRequest): Promise => { + requests.push(request); + return runs.map((r) => ({ ...r, complete: async () => void completed.push(r.chain) })); + }), + }; + return { expiry, completed, requests }; +} + +describe('LifecycleService — a sealed object expires only through the sealed expiry (ADR-0154 D8)', () => { + it('with no sealed expiry registered, archives as before but keeps the archive past `keep`, and says so once', async () => { + const hot = store('default', [{ id: 'a', created_at: '2020-01-01T00:00:00.000Z' }]); + const cold = store('archive'); + const { engine } = engineOver([ARCHIVING], { hot, cold }); + const { warns, logger } = recordingLogger(); + const svc = service(engine, logger); + + const first = await svc.sweep(); + const second = await svc.sweep(); + + // The hot→cold hand-off is not a deletion of a sealed row: the archive still holds it. + expect(hot.bulkDeleted).toEqual([['a']]); + expect(cold.deleteMany).not.toHaveBeenCalled(); + expect(first.skipped).toContainEqual({ object: 'sys_audit_log', reason: 'seal-expiry-pending' }); + expect(second.skipped).toContainEqual({ object: 'sys_audit_log', reason: 'seal-expiry-pending' }); + expect(first.swept.some((e) => e.policy === 'expiry')).toBe(false); + expect(warns.filter((w) => /sys_audit_log declares lifecycle\.seal, but no sealed-object expiry is registered/.test(w))).toHaveLength(1); + expect(warns.join('\n')).toMatch(/rows past archive\.keep 7y are KEPT/); + }); + + it('an archiving sealed object: plans `archive.keep` at its cutoff, deletes each run by id on both stores, then completes it', async () => { + const hot = store('default', [{ id: 'x', created_at: '2026-01-01T00:00:00.000Z' }]); + const cold = store('archive', [{ id: 'e1' }, { id: 'e2' }, { id: 'e3' }, { id: 'kept' }]); + const { engine } = engineOver([ARCHIVING], { hot, cold }); + const svc = service(engine); + const { expiry, completed, requests } = expiryOf([ + { chain: 'org:a', rowIds: ['e1', 'e2'] }, + { chain: 'org:b', rowIds: ['e3'] }, + ]); + svc.registerSealedExpiry(expiry); + + const report = await svc.sweep(); + + expect(requests).toEqual([{ object: 'sys_audit_log', policy: 'archive.keep', policyValue: '7y', cutoff: isoCutoff('7y') }]); + expect(cold.remaining()).toEqual(['kept']); + expect(cold.bulkDeleted).toEqual([['e1', 'e2'], ['e3']]); + // The hot store is asked too: a sealed row may sit on either side of the hand-off. + expect(hot.bulkDeleted).toContainEqual(['e1', 'e2']); + expect(completed).toEqual(['org:a', 'org:b']); + expect(cold.deleteMany).not.toHaveBeenCalled(); // never the row-cutoff prune + expect(report.swept).toContainEqual({ object: 'sys_audit_log', class: 'audit', policy: 'expiry', cutoff: isoCutoff('7y'), deleted: 3 }); + expect(report.skipped).toEqual([]); + }); + + it('a retained sealed object: plans `retention.maxAge`, deletes each row through the engine, never by the cutoff', async () => { + const { engine, deletes } = engineOver([RETAINED], { rows: [{ id: 'r1' }, { id: 'r2' }, { id: 'r3' }] }); + const svc = service(engine); + const { expiry, completed, requests } = expiryOf([{ chain: 'deployment', rowIds: ['r1', 'r2'] }]); + svc.registerSealedExpiry(expiry); + + const report = await svc.sweep(); + + expect(requests).toEqual([{ object: 'app_ledger', policy: 'retention.maxAge', policyValue: '30d', cutoff: isoCutoff('30d') }]); + expect(deletes.map((d) => d.where)).toEqual([{ id: 'r1' }, { id: 'r2' }]); + expect(deletes.every((d) => d.context?.isSystem === true)).toBe(true); + expect(completed).toEqual(['deployment']); + expect(report.swept).toEqual([{ object: 'app_ledger', class: 'audit', policy: 'expiry', cutoff: isoCutoff('30d'), deleted: 2 }]); + }); + + it('a ttl sealed object plans `ttl.expireAfter`', async () => { + const { engine } = engineOver([TTL], { rows: [] }); + const svc = service(engine); + const { expiry, requests } = expiryOf([]); + svc.registerSealedExpiry(expiry); + + const report = await svc.sweep(); + + expect(requests).toEqual([{ object: 'app_receipt', policy: 'ttl.expireAfter', policyValue: '7d', cutoff: isoCutoff('7d') }]); + expect(report.swept).toEqual([{ object: 'app_receipt', class: 'audit', policy: 'expiry', cutoff: isoCutoff('7d'), deleted: 0 }]); + }); + + it('a run a reap guard vetoes in part is not completed: its rows that went stay gone, its checkpoints stay for the next sweep', async () => { + const { engine, deletes } = engineOver([RETAINED], { rows: [{ id: 'r1' }, { id: 'r2' }, { id: 'r3' }] }); + const svc = service(engine); + svc.registerReapGuard('app_ledger', async (_o, rows) => rows.map((r) => r.id).filter((id) => id !== 'r2')); + const { expiry, completed } = expiryOf([ + { chain: 'org:a', rowIds: ['r1', 'r2'] }, + { chain: 'org:b', rowIds: ['r3'] }, + ]); + svc.registerSealedExpiry(expiry); + + const report = await svc.sweep(); + + expect(deletes.map((d) => d.where)).toEqual([{ id: 'r1' }, { id: 'r3' }]); + expect(completed).toEqual(['org:b']); + expect(report.swept).toEqual([{ object: 'app_ledger', class: 'audit', policy: 'expiry', cutoff: isoCutoff('30d'), deleted: 1 }]); + }); + + it('a plan that fails deletes nothing and reports the object', async () => { + const { engine, deletes } = engineOver([RETAINED], { rows: [{ id: 'r1' }] }); + const svc = service(engine); + svc.registerSealedExpiry({ plan: async () => { throw new Error('no expiry amendment can be signed'); } }); + + const report = await svc.sweep(); + + expect(deletes).toEqual([]); + expect(report.errors).toHaveLength(1); + expect(report.errors[0]).toMatchObject({ object: 'app_ledger' }); + }); + + it('a later registration replaces the slot, and an earlier unregistration does not clear it', async () => { + const { engine } = engineOver([RETAINED], { rows: [] }); + const svc = service(engine); + const first = expiryOf([]); + const second = expiryOf([]); + const unregisterFirst = svc.registerSealedExpiry(first.expiry); + const unregisterSecond = svc.registerSealedExpiry(second.expiry); + unregisterFirst(); + + await svc.sweep(); + expect(first.requests).toEqual([]); + expect(second.requests).toHaveLength(1); + + unregisterSecond(); + const report = await svc.sweep(); + expect(second.requests).toHaveLength(1); + expect(report.skipped).toContainEqual({ object: 'app_ledger', reason: 'seal-expiry-pending' }); + }); + + it('refuses a registration with no plan method', () => { + const svc = service(engineOver([]).engine); + expect(() => svc.registerSealedExpiry({} as never)).toThrow(/requires an object with a plan\(request\) method/); + }); + + it('an object without `seal` keeps the row-cutoff path, and never asks the sealed expiry', async () => { + const plain: LifecycleObjectLike = { name: 'app_log', lifecycle: { class: 'telemetry', retention: { maxAge: '30d' } } as any }; + const { engine, finds } = engineOver([plain], { rows: [] }); + const svc = service(engine); + const { expiry, requests } = expiryOf([]); + svc.registerSealedExpiry(expiry); + + const report = await svc.sweep(); + + expect(requests).toEqual([]); + expect(finds.map((f) => f.where)).toContainEqual({ created_at: { $lt: isoCutoff('30d') } }); + expect(report.swept.map((e) => e.policy)).toEqual(['retention']); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts index b3ccdaa82cd..933caab661e 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-chain-field-34164.test.ts @@ -84,7 +84,9 @@ describe('a sealed object chained by organization_id, on a live engine (ADR-0154 const past = Math.floor(Date.now() / H) * H - 3 * H; // a window three hours ago: settled const hot = () => engine.getDriverForObject(CHAIN_PROBE) as unknown as Driver; const sealer = () => (plugin as unknown as { sealer: AuditSealer }).sealer; - const verify = (orgs: string[]) => verifyAuditLedger({ engine: engine as never, crypto, orgs }); + // `sys_audit_log` is sealed by default and archives to 'archive', which this boot never connects: nothing was + // archived, as `os audit verify` establishes before it reads the hot store alone. + const verify = (orgs: string[]) => verifyAuditLedger({ engine: engine as never, crypto, orgs, archive: () => 'none' }); let written = 0; beforeAll(async () => { diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-live.integration.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-live.integration.test.ts new file mode 100644 index 00000000000..bc2f98553a1 --- /dev/null +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-live.integration.test.ts @@ -0,0 +1,285 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin, type LifecycleService } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import { SysSecret } from '@objectstack/platform-objects/system'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { AuditPlugin } from '../audit-plugin.js'; +import { installDefaultOrganization } from '../default-organization.testkit.js'; +import { SysAuditLog } from '../objects/sys-audit-log.object.js'; +import { RedactionAmender } from './amendment-writer.js'; +import { auditExpiryCutoff } from './expiry.js'; +import { amendmentBodyFromRow, checkpointBodyFromRow, checkpointDigest, type ExpiryAmendmentBody } from './signed-body.js'; +import { bindingCrypto } from './seal-store.testkit.js'; +import type { AuditSealer } from './sealer.js'; +import { verifyAuditLedger, type AuditVerifyReport } from './verifier.js'; + +/** + * ADR-0154 D8 + D10, end to end on a real kernel over SQLite with an `archive` + * datasource: `sys_audit_log` is sealed by its own declaration (no opt-in + * here), the plugin's sealer seals it, and the kernel's own LifecycleService + * archives it and expires it past `archive.keep` through the sealer — each + * chain's signed `expiry` amendment stored before a row goes. The live check + * then tells every case apart: a row changed outside the platform reads + * `modified`, a deleted one `missing`, a rewritten one `redacted`, an expired + * one `expired` (while its checkpoint stands) or gone with its checkpoint + * under an honoured expiry, and an untouched window reads `unmodified` + * whether its rows sit in the hot store or the archive. The rows carry + * sentinels only. + */ + +const H = 60 * 60 * 1000; +const DAY = 24 * H; +const YEAR = 365 * DAY; +const SYS = { isSystem: true } as const; +const LOG = 'sys_audit_log'; + +type Row = Record; +interface Driver { + find(o: string, q: Row): Promise; + create(o: string, r: Row): Promise; + update(o: string, id: string, r: Row, options?: { preserveAudit?: boolean }): Promise; + delete(o: string, id: string): Promise; +} + +const verdicts = (report: AuditVerifyReport, ids: readonly string[]) => + Object.fromEntries(report.rows.filter((r) => ids.includes(r.row)).map((r) => [r.row, r.verdict === 'late' && !r.sealed ? 'late!' : r.verdict])); +const chainOf = (report: AuditVerifyReport, chain: string) => report.chains.find((c) => c.object === LOG && c.chain === chain); + +/** A kernel over SQLite with an `archive` datasource and `plugin` composed; the ledger as the plugin declares it. */ +async function boot(plugin: AuditPlugin) { + const kernel = new ObjectKernel({ logger: { level: 'silent' } }); + await kernel.use(new ObjectQLPlugin({ lifecycle: { initialDelayMs: 24 * H, sweepIntervalMs: 24 * H } })); + await kernel.use(plugin); + await kernel.bootstrap(); + const engine = kernel.getService('objectql'); + const sqlite = new SqliteWasmDriver({ filename: ':memory:' }); + await sqlite.connect(); + engine.registerDriver(sqlite, true); + const cold = new SqliteWasmDriver({ filename: ':memory:' }); + Object.defineProperty(cold, 'name', { value: 'archive' }); + await cold.connect(); + engine.registerDriver(cold); + engine.registry.registerObject(SysSecret as never, 'com.objectstack.audit.test.expiry'); + await engine.syncSchemas(); + await cold.syncSchema(LOG, engine.registry.getObject(LOG) as never); + await installDefaultOrganization(engine); + const lifecycle = kernel.getService('lifecycle'); + const sealer = (plugin as unknown as { sealer: AuditSealer }).sealer; + await sealer.stop(); // drive the passes here, not on the loop's clock + return { kernel, engine, cold, lifecycle, sealer }; +} + +describe('sys_audit_log seals by default, and expires by whole checkpoints across hot and archive (ADR-0154 D8, D10)', () => { + const crypto = bindingCrypto(); + const plugin = new AuditPlugin({ cryptoProvider: () => crypto }); + let kernel: ObjectKernel; + let engine: ObjectQL; + let cold: SqliteWasmDriver; + let lifecycle: LifecycleService; + let sealer: AuditSealer; + const now = Date.now(); + const hour = Math.floor(now / H) * H; + const old = hour - 8 * YEAR; // past `archive.keep: 7y` + const mid = hour - YEAR; // past `archive.after: 90d`, within `keep` + const recent = hour - 3 * H; // a settled window, still hot + const iso = (ms: number) => new Date(ms).toISOString(); + const hot = () => engine.getDriverForObject(LOG) as unknown as Driver; + const archive = () => cold as unknown as Driver; + const verify = () => verifyAuditLedger({ engine: engine as never, crypto }); + const entry = (id: string, at: number, tenant: string): Row => ({ + id, created_at: iso(at), action: 'update', object_name: 'crm_note', record_id: `${id}_rec`, tenant_id: tenant, + new_value: JSON.stringify({ id: `${id}_rec`, note: 'sentinel' }), + }); + const checkpoints = async (chain?: string) => + ((await engine.find('sys_audit_checkpoint', { where: { sealed_object: LOG, ...(chain ? { chain_key: chain } : {}) }, context: SYS })) as Row[]) + .map((row) => ({ row, body: checkpointBodyFromRow(row) })) + .sort((a, b) => a.body.sequence - b.body.sequence); + const expiries = async () => + ((await engine.find('sys_audit_amendment', { where: { sealed_object: LOG, kind: 'expiry' }, context: SYS })) as Row[]) + .map((row) => amendmentBodyFromRow(row) as ExpiryAmendmentBody) + .sort((a, b) => a.tenant_id!.localeCompare(b.tenant_id!)); + const secretExists = async (handle: string) => + ((await engine.find('sys_secret', { where: { id: handle }, context: SYS })) as Row[]).length > 0; + const where = async (id: string) => ({ + hot: (await hot().find(LOG, { where: { id } })).length > 0, + archive: (await archive().find(LOG, { where: { id } })).length > 0, + }); + const keepRequest = () => ({ object: LOG, policy: 'archive.keep', policyValue: '7y', cutoff: iso(now - 7 * YEAR) }); + + let oldSeeds: string[] = []; + + beforeAll(async () => { + ({ kernel, engine, cold, lifecycle, sealer } = await boot(plugin)); + // org_a: an expired window, a window that goes to the archive, and a recent window that stays hot. + await hot().create(LOG, entry('a_old1', old + 60_000, 'org_a')); + await hot().create(LOG, entry('a_old2', old + 120_000, 'org_a')); + await hot().create(LOG, entry('a_mid', mid + 60_000, 'org_a')); + await hot().create(LOG, entry('a_keep', recent + 60_000, 'org_a')); + await hot().create(LOG, entry('a_mod', recent + 120_000, 'org_a')); + await hot().create(LOG, entry('a_del', recent + 180_000, 'org_a')); + await hot().create(LOG, entry('a_red', recent + 240_000, 'org_a')); + // org_b: one expired window only, so the whole chain expires. + await hot().create(LOG, entry('b_old', old + 180_000, 'org_b')); + // Seals 3 windows for org_a and one for org_b, one pass after another. + for (let pass = 0; pass < 5 && (await sealer.runPass()) > 0; pass++); + oldSeeds = (await checkpoints()).filter((c) => c.body.window_start === iso(Math.floor(old / H) * H)).map((c) => c.body.seed_handle); + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + it('the ledger carries the seal by its own declaration, and every row is sealed', async () => { + expect((engine.registry.getObject(LOG) as { lifecycle: { seal?: unknown } }).lifecycle.seal).toEqual({ valueFields: ['old_value', 'new_value', 'metadata'] }); + expect(SysAuditLog.lifecycle?.seal).toEqual({ valueFields: ['old_value', 'new_value', 'metadata'] }); + expect((await checkpoints('org:org_a')).map((c) => [c.body.sequence, c.body.row_ids])).toEqual([ + [0, ['a_old1', 'a_old2']], + [1, ['a_mid']], + [2, ['a_keep', 'a_mod', 'a_del', 'a_red']], + ]); + expect((await checkpoints('org:org_b')).map((c) => [c.body.sequence, c.body.row_ids])).toEqual([[0, ['b_old']]]); + expect(oldSeeds).toHaveLength(2); + const report = await verify(); + expect(report.faults).toEqual([]); + expect(report.ok).toBe(true); + }); + + it('the kernel\'s lifecycle service holds the sealer\'s expiry: an interrupted expiry has signed its amendment, and its rows read expired', async () => { + // What a sweep stopped right after the amendment leaves: the amendment stored, every row and checkpoint still there. + const runs = await sealer.expire(keepRequest()); + expect(runs.map((r) => [r.chain, [...r.rowIds].sort()])).toEqual([ + ['org:org_a', ['a_old1', 'a_old2']], + ['org:org_b', ['b_old']], + ]); + const [a, b] = await expiries(); + const [a0] = await checkpoints('org:org_a'); + expect(a).toMatchObject({ + kind: 'expiry', tenant_id: 'org_a', first_sequence: 0, last_sequence: 0, policy: 'archive.keep', policy_value: '7y', + last_removed_digest: checkpointDigest(a0.body), + }); + expect(Date.parse(a.covered_to)).toBeLessThanOrEqual(auditExpiryCutoff(now - 7 * YEAR)); + expect(b).toMatchObject({ tenant_id: 'org_b', first_sequence: 0, last_sequence: 0 }); + + const report = await verify(); + expect(verdicts(report, ['a_old1', 'a_old2', 'b_old'])).toEqual({ a_old1: 'expired', a_old2: 'expired', b_old: 'expired' }); + expect(report.faults).toEqual([]); + expect(report.ok).toBe(true); + }); + + it('the sweep finishes it: archives, then deletes exactly the expired rows from both stores, and their checkpoints and seeds after them', async () => { + const report = await lifecycle.sweep(); + expect(report.errors).toEqual([]); + expect(report.swept).toContainEqual(expect.objectContaining({ object: LOG, policy: 'archive', archived: 4 })); + expect(report.swept).toContainEqual(expect.objectContaining({ object: LOG, policy: 'expiry', deleted: 3 })); + // Resumed under the stored amendments: no second one. + expect((await expiries()).length).toBe(2); + for (const id of ['a_old1', 'a_old2', 'b_old']) expect(await where(id)).toEqual({ hot: false, archive: false }); + expect(await where('a_mid')).toEqual({ hot: false, archive: true }); + expect(await where('a_keep')).toEqual({ hot: true, archive: false }); + expect((await checkpoints('org:org_a')).map((c) => c.body.sequence)).toEqual([1, 2]); + expect(await checkpoints('org:org_b')).toEqual([]); + for (const handle of oldSeeds) expect(await secretExists(handle)).toBe(false); + }); + + it('a second sweep the same day signs nothing more and deletes nothing', async () => { + const report = await lifecycle.sweep(); + expect(report.swept).toContainEqual(expect.objectContaining({ object: LOG, policy: 'expiry', deleted: 0 })); + expect((await expiries()).length).toBe(2); + }); + + it('the live check honours the expiries: no gap, the untouched windows read unmodified across hot and archive', async () => { + const report = await verify(); + expect(report.faults).toEqual([]); + expect(report.rows).toEqual([]); + expect(chainOf(report, 'org:org_a')).toMatchObject({ checkpoints: 2, counts: expect.objectContaining({ unmodified: 5, expired: 0 }) }); + expect(report.ok).toBe(true); + }); + + it('a chain that expired whole chains its next checkpoint onto the expiry: it links to the last removed digest', async () => { + await hot().create(LOG, entry('b_next', recent + 300_000, 'org_b')); + expect(await sealer.runPass()).toBeGreaterThan(0); + const [next] = await checkpoints('org:org_b'); + const [, b] = await expiries(); + expect(next.body).toMatchObject({ sequence: 1, row_ids: ['b_next'], previous_digest: b.last_removed_digest }); + const report = await verify(); + expect(report.faults).toEqual([]); + expect(report.ok).toBe(true); + }); + + it('still tells modified, missing and redacted rows apart beside the expiry', async () => { + await hot().update(LOG, 'a_mod', { action: 'delete' }); + await hot().delete(LOG, 'a_del'); + const amender = new RedactionAmender({ engine: engine as never, crypto }, 'pin: expiry e2e'); + const patch = { new_value: JSON.stringify({ id: 'a_red_rec', redacted: true }) }; + const decision = await amender.decide(LOG, 'a_red', patch); + expect(decision.kind).toBe('amend'); + await amender.write(LOG, decision); + const stored = (await hot().find(LOG, { where: { id: 'a_red' } }))[0]!; + await hot().update(LOG, 'a_red', { ...patch, updated_at: stored.updated_at }, { preserveAudit: true }); + + const report = await verify(); + expect(verdicts(report, ['a_mod', 'a_del', 'a_red', 'a_keep', 'a_mid', 'b_next'])).toEqual({ a_mod: 'modified', a_del: 'missing', a_red: 'redacted' }); + expect(report.faults).toEqual([]); + expect(report.ok).toBe(false); + }); +}); + +describe('an expiry signs only what it can show the platform sealed (ADR-0154 D6, D8)', () => { + const crypto = bindingCrypto(); + const plugin = new AuditPlugin({ cryptoProvider: crypto }); + let kernel: ObjectKernel; + let engine: ObjectQL; + let lifecycle: LifecycleService; + let sealer: AuditSealer; + const now = Date.now(); + const old = Math.floor(now / H) * H - 8 * YEAR; + const iso = (ms: number) => new Date(ms).toISOString(); + const hot = () => engine.getDriverForObject(LOG) as unknown as Driver; + const entry = (id: string, at: number, tenant: string): Row => ({ id, created_at: iso(at), action: 'update', object_name: 'crm_note', record_id: `${id}_rec`, tenant_id: tenant }); + const checkpointOf = async (chain: string, sequence: number) => + ((await engine.find('sys_audit_checkpoint', { where: { sealed_object: LOG, chain_key: chain, sequence }, context: SYS })) as Row[])[0]!; + const expiries = async () => (await engine.find('sys_audit_amendment', { where: { sealed_object: LOG, kind: 'expiry' }, context: SYS })) as Row[]; + let cold: SqliteWasmDriver; + /** Whether either store still holds row `id`: the sweep archives every row here before it expires any. */ + const present = async (id: string) => + (await hot().find(LOG, { where: { id } })).length + (await (cold as unknown as Driver).find(LOG, { where: { id } })).length > 0; + + beforeAll(async () => { + ({ kernel, engine, cold, lifecycle, sealer } = await boot(plugin)); + // Each chain seals two windows, both past `keep`. + for (const tenant of ['org_gap', 'org_forged', 'org_ok']) { + await hot().create(LOG, entry(`${tenant}_0`, old + 60_000, tenant)); + await hot().create(LOG, entry(`${tenant}_1`, old + H + 60_000, tenant)); + } + for (let pass = 0; pass < 5 && (await sealer.runPass()) > 0; pass++); + // org_gap: its first checkpoint removed outside the platform. org_forged: its second re-signed by no trusted key. + await hot().delete('sys_audit_checkpoint', String((await checkpointOf('org:org_gap', 0)).id)); + await hot().update('sys_audit_checkpoint', String((await checkpointOf('org:org_forged', 1)).id), { signature: Buffer.alloc(64).toString('base64') }); + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + it('expires a sound chain whole, stops a chain at a checkpoint no trusted key signed, and keeps a chain with a gap', async () => { + const logger = (sealer as unknown as { options: { logger: { warn(m: string): void } } }).options.logger; + const warn = vi.spyOn(logger, 'warn'); + const report = await lifecycle.sweep(); + expect(report.errors).toEqual([]); + const warned = warn.mock.calls.map(([m]) => String(m)); + warn.mockRestore(); + + const byChain = Object.fromEntries((await expiries()).map((row) => { + const body = amendmentBodyFromRow(row) as ExpiryAmendmentBody; + return [body.tenant_id, [body.first_sequence, body.last_sequence]]; + })); + expect(byChain).toEqual({ org_ok: [0, 1], org_forged: [0, 0] }); + expect([await present('org_ok_0'), await present('org_ok_1')]).toEqual([false, false]); + expect([await present('org_forged_0'), await present('org_forged_1')]).toEqual([false, true]); + expect([await present('org_gap_0'), await present('org_gap_1')]).toEqual([true, true]); + expect(warned.filter((m) => /'sys_audit_log' chain 'org:org_gap' is NOT expired: its first remaining checkpoint is sequence 1/.test(m))).toHaveLength(1); + expect(warned.filter((m) => /'sys_audit_log' chain 'org:org_forged' is expired only up to its checkpoint 1/.test(m))).toHaveLength(1); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-host-seam-resolve-34280.integration.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-host-seam-resolve-34280.integration.test.ts index 8d3a6d955a7..46740fe7e5c 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-host-seam-resolve-34280.integration.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-host-seam-resolve-34280.integration.test.ts @@ -105,6 +105,9 @@ async function boot(register: (kernel: ObjectKernel) => void = () => {}): Promis const sealer = (plugin as unknown as { sealer: AuditSealer }).sealer; await sealer.stop(); // drive the pass here, not on the loop's clock + // `sys_audit_log` is sealed by default (ADR-0154 D10), so the loop's own first pass, which ran at start, may + // already have reported a seam: forget it, so each pin counts what its own passes say. + (sealer as unknown as { reported: Map }).reported.clear(); const errors: string[] = []; const logger = (sealer as unknown as { options: { logger: { error(m: string): void } } }).options.logger; const error = logger.error.bind(logger); 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 bd23db6b357..638635afdd3 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 @@ -325,6 +325,17 @@ describe('per-chain isolation: only a chain-local fault skips a chain, and only 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 }); }); + + it('keeps verify loud where the skipped chain is alone in its window: a window before the newest sealed one is sealed (seat ruling 6885452378)', async () => { + const s = setup(); + // 08:00 holds only org_b's refused row, so no window checkpoint names it and sealed_through is held there. + s.hot.table('ledger_probe').push(refused('b1', at(8, 20), 'org_b'), row('a2', at(9, 10))); + await s.sealer.runPass(); + expect(s.checkpoints().map((c) => [c.tenant_id, c.window_start])).toEqual([['org_a', at(9, 0)]]); + const report = await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); + expect(report.rows.map((r) => [r.chain, r.row, r.verdict, r.sealed])).toEqual([['org:org_b', 'b1', 'late', false]]); + expect(report.ok).toBe(false); + }); }); describe('bounded checkpoints: a window seals into consecutive parts of at most N leaves (S7, ADR-0154 D4 amended)', () => { From 1854f11685cc962a0e9f1f9a4f4b9f0d6460eafe Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:40:28 +0000 Subject: [PATCH 04/16] test(plugin-audit): plugin registration pins; docs and changeset for sealed expiry (WIP) Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt Co-authored-by: Claude --- .changeset/31908-p4c-sealed-expiry.md | 22 ++++++++ content/docs/data-modeling/objects.mdx | 7 ++- .../plugin-audit/src/audit-plugin.test.ts | 52 +++++++++++++++++++ .../plugins/plugin-audit/src/audit-plugin.ts | 4 +- 4 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 .changeset/31908-p4c-sealed-expiry.md diff --git a/.changeset/31908-p4c-sealed-expiry.md b/.changeset/31908-p4c-sealed-expiry.md new file mode 100644 index 00000000000..a65875816c0 --- /dev/null +++ b/.changeset/31908-p4c-sealed-expiry.md @@ -0,0 +1,22 @@ +--- +'@objectstack/plugin-audit': patch +'@objectstack/objectql': patch +'@objectstack/verify': patch +'@objectstack/spec': patch +--- + +feat(plugin-audit): the audit log is sealed by default, and sealed rows expire by whole checkpoints under a signed expiry amendment + +Clause-②: yes (widening) (LifecycleService gains a public prefix-expiry seam for sealed objects: `registerSealedExpiry` and the `LifecycleSealedExpiry` types) +Metadata-protocol: none (the `seal` key landed in P1b; this changes a platform object's declaration only) + +ADR-0154 D8 and D10 (#31908, slice P4c, the last one). + +- **`sys_audit_log` is sealed.** Its lifecycle declares `seal: { valueFields: ['old_value', 'new_value', 'metadata'] }`, so every deployment whose `AuditPlugin` has a crypto provider (`os serve` hands it one) signs each hour's audit rows into a per-organization checkpoint, and `os audit verify` checks them. The three value columns enter each checkpoint as salted commitments; every other column enters in clear. +- **Sealed rows leave only by whole checkpoints.** The LifecycleService no longer deletes a row of an object that declares `lifecycle.seal` by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerSealedExpiry`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). +- **No sealer, no deletion.** While no sealed expiry is registered (an `AuditPlugin` with no crypto provider, a one-shot boot), a sealed object's rows past their policy are kept, the archive copy still runs, the sweep reports `seal-expiry-pending`, and the lifecycle service says so once at `warn`. A chain whose first remaining checkpoint does not follow its last expiry (a checkpoint removed outside the platform), or whose next checkpoint does not verify under a trusted key, is not expired past that point, and the sealer says so. +- **A tenant-scoped retention override does not apply to a sealed object.** One signed policy value covers a chain, so the global window stands for every organization, and the lifecycle service says so once. +- **A fully expired chain continues.** Its next checkpoint chains onto the expiry: sequence after the expiry's last, linked to its `last_removed_digest`. +- **`os audit verify` stays loud for a chain a fault left behind** (seat ruling 6885452378, ADR-0154 D3 as amended): a window that starts at or before the newest window a trusted `window` checkpoint names is sealed, so a row there that no checkpoint holds reads `late` and unsealed, and the check fails. +- **The verify harness hands its crypto provider to `AuditPlugin`.** `bootStack` gives an `AuditPlugin` it mounts (an `extraPlugins` entry, a stack `plugins` entry, or the provider `requires: ['audit']` constructs) the same `harnessCryptoProvider()` instance that settings and the engine get, never a bare `LocalCryptoProvider`; an instance composed with its own provider keeps it. +- The `lifecycle.seal` description no longer says the retention sweeper deletes sealed rows. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 14f4fea42d4..2121f29f711 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -223,6 +223,9 @@ lifecycle: { } ``` +The platform's own audit log, `sys_audit_log`, declares exactly this block, so +it is sealed on every deployment whose `AuditPlugin` has a crypto provider. + - Each hour of `created_at` is sealed ten minutes after it ends, per organization (and once for rows about no organization): into one checkpoint, or, when the hour holds more than 10,000 such rows, into @@ -277,7 +280,9 @@ lifecycle: { Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints: the sealer first writes a signed expiry amendment naming them, so the verifier reads them as `expired` rather than - missing. While no sealer is running, the sweeper keeps them. + missing. At most 10,000 such rows leave per object per sweep, and once the + backlog is drained a chain gains at most one expiry amendment a day. While no sealer is running (no + crypto provider), the sweeper keeps them and says so once. - Sealing needs a crypto provider, which the host passes to `AuditPlugin` as `cryptoProvider`. `os serve` passes the one it seals every secret with; an app that puts its own `AuditPlugin` in `plugins` passes one itself. Without diff --git a/packages/plugins/plugin-audit/src/audit-plugin.test.ts b/packages/plugins/plugin-audit/src/audit-plugin.test.ts index 087572071d8..0071d3f6fe4 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.test.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.test.ts @@ -624,3 +624,55 @@ describe('AuditPlugin — a host hands an app-supplied instance its crypto provi expect(sealer?.crypto).toBeUndefined(); }); }); + +describe('AuditPlugin — hands its sealer\'s expiry to the lifecycle service (ADR-0154 D8)', () => { + /** Start the sealer over a storage double whose registry holds no sealed object, with `lifecycle` as the service. */ + const start = async (plugin: AuditPlugin, lifecycle: unknown) => { + const engine = { getDriverForObject: () => undefined, registry: { getAllObjects: () => [] } }; + const ctx = { + logger: { info() {}, warn() {}, error() {}, debug() {} }, + getService: (name: string) => { + if (name === 'lifecycle') return lifecycle; + throw new Error(`no '${name}' service`); + }, + }; + (plugin as unknown as { startSealer(e: unknown, c: unknown): void }).startSealer(engine, ctx); + await (plugin as unknown as { sealer: { stop(): Promise } | null }).sealer?.stop(); + }; + const lifecycleDouble = () => { + const registered: Array<{ plan(request: unknown): Promise }> = []; + let unregistered = 0; + return { + registered, + unregistered: () => unregistered, + service: { + registerSealedExpiry(expiry: { plan(request: unknown): Promise }) { + registered.push(expiry); + return () => void (unregistered += 1); + }, + }, + }; + }; + + it('registers one expiry whose plan is the sealer\'s, and unregisters it on destroy', async () => { + const plugin = new AuditPlugin({ cryptoProvider: { label: 'host' } as never }); + const lifecycle = lifecycleDouble(); + await start(plugin, lifecycle.service); + expect(lifecycle.registered).toHaveLength(1); + // The sealer holds no sealed object, so its plan answers no run. + await expect(lifecycle.registered[0].plan({ object: 'sys_audit_log', policy: 'archive.keep', policyValue: '7y', cutoff: new Date(0).toISOString() })).resolves.toEqual([]); + await plugin.destroy(); + expect(lifecycle.unregistered()).toBe(1); + }); + + it('registers none with no crypto provider: nothing can be signed, so the lifecycle service keeps the sealed rows', async () => { + const lifecycle = lifecycleDouble(); + await start(new AuditPlugin(), lifecycle.service); + expect(lifecycle.registered).toEqual([]); + }); + + it('registers none, and still starts, beside a lifecycle service without the seam or with none at all', async () => { + await expect(start(new AuditPlugin({ cryptoProvider: { label: 'host' } as never }), {})).resolves.toBeUndefined(); + await expect(start(new AuditPlugin({ cryptoProvider: { label: 'host' } as never }), undefined)).resolves.toBeUndefined(); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index d168cc07adf..411619cad35 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -923,7 +923,9 @@ export class AuditPlugin implements Plugin { logger: ctx.logger, }); this.sealer.start(); - this.registerSealedExpiry(this.sealer, ctx); + // With no crypto provider nothing is sealed and no expiry can be signed: the + // lifecycle service then keeps the sealed rows and says so (ADR-0154 D8). + if (crypto) this.registerSealedExpiry(this.sealer, ctx); } /** From 51ba1c1a750a59507f18dcd68fa814985b488a43 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:42:26 +0000 Subject: [PATCH 05/16] test: adjust gates and cli audit verify pins to the sys_audit_log seal default (WIP) Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt Co-authored-by: Claude --- .../plugins/plugin-audit.md | 13 +++++++------ .../src/commands/audit/verify.integration.test.ts | 14 ++++++++------ .../verify.ownership-queue.integration.test.ts | 3 ++- .../lifecycle-service.sealed-expiry.test.ts | 7 +++++-- packages/verify/vitest.config.ts | 1 + scripts/engine-double-contract.pinned.json | 5 +++++ 6 files changed, 28 insertions(+), 15 deletions(-) diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-audit.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-audit.md index 2d3ff9b3fd3..a3364599cfc 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-audit.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-audit.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 21 | +| Write call sites | 22 | | Object name statically decidable | 15 | -| Object name chosen at run time | 6 | +| Object name chosen at run time | 7 | | Object name spelled inline | 11 | | Object name spelled through a `const` | 4 | | Object name is an `object: string` parameter | 0 | -| Object name is some other run-time expression | 6 | +| Object name is some other run-time expression | 7 | | Against a tenancy-enabled object | 15 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 16 | +| Threading a tenant context | 17 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 5 | | …and decidably tenancy-enabled | 4 | -| Threading a decidably elevated (`isSystem`) context | 16 | +| Threading a decidably elevated (`isSystem`) context | 17 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 5 | -| Receiver carried a readable engine type | 21 | +| Receiver carried a readable engine type | 22 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -51,6 +51,7 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-audit/src/activity-changed-fields-backfill.ts` | `update` | `sys_activity` | enabled | elevated | 1 | | `packages/plugins/plugin-audit/src/app-activity-door.ts` | `insert` | `sys_activity` | enabled | options unreadable | 1 | | `packages/plugins/plugin-audit/src/audit-seal/amendment-writer.ts` | `insert` | `AUDIT_AMENDMENT_OBJECT` | undecidable | elevated | 1 | +| `packages/plugins/plugin-audit/src/audit-seal/expiry.ts` | `insert` | `AUDIT_AMENDMENT_OBJECT` | undecidable | elevated | 1 | | `packages/plugins/plugin-audit/src/audit-seal/sealer.ts` | `insert` | `AUDIT_CHECKPOINT_OBJECT` | undecidable | elevated | 1 | | `packages/plugins/plugin-audit/src/audit-seal/signer.ts` | `insert` | `AUDIT_SIGNING_KEY_OBJECT` | undecidable | elevated | 1 | | `packages/plugins/plugin-audit/src/audit-seal/signer.ts` | `delete` | `sys_secret` | enabled | options unreadable | 1 | diff --git a/packages/cli/src/commands/audit/verify.integration.test.ts b/packages/cli/src/commands/audit/verify.integration.test.ts index c1f89a42660..9f98f9e2b95 100644 --- a/packages/cli/src/commands/audit/verify.integration.test.ts +++ b/packages/cli/src/commands/audit/verify.integration.test.ts @@ -18,7 +18,8 @@ * the run exits 1; * 3. a usage error, a declared archive this boot cannot reach, and a run * with no data key to open the stored checkpoints, exit 2 with no verdict; - * 4. a project that seals nothing exits 0 and says so, and no run starts + * 4. a project that declares no seal of its own still checks the platform's + * sealed audit log and exits 0, and no run starts * the sealer: a due row stays unsealed and no run reports on sealing; * 5. `--out` writes the proof bundle, with no stored value and no wrapped * secret in it, and `--bundle` re-judges it with no boot, from an empty @@ -293,7 +294,7 @@ beforeAll(async () => { ], [sealedObject]); runs.unreachable = await verify(unreachable, join(unreachable, 'main.db'), ['--json']); - // A project that seals nothing. + // A project that declares no seal of its own: only the platform's audit log is sealed. const plain = mkdtempSync(join(tmpdir(), 'os-31908-plain-')); dirs.push(plain); writeArtifact(plain, [], [{ name: 'os31908_plain', fields: { name: { type: 'text' } } }]); @@ -325,7 +326,8 @@ describe('os audit verify over a sealed ledger and its archive (ADR-0154 D9)', ( const run = runs.clean; expect(run.code, run.stderr.slice(-2000)).toBe(0); const { report } = doc(run); - expect(report).toMatchObject({ ok: true, sealed: true, objects: [LEDGER], faults: [], rows: [] }); + // `sys_audit_log` is sealed by its own declaration (ADR-0154 D10), so every project checks it too. + expect(report).toMatchObject({ ok: true, sealed: true, objects: [LEDGER, 'sys_audit_log'], faults: [], rows: [] }); expect(report.totals.unmodified).toBe(5); expect(report.keys.trusted).toHaveLength(1); expect(report.keys.trusted[0]).toMatch(/^[0-9a-f]{64}$/); @@ -360,7 +362,7 @@ describe('os audit verify over a sealed ledger and its archive (ADR-0154 D9)', ( const run = runs.unreachable; expect(run.code, run.stderr.slice(-2000)).toBe(2); expect(doc(run)).toMatchObject({ error: 'archive_not_connected' }); - expect(doc(run).message).toContain("Archive datasource 'archive' (os31908_ledger) is not connected on this boot"); + expect(doc(run).message).toContain("Archive datasource 'archive' (os31908_ledger, sys_audit_log) is not connected on this boot"); }); it('3c. a run with no data key exits 2 with no verdict: the checkpoints it would judge cannot be opened', () => { @@ -377,10 +379,10 @@ describe('os audit verify over a sealed ledger and its archive (ADR-0154 D9)', ( for (const [name, run] of Object.entries(runs)) expect(run.stderr, name).not.toContain('AuditSealer'); }); - it('4. a project that seals nothing exits 0 and says so', () => { + it('4. a project that declares no seal of its own still checks the platform\'s sealed audit log, and exits 0 (ADR-0154 D10)', () => { const run = runs.nothing; expect(run.code, run.stderr.slice(-2000)).toBe(0); - expect(doc(run).report).toMatchObject({ ok: true, sealed: false, objects: [] }); + expect(doc(run).report).toMatchObject({ ok: true, sealed: true, objects: ['sys_audit_log'], faults: [], rows: [] }); }); }); diff --git a/packages/cli/src/commands/audit/verify.ownership-queue.integration.test.ts b/packages/cli/src/commands/audit/verify.ownership-queue.integration.test.ts index 92fccec8c75..1f21b7a210e 100644 --- a/packages/cli/src/commands/audit/verify.ownership-queue.integration.test.ts +++ b/packages/cli/src/commands/audit/verify.ownership-queue.integration.test.ts @@ -206,7 +206,8 @@ describe('os audit verify on a stack that declares queues and assignmentRules (A expect(run.code, `${run.stdout.slice(0, 2000)}\n${run.stderr.slice(-2000)}`).toBe(0); const doc = JSON.parse(run.stdout); expect(doc.error).toBeUndefined(); - expect(doc.report).toMatchObject({ ok: true, sealed: true, objects: [LEDGER], faults: [], rows: [] }); + // `sys_audit_log` is sealed by its own declaration (ADR-0154 D10), so it is checked beside the ledger. + expect(doc.report).toMatchObject({ ok: true, sealed: true, objects: [LEDGER, 'sys_audit_log'], faults: [], rows: [] }); expect(doc.report.totals.unmodified).toBe(3); }); }); diff --git a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts index 257e863c622..d52d2de809c 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts @@ -8,6 +8,7 @@ import { type LifecycleSealedExpiryRequest, type LifecycleSealedExpiryRun, } from './lifecycle-service.js'; +import { assertEngineDeleteDispatch } from '@objectstack/metadata-core'; import { parseLifecycleDuration } from './duration.js'; /** @@ -77,10 +78,12 @@ function engineOver(objects: LifecycleObjectLike[], opts: { hot?: ReturnType ids.includes(r.id as string)); + const ids: string[] | undefined = q?.where?.id?.$in; + const matched = ids ? rows.filter((r) => ids.includes(r.id as string)) : rows; + return typeof q?.limit === 'number' ? matched.slice(0, q.limit) : matched; }, async delete(object: string, q: any) { + assertEngineDeleteDispatch(q); deletes.push({ object, where: q?.where, context: q?.context }); rows = rows.filter((r) => r.id !== q?.where?.id); return { deletedCount: 1 }; diff --git a/packages/verify/vitest.config.ts b/packages/verify/vitest.config.ts index 28d95429862..e6bc6f5a27f 100644 --- a/packages/verify/vitest.config.ts +++ b/packages/verify/vitest.config.ts @@ -58,6 +58,7 @@ export default defineConfig({ alias: [ { find: /^@objectstack\/core$/, replacement: path.resolve(HERE, '../core/src/index.ts') }, { find: /^@objectstack\/metadata$/, replacement: path.resolve(HERE, '../metadata/src/index.ts') }, + { find: /^@objectstack\/plugin-audit$/, replacement: path.resolve(HERE, '../plugins/plugin-audit/src/index.ts') }, ], }, test: { diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 9ee0653af5d..8995ed1146a 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -3101,6 +3101,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts", + "verb": "delete", + "pinned": 1 + }, { "file": "packages/objectql/src/meta-object-primary-designation-roundtrip.test.ts", "verb": "delete", From 9177bc8995af8c41e8e470877ec96b09ce4a781e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:56:24 +0000 Subject: [PATCH 06/16] docs: production readiness names the sealed audit log and its global expiry window Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt Co-authored-by: Claude --- content/docs/deployment/production-readiness.mdx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/content/docs/deployment/production-readiness.mdx b/content/docs/deployment/production-readiness.mdx index cdf88fefd9d..8b6db9137f6 100644 --- a/content/docs/deployment/production-readiness.mdx +++ b/content/docs/deployment/production-readiness.mdx @@ -205,6 +205,8 @@ and per-class budgets: the `lifecycle.retention_overrides` setting **before** go-live if your compliance regime needs longer, and register an `archive` datasource if audit data must move to cold storage instead of being retained hot. + The sealed audit log expires by whole checkpoints under its global + window: a tenant-scoped override does not change it. ## CDN / reverse-proxy caching of `/meta` object schemas @@ -282,5 +284,6 @@ strongly, so a layer that weakens it to `W/` makes those saves fail. recipe, not the endpoint, because TLS / auth / path conventions vary. - **A built-in audit log immutability layer.** `@objectstack/plugin-audit` writes `sys_audit_log` records via ObjectQL afterInsert/afterUpdate/afterDelete - hooks; durable storage and tamper-evidence are the host's choice - (append-only S3, immudb, etc.). + hooks and seals them (ADR-0154), so a change or delete made outside the + platform shows in `os audit verify`. Sealing detects; it does not prevent: + write-once storage is the host's choice (append-only S3, immudb, etc.). From 586021655c52e5add24cea97df85270cf1ae4c42 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:47:32 +0000 Subject: [PATCH 07/16] fix(plugin-audit): pass --sealer-stopped in the SQLite audit-migrate pins; type the sealed-expiry test's veto sys_audit_log now declares lifecycle.seal, so an `os migrate audit-* --apply` run on SQLite needs --sealer-stopped (ADR-0154 D3 amended, B). The four archive/preview integration files pass it; the changeset names the operator change. The lifecycle sealed-expiry test's partial-veto double returns string ids. Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt Co-authored-by: Claude --- .changeset/31908-p4c-sealed-expiry.md | 1 + .../audit-key-material.archive.integration.test.ts | 10 ++++++---- .../audit-mail-bodies.archive.integration.test.ts | 10 ++++++---- .../audit-side-copies.archive.integration.test.ts | 6 ++++-- .../migrate/preview-read-only.integration.test.ts | 3 ++- .../lifecycle/lifecycle-service.sealed-expiry.test.ts | 2 +- 6 files changed, 20 insertions(+), 12 deletions(-) diff --git a/.changeset/31908-p4c-sealed-expiry.md b/.changeset/31908-p4c-sealed-expiry.md index a65875816c0..8ed154695bf 100644 --- a/.changeset/31908-p4c-sealed-expiry.md +++ b/.changeset/31908-p4c-sealed-expiry.md @@ -14,6 +14,7 @@ ADR-0154 D8 and D10 (#31908, slice P4c, the last one). - **`sys_audit_log` is sealed.** Its lifecycle declares `seal: { valueFields: ['old_value', 'new_value', 'metadata'] }`, so every deployment whose `AuditPlugin` has a crypto provider (`os serve` hands it one) signs each hour's audit rows into a per-organization checkpoint, and `os audit verify` checks them. The three value columns enter each checkpoint as salted commitments; every other column enters in clear. - **Sealed rows leave only by whole checkpoints.** The LifecycleService no longer deletes a row of an object that declares `lifecycle.seal` by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerSealedExpiry`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). +- **`os migrate audit-* --apply` on SQLite or Turso now needs `--sealer-stopped` for the audit log.** The rule 18.6.0 set for a sealed object now holds on every deployment, since `sys_audit_log` is one: stop every server that seals the database, then run with the flag. Postgres and MySQL take the audit seal lock as before, and a dry run is unchanged. - **No sealer, no deletion.** While no sealed expiry is registered (an `AuditPlugin` with no crypto provider, a one-shot boot), a sealed object's rows past their policy are kept, the archive copy still runs, the sweep reports `seal-expiry-pending`, and the lifecycle service says so once at `warn`. A chain whose first remaining checkpoint does not follow its last expiry (a checkpoint removed outside the platform), or whose next checkpoint does not verify under a trusted key, is not expired past that point, and the sealer says so. - **A tenant-scoped retention override does not apply to a sealed object.** One signed policy value covers a chain, so the global window stands for every organization, and the lifecycle service says so once. - **A fully expired chain continues.** Its next checkpoint chains onto the expiry: sequence after the expiry's last, linked to its `last_removed_digest`. diff --git a/packages/cli/src/commands/migrate/audit-key-material.archive.integration.test.ts b/packages/cli/src/commands/migrate/audit-key-material.archive.integration.test.ts index 614cb9d7c19..f04b0cdfaf7 100644 --- a/packages/cli/src/commands/migrate/audit-key-material.archive.integration.test.ts +++ b/packages/cli/src/commands/migrate/audit-key-material.archive.integration.test.ts @@ -249,10 +249,12 @@ beforeAll(async () => { runs.dry = await runCommand(dir, mainDb, ['--json']); archivedAfterDry = auditRows(archiveDb); hotAfterDry = auditRows(mainDb); - runs.apply = await runCommand(dir, mainDb, ['--apply', '--yes', '--json']); + // [#31908] sys_audit_log declares lifecycle.seal, and SQLite offers no session lock: an --apply run + // needs --sealer-stopped (ADR-0154 D3 amended, B). No server seals this fixture while the command runs. + runs.apply = await runCommand(dir, mainDb, ['--apply', '--yes', '--sealer-stopped', '--json']); archivedAfterApply = auditRows(archiveDb); hotAfterApply = auditRows(mainDb); - runs.again = await runCommand(dir, mainDb, ['--apply', '--yes', '--json']); + runs.again = await runCommand(dir, mainDb, ['--apply', '--yes', '--sealer-stopped', '--json']); archivedAfterAgain = auditRows(archiveDb); ageDetail = sweep('age'); @@ -263,7 +265,7 @@ beforeAll(async () => { runtimeRowDir = mkdtempSync(join(tmpdir(), 'os-26687-runtime-row-')); runtimeRowDb = join(runtimeRowDir, 'main.db'); writeArtifact(runtimeRowDir, []); - noArchiveRun = await runCommand(runtimeRowDir, runtimeRowDb, ['--apply', '--yes', '--json']); + noArchiveRun = await runCommand(runtimeRowDir, runtimeRowDb, ['--apply', '--yes', '--sealer-stopped', '--json']); const db = new Database(runtimeRowDb); try { db.prepare("INSERT INTO sys_metadata (id, name, type, scope, metadata, state, version) VALUES ('md_26687', 'archive', 'datasource', 'platform', ?, 'active', 1)") @@ -282,7 +284,7 @@ beforeAll(async () => { writeArtifact(unreachableDir, [ { name: 'archive', driver: 'postgres', config: { host: '127.0.0.1', port: 1, database: 'archive', username: 'os26687' }, autoConnect: true }, ]); - unreachableRun = await runCommand(unreachableDir, join(unreachableDir, 'main.db'), ['--apply', '--yes', '--json']); + unreachableRun = await runCommand(unreachableDir, join(unreachableDir, 'main.db'), ['--apply', '--yes', '--sealer-stopped', '--json']); }, HOOK_TIMEOUT_MS); afterAll(() => { diff --git a/packages/cli/src/commands/migrate/audit-mail-bodies.archive.integration.test.ts b/packages/cli/src/commands/migrate/audit-mail-bodies.archive.integration.test.ts index c6f44db17f4..86c8c5b2748 100644 --- a/packages/cli/src/commands/migrate/audit-mail-bodies.archive.integration.test.ts +++ b/packages/cli/src/commands/migrate/audit-mail-bodies.archive.integration.test.ts @@ -257,10 +257,12 @@ beforeAll(async () => { runs.dry = await runCommand(dir, mainDb, ['--json']); archivedAfterDry = auditRows(archiveDb); hotAfterDry = auditRows(mainDb); - runs.apply = await runCommand(dir, mainDb, ['--apply', '--yes', '--json']); + // [#31908] sys_audit_log declares lifecycle.seal, and SQLite offers no session lock: an --apply run + // needs --sealer-stopped (ADR-0154 D3 amended, B). No server seals this fixture while the command runs. + runs.apply = await runCommand(dir, mainDb, ['--apply', '--yes', '--sealer-stopped', '--json']); archivedAfterApply = auditRows(archiveDb); hotAfterApply = auditRows(mainDb); - runs.again = await runCommand(dir, mainDb, ['--apply', '--yes', '--json']); + runs.again = await runCommand(dir, mainDb, ['--apply', '--yes', '--sealer-stopped', '--json']); archivedAfterAgain = auditRows(archiveDb); ageDetail = sweep('age'); @@ -271,7 +273,7 @@ beforeAll(async () => { runtimeRowDir = mkdtempSync(join(tmpdir(), 'os-24899-runtime-row-')); runtimeRowDb = join(runtimeRowDir, 'main.db'); writeArtifact(runtimeRowDir, []); - noArchiveRun = await runCommand(runtimeRowDir, runtimeRowDb, ['--apply', '--yes', '--json']); + noArchiveRun = await runCommand(runtimeRowDir, runtimeRowDb, ['--apply', '--yes', '--sealer-stopped', '--json']); const db = new Database(runtimeRowDb); try { db.prepare("INSERT INTO sys_metadata (id, name, type, scope, metadata, state, version) VALUES ('md_24899', 'archive', 'datasource', 'platform', ?, 'active', 1)") @@ -290,7 +292,7 @@ beforeAll(async () => { writeArtifact(unreachableDir, [ { name: 'archive', driver: 'postgres', config: { host: '127.0.0.1', port: 1, database: 'archive', username: 'os24899' }, autoConnect: true }, ]); - unreachableRun = await runCommand(unreachableDir, join(unreachableDir, 'main.db'), ['--apply', '--yes', '--json']); + unreachableRun = await runCommand(unreachableDir, join(unreachableDir, 'main.db'), ['--apply', '--yes', '--sealer-stopped', '--json']); }, HOOK_TIMEOUT_MS); afterAll(() => { diff --git a/packages/cli/src/commands/migrate/audit-side-copies.archive.integration.test.ts b/packages/cli/src/commands/migrate/audit-side-copies.archive.integration.test.ts index 9d1a434b283..11d137949a3 100644 --- a/packages/cli/src/commands/migrate/audit-side-copies.archive.integration.test.ts +++ b/packages/cli/src/commands/migrate/audit-side-copies.archive.integration.test.ts @@ -255,10 +255,12 @@ beforeAll(async () => { runs.scoped = await runCommand(dir, mainDb, ['--object', 'sys_activity', '--apply', '--yes', '--json']); archivedAfterScoped = auditRows(archiveDb); hotAfterScoped = auditRows(mainDb); - runs.apply = await runCommand(dir, mainDb, ['--apply', '--yes', '--json']); + // [#31908] sys_audit_log declares lifecycle.seal, and SQLite offers no session lock: an --apply run + // needs --sealer-stopped (ADR-0154 D3 amended, B). No server seals this fixture while the command runs. + runs.apply = await runCommand(dir, mainDb, ['--apply', '--yes', '--sealer-stopped', '--json']); archivedAfterApply = auditRows(archiveDb); hotAfterApply = auditRows(mainDb); - runs.again = await runCommand(dir, mainDb, ['--apply', '--yes', '--json']); + runs.again = await runCommand(dir, mainDb, ['--apply', '--yes', '--sealer-stopped', '--json']); archivedAfterAgain = auditRows(archiveDb); ageDetail = sweep('age'); diff --git a/packages/cli/src/commands/migrate/preview-read-only.integration.test.ts b/packages/cli/src/commands/migrate/preview-read-only.integration.test.ts index 0f8e6fdc944..37dc280811c 100644 --- a/packages/cli/src/commands/migrate/preview-read-only.integration.test.ts +++ b/packages/cli/src/commands/migrate/preview-read-only.integration.test.ts @@ -457,7 +457,8 @@ for (const cell of DIALECT_CELLS) { }, cell.timeout); it('audit-metadata-bodies --apply still redacts the cleartext copy (the control)', async () => { - const { payload } = await runJson(auditBodies, ['--apply', '--yes', '--database-url', fixture!.databaseUrl]); + // [#31908] sys_audit_log is sealed by default, and SQLite offers no session lock: --sealer-stopped (ADR-0154 D3 amended, B). + const { payload } = await runJson(auditBodies, ['--apply', '--yes', '--sealer-stopped', '--database-url', fixture!.databaseUrl]); expect(payload.apply).toBe(true); expect(payload.report.byObject.sys_audit_log.rewritten).toBe(1); diff --git a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts index d52d2de809c..89c909b780f 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts @@ -183,7 +183,7 @@ describe('LifecycleService — a sealed object expires only through the sealed e it('a run a reap guard vetoes in part is not completed: its rows that went stay gone, its checkpoints stay for the next sweep', async () => { const { engine, deletes } = engineOver([RETAINED], { rows: [{ id: 'r1' }, { id: 'r2' }, { id: 'r3' }] }); const svc = service(engine); - svc.registerReapGuard('app_ledger', async (_o, rows) => rows.map((r) => r.id).filter((id) => id !== 'r2')); + svc.registerReapGuard('app_ledger', async (_o, rows) => rows.map((r) => r.id as string).filter((id) => id !== 'r2')); const { expiry, completed } = expiryOf([ { chain: 'org:a', rowIds: ['r1', 'r2'] }, { chain: 'org:b', rowIds: ['r3'] }, From 4deab949980d45dd8a860ca86b187b4c38379691 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:00:11 +0000 Subject: [PATCH 08/16] test(cli): pay the preview-read-only fixture's dynamic imports at module load The edited test file is now judged by the test-source alias gate's source reach: each dist-resolved dependency its served boot reaches through a dynamic import gets a module-top side-effect import. Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt Co-authored-by: Claude --- .../migrate/preview-read-only.integration.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/cli/src/commands/migrate/preview-read-only.integration.test.ts b/packages/cli/src/commands/migrate/preview-read-only.integration.test.ts index 37dc280811c..3a84bf8f862 100644 --- a/packages/cli/src/commands/migrate/preview-read-only.integration.test.ts +++ b/packages/cli/src/commands/migrate/preview-read-only.integration.test.ts @@ -63,6 +63,18 @@ import { isExitSignal } from '../../utils/format.js'; // MODULE LOAD: the fixture's served boot reaches it through a dynamic // `import()` inside a clocked hook (`scripts/check-test-source-alias.mjs`). import '@objectstack/runtime'; +import '@objectstack/cloud-connection'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/service-automation'; +import '@objectstack/service-datasource'; +import '@objectstack/service-settings'; +import '@objectstack/service-storage'; import { withDefaultOrganization } from '../../utils/default-organization-plugin.testkit.js'; const HERE = dirname(fileURLToPath(import.meta.url)); From 46e272ed4599332945e9a7e0709e08f08408f8aa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:02:29 +0000 Subject: [PATCH 09/16] fix(plugin-audit): admit every checkpoint a resumed expiry deletes; apply tenant windows per chain Review 7198128323 and its seat rulings: - a resumed expiry admits each checkpoint left in its range under a trusted key, consecutively to the amendment's last sequence and digest, or deletes nothing; a chain head and the object floor follow only an admitted expiry; - a tenant-scoped retention window travels to the sealed expiry and applies to its organization's chain; a chain of no one organization takes the longest window; - the resumed range is removed oldest first; an archive store with no bulkDelete is never planned; - the seam is registerExpiryPrefix, as the slice plan ruled; - the changeset declares the narrowing and the semantic change (minor), with the BREAKING banner and the ADR-0087 marker; cli.mdx and upgrading.mdx name the audit seal lock for every deployment. Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt Co-authored-by: Claude --- .changeset/31908-p4c-sealed-expiry.md | 32 +++++-- content/docs/data-modeling/objects.mdx | 11 ++- content/docs/deployment/cli.mdx | 10 ++ content/docs/references/data/object.mdx | 4 +- content/docs/upgrading.mdx | 2 +- .../lifecycle-service.sealed-expiry.test.ts | 73 ++++++++++++-- .../src/lifecycle/lifecycle-service.ts | 68 ++++++++++---- .../plugin-audit/src/audit-plugin.test.ts | 2 +- .../plugins/plugin-audit/src/audit-plugin.ts | 16 ++-- ...audit-seal-expiry-live.integration.test.ts | 35 +++++++ .../audit-seal-expiry-window.test.ts | 47 ++++++++++ .../plugin-audit/src/audit-seal/expiry.ts | 94 ++++++++++++++++--- .../plugin-audit/src/audit-seal/sealer.ts | 57 ++++++++--- packages/spec/src/data/object.zod.ts | 6 +- 14 files changed, 377 insertions(+), 80 deletions(-) create mode 100644 packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts diff --git a/.changeset/31908-p4c-sealed-expiry.md b/.changeset/31908-p4c-sealed-expiry.md index 8ed154695bf..367fadf30a6 100644 --- a/.changeset/31908-p4c-sealed-expiry.md +++ b/.changeset/31908-p4c-sealed-expiry.md @@ -1,22 +1,34 @@ --- -'@objectstack/plugin-audit': patch -'@objectstack/objectql': patch -'@objectstack/verify': patch -'@objectstack/spec': patch +'@objectstack/plugin-audit': minor +'@objectstack/objectql': minor +'@objectstack/verify': minor +'@objectstack/spec': minor --- feat(plugin-audit): the audit log is sealed by default, and sealed rows expire by whole checkpoints under a signed expiry amendment -Clause-②: yes (widening) (LifecycleService gains a public prefix-expiry seam for sealed objects: `registerSealedExpiry` and the `LifecycleSealedExpiry` types) -Metadata-protocol: none (the `seal` key landed in P1b; this changes a platform object's declaration only) +Clause-②: yes (narrowing) — narrowed: because `sys_audit_log` now declares `lifecycle.seal` on every deployment, `os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies` with `--apply` refuse on SQLite or Turso without `--sealer-stopped`, and on Postgres or MySQL take the audit seal lock and refuse when a sealer pass still holds it after ten minutes, where 18.6.0 ran them unlocked on a deployment that sealed nothing; `os audit verify` exits 1 on a row in a window at or before the newest window a trusted `window` checkpoint names that no checkpoint holds (`late`, unsealed), where it read the window unsealed and exited 0; and `verifyAuditLedger` throws for `sys_audit_log` when the `archive` datasource it archives to is not connected and no `archive` is passed. This breaks the bound changeset `35c9a30` (#33675) set, "No object declares `lifecycle.seal` by default, so a deployment that did not opt in sees no change": this release is the one that opts every deployment in. Widened: `@objectstack/objectql` `LifecycleService.registerExpiryPrefix` and the types `LifecycleSealedExpiry`, `LifecycleSealedExpiryRequest` (with its `tenants` windows), `LifecycleSealedExpiryRun`; a sweep entry's `policy` gains `'expiry'` and `skipped[].reason` gains `seal-expiry-pending` and `seal-delete-unsupported`. +Metadata-protocol: semantic — on an object that declares `lifecycle.seal`, the authored `retention.maxAge`, `ttl.expireAfter` and `archive.keep` no longer delete a row at its row cutoff: rows leave by whole checkpoints under a signed expiry amendment, counted to the start of a UTC day, at most 10,000 a sweep, and not at all while no sealer runs +Skills-docs: follow-up owed — this claim's second PR (amendment 7193137455) rewrites `skills/objectstack-data/rules/lifecycle.md`, which still says the sweeper deletes sealed rows + + + +**BREAKING** for operators and library callers, because the audit log is now sealed on every deployment: + +- **`os migrate audit-* --apply` on SQLite or Turso** stops before writing and names the flag. Fix: stop every server that seals the database, then run it again with `--sealer-stopped`. +- **The same run on Postgres or MySQL** waits up to ten minutes for a sealer pass in flight, then refuses having changed nothing. Fix: run it again once that pass has finished. +- **`os audit verify` exits 1** on a row it reads `late` and unsealed in a window another chain of the object already sealed. Fix: none is owed by the command; read the rows the report names (a chain a fault left behind), and run it again after the sealer's next pass. +- **`verifyAuditLedger`** (`@objectstack/plugin-audit`) throws for `sys_audit_log` when its `archive` datasource is not connected. Fix: pass `archive`, for example `archive: () => 'none'` where the deployment has no archive datasource. + +Every dry run is unchanged. A deployment's own objects that do not declare `lifecycle.seal` keep the row-cutoff retention they had. ADR-0154 D8 and D10 (#31908, slice P4c, the last one). - **`sys_audit_log` is sealed.** Its lifecycle declares `seal: { valueFields: ['old_value', 'new_value', 'metadata'] }`, so every deployment whose `AuditPlugin` has a crypto provider (`os serve` hands it one) signs each hour's audit rows into a per-organization checkpoint, and `os audit verify` checks them. The three value columns enter each checkpoint as salted commitments; every other column enters in clear. -- **Sealed rows leave only by whole checkpoints.** The LifecycleService no longer deletes a row of an object that declares `lifecycle.seal` by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerSealedExpiry`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). -- **`os migrate audit-* --apply` on SQLite or Turso now needs `--sealer-stopped` for the audit log.** The rule 18.6.0 set for a sealed object now holds on every deployment, since `sys_audit_log` is one: stop every server that seals the database, then run with the flag. Postgres and MySQL take the audit seal lock as before, and a dry run is unchanged. -- **No sealer, no deletion.** While no sealed expiry is registered (an `AuditPlugin` with no crypto provider, a one-shot boot), a sealed object's rows past their policy are kept, the archive copy still runs, the sweep reports `seal-expiry-pending`, and the lifecycle service says so once at `warn`. A chain whose first remaining checkpoint does not follow its last expiry (a checkpoint removed outside the platform), or whose next checkpoint does not verify under a trusted key, is not expired past that point, and the sealer says so. -- **A tenant-scoped retention override does not apply to a sealed object.** One signed policy value covers a chain, so the global window stands for every organization, and the lifecycle service says so once. +- **Sealed rows leave only by whole checkpoints.** The LifecycleService no longer deletes a row of an object that declares `lifecycle.seal` by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerExpiryPrefix`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). +- **`os migrate audit-* --apply` on SQLite or Turso now needs `--sealer-stopped` for the audit log.** The rule 18.6.0 set for a sealed object now holds on every deployment, since `sys_audit_log` is one: stop every server that seals the database, then run with the flag. That includes the `os migrate audit-side-copies --apply` an upgrade from 18.4.0 or earlier runs. Postgres and MySQL take the audit seal lock, and a dry run is unchanged. +- **No sealer, no deletion.** While no sealed expiry is registered (an `AuditPlugin` with no crypto provider, a one-shot boot), a sealed object's rows past their policy are kept, the archive copy still runs, the sweep reports `seal-expiry-pending`, and the lifecycle service says so once at `warn`; such a host keeps `sys_audit_log` past `archive.keep`, and its sealer reports the missing provider hourly at `error`. An archive store with no `bulkDelete` is never planned (`seal-delete-unsupported`), so no amendment is signed over rows it could not delete. A chain whose first remaining checkpoint does not follow its last expiry (a checkpoint removed outside the platform), or whose next checkpoint does not verify under a trusted key, is not expired past that point, and the sealer says so. A stopped expiry is resumed only over checkpoints that each verify under a trusted key and run on to the amendment's last sequence and digest; otherwise nothing in its range is deleted. An expiry deletes rows for good: a deleted row cannot be restored from the ledger. +- **A tenant-scoped retention override applies to its organization's chain.** The lifecycle service hands each tenant's window, through the same floors, to the sealed expiry (`LifecycleSealedExpiryRequest.tenants`); an organization's chain expires under its own window and its amendment signs that value, and the chain of rows about no organization expires under the longest window configured, so no chain expires under a window shorter than one set for its rows. - **A fully expired chain continues.** Its next checkpoint chains onto the expiry: sequence after the expiry's last, linked to its `last_removed_digest`. - **`os audit verify` stays loud for a chain a fault left behind** (seat ruling 6885452378, ADR-0154 D3 as amended): a window that starts at or before the newest window a trusted `window` checkpoint names is sealed, so a row there that no checkpoint holds reads `late` and unsealed, and the check fails. - **The verify harness hands its crypto provider to `AuditPlugin`.** `bootStack` gives an `AuditPlugin` it mounts (an `extraPlugins` entry, a stack `plugins` entry, or the provider `requires: ['audit']` constructs) the same `harnessCryptoProvider()` instance that settings and the engine get, never a bare `LocalCryptoProvider`; an instance composed with its own provider keeps it. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 2121f29f711..d42219befdc 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -280,9 +280,14 @@ it is sealed on every deployment whose `AuditPlugin` has a crypto provider. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints: the sealer first writes a signed expiry amendment naming them, so the verifier reads them as `expired` rather than - missing. At most 10,000 such rows leave per object per sweep, and once the - backlog is drained a chain gains at most one expiry amendment a day. While no sealer is running (no - crypto provider), the sweeper keeps them and says so once. + missing. The window is counted to the start of a UTC day, so a row can stay + up to a day past it, and at most 10,000 such rows leave per object per sweep, + so a backlog drains over several sweeps; once it has, a chain gains at most + one expiry amendment a day. A tenant-scoped retention window applies to that + organization's chain, and the chain of rows about no organization expires + under the longest window configured, so no row leaves before the window set + for it. While no sealer is running (no crypto provider), the sweeper keeps + them and says so once. - Sealing needs a crypto provider, which the host passes to `AuditPlugin` as `cryptoProvider`. `os serve` passes the one it seals every secret with; an app that puts its own `AuditPlugin` in `plugins` passes one itself. Without diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 4837a98a6eb..fc8468af737 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -2378,6 +2378,16 @@ crypto provider `os serve` seals with is available. ten minutes after it ends, and it can seal a row between the command's decision and its write; that row then reads `modified`. +**The audit seal lock.** An `--apply` run holds the audit seal lock from before +its first write to after its last, archive runs included, on the database of +each object it covers that declares `lifecycle.seal`. `sys_audit_log` declares +it, so this is every run that covers the audit log. On Postgres and MySQL the +run waits up to ten minutes for a sealer pass in flight, then refuses having +changed nothing: run it again once that pass has finished. On SQLite and Turso, +which offer no session lock, the run stops before writing and names +`--sealer-stopped`: stop every server that seals the database, then run it again +with the flag. A dry run takes no lock and needs no flag. + #### `os migrate organization-ownership` The v18 ownership ceremony (ADR-0131 D10), and the upgrade path of a database diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index dbf611f3938..ab9cb407aa8 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -82,7 +82,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing; while no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing; a tenant-scoped retention window applies to that organization's chain, and the window is counted to the start of a UTC day, so a row can stay up to a day longer. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Lifecycle.retention` @@ -384,7 +384,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing; while no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing; a tenant-scoped retention window applies to that organization's chain, and the window is counted to the start of a UTC day, so a row can stay up to a day longer. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Object.activityMilestones[number]` diff --git a/content/docs/upgrading.mdx b/content/docs/upgrading.mdx index 7ebe3ca2d3c..861dd00243e 100644 --- a/content/docs/upgrading.mdx +++ b/content/docs/upgrading.mdx @@ -491,7 +491,7 @@ the protocol-18 step, which `os migrate meta --from 17` lists for your sources **Upgrading from 18.4.0 or earlier:** run [`os migrate audit-side-copies`](/docs/deployment/cli#os-migrate-audit-side-copies) once, a dry run first and then `--apply`; it removes the side-copy columns (an approval request's `payload_json`) from the audit-ledger copies those releases wrote. Served copies are redacted at read time until it runs, so it is cleanup, not a gate. -**Upgrading from 18.5.0 or earlier:** the first [`os migrate plan`](/docs/deployment/cli#schema-migrations) after the move lists a safe `create_index` for each `(created_at, id)` and `(owner_id)` index schema sync now builds without a declaration, and on SQLite a `normalize_boolean_storage` step for boolean cells stored as text; the next sync or `os migrate apply` builds them, and neither is destructive. Where an app declares `lifecycle.seal`, an `os migrate audit-* --apply` run on SQLite or Turso now needs every sealing server stopped and `--sealer-stopped` ([18.6.0 checklist](/docs/releases/v18/18-6#upgrade-checklist)). +**Upgrading from 18.5.0 or earlier:** the first [`os migrate plan`](/docs/deployment/cli#schema-migrations) after the move lists a safe `create_index` for each `(created_at, id)` and `(owner_id)` index schema sync now builds without a declaration, and on SQLite a `normalize_boolean_storage` step for boolean cells stored as text; the next sync or `os migrate apply` builds them, and neither is destructive. Where an app declares `lifecycle.seal`, an `os migrate audit-* --apply` run on SQLite or Turso now needs every sealing server stopped and `--sealer-stopped` ([18.6.0 checklist](/docs/releases/v18/18-6#upgrade-checklist)). From the release that seals `sys_audit_log` by default, that holds on every deployment: see [Sealed audit rows](/docs/deployment/cli#sealed-audit-rows-os-migrate-audit-). **Upgrading from 18.6.0 or earlier:** the Console no longer reads the per-reader list preferences stored in `sys_user_preference` under `ui.list.`, so every reader's lists open on their views' own sorts, filters, columns, widths, row height and tab order; nothing is carried over. Once the upgraded Console is serving, run [`os migrate list-preferences`](/docs/deployment/cli#os-migrate-list-preferences) once, a dry run first and then `--apply --export `; it deletes those rows after writing them to an owner-only export. Left in place they are unread, so it is cleanup, not a gate. diff --git a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts index 89c909b780f..cf79ec7b34d 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts @@ -138,7 +138,7 @@ describe('LifecycleService — a sealed object expires only through the sealed e { chain: 'org:a', rowIds: ['e1', 'e2'] }, { chain: 'org:b', rowIds: ['e3'] }, ]); - svc.registerSealedExpiry(expiry); + svc.registerExpiryPrefix(expiry); const report = await svc.sweep(); @@ -153,11 +153,31 @@ describe('LifecycleService — a sealed object expires only through the sealed e expect(report.skipped).toEqual([]); }); + it('an archive store with no bulkDelete: the expiry is never planned, so no amendment is signed, and the rows are kept', async () => { + const hot = store('default', []); + const cold = store('archive', [{ id: 'e1' }]); + delete (cold.driver as { bulkDelete?: unknown }).bulkDelete; + const { engine } = engineOver([ARCHIVING], { hot, cold }); + const { warns, logger } = recordingLogger(); + const svc = service(engine, logger); + const { expiry, completed } = expiryOf([{ chain: 'org:a', rowIds: ['e1'] }]); + svc.registerExpiryPrefix(expiry); + + const report = await svc.sweep(); + await svc.sweep(); + + expect(expiry.plan).not.toHaveBeenCalled(); + expect(completed).toEqual([]); + expect(cold.remaining()).toEqual(['e1']); + expect(report.skipped).toContainEqual({ object: 'sys_audit_log', reason: 'seal-delete-unsupported' }); + expect(warns.filter((w) => /a store it lives on has no bulkDelete/.test(w))).toHaveLength(1); + }); + it('a retained sealed object: plans `retention.maxAge`, deletes each row through the engine, never by the cutoff', async () => { const { engine, deletes } = engineOver([RETAINED], { rows: [{ id: 'r1' }, { id: 'r2' }, { id: 'r3' }] }); const svc = service(engine); const { expiry, completed, requests } = expiryOf([{ chain: 'deployment', rowIds: ['r1', 'r2'] }]); - svc.registerSealedExpiry(expiry); + svc.registerExpiryPrefix(expiry); const report = await svc.sweep(); @@ -172,7 +192,7 @@ describe('LifecycleService — a sealed object expires only through the sealed e const { engine } = engineOver([TTL], { rows: [] }); const svc = service(engine); const { expiry, requests } = expiryOf([]); - svc.registerSealedExpiry(expiry); + svc.registerExpiryPrefix(expiry); const report = await svc.sweep(); @@ -188,7 +208,7 @@ describe('LifecycleService — a sealed object expires only through the sealed e { chain: 'org:a', rowIds: ['r1', 'r2'] }, { chain: 'org:b', rowIds: ['r3'] }, ]); - svc.registerSealedExpiry(expiry); + svc.registerExpiryPrefix(expiry); const report = await svc.sweep(); @@ -197,10 +217,45 @@ describe('LifecycleService — a sealed object expires only through the sealed e expect(report.swept).toEqual([{ object: 'app_ledger', class: 'audit', policy: 'expiry', cutoff: isoCutoff('30d'), deleted: 1 }]); }); + it('a tenant-scoped window travels to the sealed expiry for its organization, through the floors, and is not dropped', async () => { + const { engine } = engineOver([RETAINED], { rows: [] }); + const find = engine.find; + engine.find = async (object: string, q: any) => + object === 'sys_organization' ? [{ id: 'org_long' }, { id: 'org_short' }] : find(object, q); + const tenantValues: Record = { + org_long: { app_ledger: { maxAge: '400d' } }, + org_short: { app_ledger: { maxAge: '10d' } }, + }; + const settings = { + async get(_ns: string, key: string, ctx?: Record) { + const tenantId = ctx?.tenantId as string | undefined; + if (key === 'retention_overrides' && tenantId && tenantValues[tenantId]) return { value: tenantValues[tenantId], source: 'tenant' }; + return { value: undefined, source: 'default' }; + }, + }; + const { warns, logger } = recordingLogger(); + const svc = new LifecycleService({ + getEngine: () => engine, logger, now: () => FIXED_NOW, initialDelayMs: 1, sweepIntervalMs: 10, + getSettings: () => settings as never, referenceAudit: { enabled: false }, + } as never); + const { expiry, requests } = expiryOf([]); + svc.registerExpiryPrefix(expiry); + + await svc.sweep(); + + expect(requests).toHaveLength(1); + expect(requests[0]).toMatchObject({ object: 'app_ledger', policy: 'retention.maxAge', policyValue: '30d', cutoff: isoCutoff('30d') }); + expect([...(requests[0].tenants ?? [])].sort((a, b) => a.tenantId.localeCompare(b.tenantId))).toEqual([ + { tenantId: 'org_long', policyValue: '400d', cutoff: isoCutoff('400d') }, + { tenantId: 'org_short', policyValue: '10d', cutoff: isoCutoff('10d') }, + ]); + expect(warns.join('\n')).not.toMatch(/do not apply/); + }); + it('a plan that fails deletes nothing and reports the object', async () => { const { engine, deletes } = engineOver([RETAINED], { rows: [{ id: 'r1' }] }); const svc = service(engine); - svc.registerSealedExpiry({ plan: async () => { throw new Error('no expiry amendment can be signed'); } }); + svc.registerExpiryPrefix({ plan: async () => { throw new Error('no expiry amendment can be signed'); } }); const report = await svc.sweep(); @@ -214,8 +269,8 @@ describe('LifecycleService — a sealed object expires only through the sealed e const svc = service(engine); const first = expiryOf([]); const second = expiryOf([]); - const unregisterFirst = svc.registerSealedExpiry(first.expiry); - const unregisterSecond = svc.registerSealedExpiry(second.expiry); + const unregisterFirst = svc.registerExpiryPrefix(first.expiry); + const unregisterSecond = svc.registerExpiryPrefix(second.expiry); unregisterFirst(); await svc.sweep(); @@ -230,7 +285,7 @@ describe('LifecycleService — a sealed object expires only through the sealed e it('refuses a registration with no plan method', () => { const svc = service(engineOver([]).engine); - expect(() => svc.registerSealedExpiry({} as never)).toThrow(/requires an object with a plan\(request\) method/); + expect(() => svc.registerExpiryPrefix({} as never)).toThrow(/requires an object with a plan\(request\) method/); }); it('an object without `seal` keeps the row-cutoff path, and never asks the sealed expiry', async () => { @@ -238,7 +293,7 @@ describe('LifecycleService — a sealed object expires only through the sealed e const { engine, finds } = engineOver([plain], { rows: [] }); const svc = service(engine); const { expiry, requests } = expiryOf([]); - svc.registerSealedExpiry(expiry); + svc.registerExpiryPrefix(expiry); const report = await svc.sweep(); diff --git a/packages/objectql/src/lifecycle/lifecycle-service.ts b/packages/objectql/src/lifecycle/lifecycle-service.ts index 35f244bfd6f..f67c316a1a7 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.ts @@ -535,6 +535,16 @@ export interface LifecycleSealedExpiryRequest { readonly policyValue: string; /** Rows of windows that ended at or before this instant may expire (ISO-8601, UTC). */ readonly cutoff: string; + /** + * The tenant-scoped windows of this policy (`retention_overrides` at tenant + * scope), each through the same floors: an organization's chain expires + * under its own organization's window, in place of {@link policyValue} and + * {@link cutoff}. A chain of no one organization (the deployment chain) + * expires under the longest of all of them and the global one, so no chain + * ever expires under a window shorter than one configured for its rows. + * Absent when no tenant overrides the window. + */ + readonly tenants?: ReadonlyArray<{ readonly tenantId: string; readonly policyValue: string; readonly cutoff: string }>; } /** One chain's expiry, planned and signed: the rows the sweep deletes, then {@link complete}. */ @@ -910,9 +920,9 @@ export class LifecycleService { * Until one is registered, a sealed object's expiring rows are KEPT: the * sweep never deletes a sealed row by its own cutoff (see {@link sweepSealed}). */ - registerSealedExpiry(expiry: LifecycleSealedExpiry): () => void { + registerExpiryPrefix(expiry: LifecycleSealedExpiry): () => void { if (!expiry || typeof expiry.plan !== 'function') { - throw new Error('[lifecycle] registerSealedExpiry requires an object with a plan(request) method'); + throw new Error('[lifecycle] registerExpiryPrefix requires an object with a plan(request) method'); } this.sealedExpiry = expiry; this.sealedSaid.clear(); @@ -1663,8 +1673,10 @@ export class LifecycleService { * * A settings override of the window applies as on any object, through the * same floors, and the value applied is the one the amendment signs. A - * tenant-scoped override does not: a sealed chain's expiry is signed with one - * policy value per sweep, so it is said once and the global window stands. + * tenant-scoped override applies to its organization's chain, on the + * partition {@link tenantWindowsFor} decides for every reap: it travels as + * {@link LifecycleSealedExpiryRequest.tenants}, and each chain's amendment + * signs the window it expired under. */ private async reapSealed( engine: LifecycleEngineLike, @@ -1684,23 +1696,26 @@ export class LifecycleService { if (lc.retention) legs.push({ policy: 'retention.maxAge', kind: 'retention', key: 'maxAge', declared: lc.retention.maxAge }); const outcomes: Array = []; for (const leg of legs) { - const tenants = (this.governance.tenantOverrides.get(object) ?? []).filter((t) => typeof t[leg.key] === 'string'); - if (tenants.length > 0) { - this.saySealedOnce( - `tenant-override:${object}:${leg.key}`, - `[lifecycle] ${object} declares lifecycle.seal, so its tenant-scoped ${leg.key} override(s) ` + - `(${tenants.map((t) => t.tenantId).join(', ')}) do not apply: a sealed chain expires by whole checkpoints ` + - `under one signed policy value, and the global ${leg.policy} window stands for every organization.`, - ); - } const override = ov[leg.key]; const windowMs = this.effectiveWindowMs(override, parseLifecycleDuration(leg.declared), object, leg.kind, 'global', report); + const policyValue = appliedLiteral(override, leg.declared, windowMs); + // [#21918] The tenants that get a window of their own, as `reap()` decides them; each through the floors, + // its fallback the resolved global window. + const partition = this.tenantWindowsFor(obj, leg.key); + const tenants = (partition?.windows ?? []).map((t) => { + const tMs = this.effectiveWindowMs(t[leg.key], windowMs, object, leg.kind, `tenant:${t.tenantId}`, report); + return { + tenantId: t.tenantId, + policyValue: appliedLiteral(t[leg.key], policyValue, tMs), + cutoff: new Date(this.now() - tMs).toISOString(), + }; + }); outcomes.push( await this.sweepSealed( engine, obj, lc, - { policy: leg.policy, policyValue: appliedLiteral(override, leg.declared, windowMs), cutoffMs: this.now() - windowMs }, + { policy: leg.policy, policyValue, cutoffMs: this.now() - windowMs, ...(tenants.length > 0 ? { tenants } : {}) }, report, null, ), @@ -1725,7 +1740,12 @@ export class LifecycleService { engine: LifecycleEngineLike, obj: LifecycleObjectLike, lc: Lifecycle, - leg: { policy: LifecycleSealedExpiryRequest['policy']; policyValue: string; cutoffMs: number }, + leg: { + policy: LifecycleSealedExpiryRequest['policy']; + policyValue: string; + cutoffMs: number; + tenants?: LifecycleSealedExpiryRequest['tenants']; + }, report: LifecycleSweepReport, stores: readonly ArchiveCapableDriver[] | null, ): Promise { @@ -1745,7 +1765,23 @@ export class LifecycleService { ); return 0; } - const runs = await expiry.plan({ object, policy: leg.policy, policyValue: leg.policyValue, cutoff }); + // Asked before the plan, so no amendment is signed over rows a store could not then delete. + if (stores?.some((store) => typeof store.bulkDelete !== 'function')) { + report.skipped.push({ object, reason: 'seal-delete-unsupported' }); + this.saySealedOnce( + `bulk-delete:${object}`, + `[lifecycle] ${object} declares lifecycle.seal and archives, but a store it lives on has no bulkDelete, so ` + + `its rows past ${leg.policy} ${leg.policyValue} are KEPT: a sealed row leaves only by id, from both stores.`, + ); + return 0; + } + const runs = await expiry.plan({ + object, + policy: leg.policy, + policyValue: leg.policyValue, + cutoff, + ...(leg.tenants ? { tenants: leg.tenants } : {}), + }); let deleted = 0; for (const run of runs) { // [#4747] Leg boundary: a run not yet begun is the next sweep's; its amendment is already signed and it resumes. diff --git a/packages/plugins/plugin-audit/src/audit-plugin.test.ts b/packages/plugins/plugin-audit/src/audit-plugin.test.ts index 0071d3f6fe4..6afbb73ba25 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.test.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.test.ts @@ -646,7 +646,7 @@ describe('AuditPlugin — hands its sealer\'s expiry to the lifecycle service (A registered, unregistered: () => unregistered, service: { - registerSealedExpiry(expiry: { plan(request: unknown): Promise }) { + registerExpiryPrefix(expiry: { plan(request: unknown): Promise }) { registered.push(expiry); return () => void (unregistered += 1); }, diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 411619cad35..7634cc4c077 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -351,7 +351,7 @@ export class AuditPlugin implements Plugin { /** [ADR-0154 D3] The sealer, started at `kernel:ready` and stopped by `destroy()`. */ private sealer: AuditSealer | null = null; /** [ADR-0154 D8] Takes the sealer's expiry back off the lifecycle service, on `destroy()`. */ - private unregisterSealedExpiry: (() => void) | null = null; + private unregisterExpiryPrefix: (() => void) | null = null; /** * [#31796] The credential-use writer, built in `init()` (the `audit` slot @@ -925,7 +925,7 @@ export class AuditPlugin implements Plugin { this.sealer.start(); // With no crypto provider nothing is sealed and no expiry can be signed: the // lifecycle service then keeps the sealed rows and says so (ADR-0154 D8). - if (crypto) this.registerSealedExpiry(this.sealer, ctx); + if (crypto) this.registerExpiryPrefix(this.sealer, ctx); } /** @@ -936,9 +936,9 @@ export class AuditPlugin implements Plugin { * so nothing expires. A lifecycle service with no sealed expiry keeps a * sealed object's rows past their policy and says so. */ - private registerSealedExpiry(sealer: AuditSealer, ctx: PluginContext): void { + private registerExpiryPrefix(sealer: AuditSealer, ctx: PluginContext): void { type LifecycleLike = { - registerSealedExpiry?: (expiry: { plan(request: AuditExpiryRequest): Promise }) => () => void; + registerExpiryPrefix?: (expiry: { plan(request: AuditExpiryRequest): Promise }) => () => void; }; let lifecycle: LifecycleLike | undefined; try { @@ -946,9 +946,9 @@ export class AuditPlugin implements Plugin { } catch { return; } - if (!lifecycle || typeof lifecycle.registerSealedExpiry !== 'function') return; + if (!lifecycle || typeof lifecycle.registerExpiryPrefix !== 'function') return; // Called as a method: the service's registration reads its own state. - this.unregisterSealedExpiry = lifecycle.registerSealedExpiry({ plan: (request) => sealer.expire(request) }); + this.unregisterExpiryPrefix = lifecycle.registerExpiryPrefix({ plan: (request) => sealer.expire(request) }); } /** @@ -1172,8 +1172,8 @@ export class AuditPlugin implements Plugin { // before the process lets go, and never starts again. const sealer = this.sealer; this.sealer = null; - this.unregisterSealedExpiry?.(); - this.unregisterSealedExpiry = null; + this.unregisterExpiryPrefix?.(); + this.unregisterExpiryPrefix = null; await sealer?.stop(); const writer = this.readAuditWriter; this.readAuditWriter = null; diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-live.integration.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-live.integration.test.ts index bc2f98553a1..b4f5dac6bbe 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-live.integration.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-live.integration.test.ts @@ -282,4 +282,39 @@ describe('an expiry signs only what it can show the platform sealed (ADR-0154 D6 expect(warned.filter((m) => /'sys_audit_log' chain 'org:org_gap' is NOT expired: its first remaining checkpoint is sequence 1/.test(m))).toHaveLength(1); expect(warned.filter((m) => /'sys_audit_log' chain 'org:org_forged' is expired only up to its checkpoint 1/.test(m))).toHaveLength(1); }); + + it('never resumes a stored expiry over a checkpoint no trusted key signed: it deletes no row and no seed it lists', async () => { + // org_forged's admitted expiry ends at sequence 0, which the sweep removed. A row put there by hand, listing a + // live row and another chain's seed, sits inside that expiry's range. + const real = await checkpointOf('org:org_forged', 1); + const seed = String((await checkpointOf('org:org_gap', 1)).seed_handle); + await hot().create('sys_audit_checkpoint', { ...real, id: 'forged_resume_0', sequence: 0, previous_digest: null, seed_handle: seed }); + const before = (await expiries()).length; + const logger = (sealer as unknown as { options: { logger: { warn(m: string): void } } }).options.logger; + const warn = vi.spyOn(logger, 'warn'); + const report = await lifecycle.sweep(); + const warned = warn.mock.calls.map(([m]) => String(m)); + warn.mockRestore(); + + expect(report.errors).toEqual([]); + expect(await present('org_forged_1')).toBe(true); + expect((await engine.find('sys_secret', { where: { id: seed }, context: SYS })) as Row[]).toHaveLength(1); + expect(((await engine.find('sys_audit_checkpoint', { where: { id: 'forged_resume_0' }, context: SYS })) as Row[])).toHaveLength(1); + expect((await expiries()).length).toBe(before); + expect(warned.filter((m) => /'sys_audit_log' chain 'org:org_forged' is NOT expired further: the range its expiry 0–0/.test(m))).toHaveLength(1); + }); + + it('a chain head never follows an expiry amendment no trusted key signed', async () => { + // org_ok expired whole: its head is its expiry. A newer amendment row put there by hand names a later sequence. + const [stored] = (await expiries()).filter((row) => (amendmentBodyFromRow(row) as ExpiryAmendmentBody).tenant_id === 'org_ok'); + const admitted = amendmentBodyFromRow(stored) as ExpiryAmendmentBody; + await hot().create('sys_audit_amendment', { + ...stored, id: 'forged_head', last_sequence: admitted.last_sequence + 5, first_sequence: admitted.last_sequence + 1, + last_removed_digest: 'f'.repeat(64), signature: Buffer.alloc(64).toString('base64'), + }); + await hot().create(LOG, entry('org_ok_next', Math.floor(now / H) * H - 3 * H + 60_000, 'org_ok')); + expect(await sealer.runPass()).toBeGreaterThan(0); + const next = checkpointBodyFromRow(await checkpointOf('org:org_ok', admitted.last_sequence + 1)); + expect(next).toMatchObject({ row_ids: ['org_ok_next'], previous_digest: admitted.last_removed_digest }); + }); }); diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts new file mode 100644 index 00000000000..8e863c3e72d --- /dev/null +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts @@ -0,0 +1,47 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { auditExpiryCutoff, windowOf, type AuditExpiryRequest } from './expiry.js'; + +/** + * ADR-0154 D8, seat ruling on review 7198128323 S1: a tenant-scoped retention + * window applies to its organization's chain, and no chain expires under a + * window shorter than one configured for its rows. + */ + +const DAY = 24 * 60 * 60 * 1000; +const NOW = Date.UTC(2026, 10, 26, 15, 0, 0); +const at = (days: number) => new Date(NOW - days * DAY).toISOString(); + +const request: AuditExpiryRequest = { + object: 'app_ledger', + policy: 'retention.maxAge', + policyValue: '30d', + cutoff: at(30), + tenants: [ + { tenantId: 'org_long', policyValue: '400d', cutoff: at(400) }, + { tenantId: 'org_short', policyValue: '10d', cutoff: at(10) }, + ], +}; + +describe('windowOf — the window each chain of a sealed object expires under', () => { + it("an organization's chain takes its own tenant-scoped window, shorter or longer than the global one", () => { + expect(windowOf(request, 'org:org_long')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 400 * DAY), policyValue: '400d' }); + expect(windowOf(request, 'org:org_short')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 10 * DAY), policyValue: '10d' }); + }); + + it('an organization with no window of its own takes the global one', () => { + expect(windowOf(request, 'org:org_plain')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }); + }); + + it('a chain of no one organization takes the longest of all of them', () => { + expect(windowOf(request, 'deployment')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 400 * DAY), policyValue: '400d' }); + expect(windowOf({ ...request, tenants: [{ tenantId: 'org_short', policyValue: '10d', cutoff: at(10) }] }, 'deployment')) + .toEqual({ cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }); + }); + + it('with no tenant window every chain takes the global one', () => { + const { tenants: _, ...plain } = request; + expect(windowOf(plain, 'org:org_long')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-seal/expiry.ts b/packages/plugins/plugin-audit/src/audit-seal/expiry.ts index 7b68c94cb2e..605532aa123 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/expiry.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/expiry.ts @@ -8,6 +8,7 @@ import { AUDIT_AMENDMENT_OBJECT, AUDIT_CHECKPOINT_OBJECT } from './seed.js'; import { amendmentBodyFromRow, amendmentRow, + chainKeyOf, checkpointBodyFromRow, checkpointDigest, signedBodyBytes, @@ -46,11 +47,12 @@ import type { SigningKeyTrust } from './verifier.js'; * - **The cutoff is aligned down to a UTC day.** A chain then gains at most * one expiry amendment a day in step with the clock, where an hourly sweep * would sign one an hour, forever: amendments are never removed. It keeps - * rows at most one day past their policy, on top of D8's own bound. + * a row up to one day past its policy, on top of D8's own bound. * - **At most {@link AUDIT_EXPIRY_MAX_ROWS_PER_SWEEP} rows a sweep**, the - * Archiver's own bound (500 rows × 20 batches): the backlog drains across - * sweeps, and a run cut there continues in the next amendment, which starts - * at the sequence directly after it. + * Archiver's own bound (500 rows × 20 batches), across all of the object's + * chains: the backlog drains across sweeps, so a backlog keeps rows longer + * than the day above, and a run cut there continues in the next amendment, + * which starts at the sequence directly after it. */ type Row = Record; @@ -79,6 +81,40 @@ export interface AuditExpiryRequest { readonly policy: string; readonly policyValue: string; readonly cutoff: string; + /** Tenant-scoped windows: an organization's chain expires under its own (see {@link windowOf}). */ + readonly tenants?: ReadonlyArray<{ readonly tenantId: string; readonly policyValue: string; readonly cutoff: string }>; +} + +/** The window one chain expires under: its day-aligned cutoff and the policy value its amendment signs. */ +interface ChainWindow { + readonly cutoffMs: number; + readonly policyValue: string; +} + +const cutoffOf = (cutoff: string): number => { + const ms = auditExpiryCutoff(Date.parse(cutoff)); + if (!Number.isFinite(ms)) throw new Error(`the expiry cutoff '${cutoff}' is not an instant`); + return ms; +}; + +/** + * The window chain `key` expires under. An organization's chain (`org:`) + * takes its organization's tenant-scoped window where one is set, else the + * global one. Any other chain — the deployment chain, of no one organization — + * takes the longest of the global window and every tenant window, so no chain + * expires under a window shorter than one configured for its rows. + */ +export function windowOf(request: AuditExpiryRequest, key: string): ChainWindow { + const global: ChainWindow = { cutoffMs: cutoffOf(request.cutoff), policyValue: request.policyValue }; + const tenants = request.tenants ?? []; + if (tenants.length === 0) return global; + const windowOfTenant = (t: (typeof tenants)[number]): ChainWindow => ({ cutoffMs: cutoffOf(t.cutoff), policyValue: t.policyValue }); + if (key.startsWith('org:')) { + const own = tenants.find((t) => chainKeyOf(t.tenantId) === key); + return own ? windowOfTenant(own) : global; + } + // The longest window is the earliest cutoff. + return tenants.map(windowOfTenant).reduce((longest, t) => (t.cutoffMs < longest.cutoffMs ? t : longest), global); } /** One chain's planned expiry (`LifecycleSealedExpiryRun`, `@objectstack/objectql`). */ @@ -132,8 +168,9 @@ export class ObjectExpiry { /** The runs of this sweep, each chain's amendment stored before it is answered. */ async plan(request: AuditExpiryRequest): Promise { - const cutoffMs = auditExpiryCutoff(Date.parse(request.cutoff)); - if (!Number.isFinite(cutoffMs)) throw new Error(`the expiry cutoff '${request.cutoff}' is not an instant`); + // A chain is found by a checkpoint that ended by the LATEST cutoff any chain may use; its own window decides. + let cutoffMs = cutoffOf(request.cutoff); + for (const t of request.tenants ?? []) cutoffMs = Math.max(cutoffMs, cutoffOf(t.cutoff)); const runs: AuditExpiryRun[] = []; let budget = AUDIT_EXPIRY_MAX_ROWS_PER_SWEEP; // Chains in `chain_key` order, each found by one checkpoint of an expired window: a keyset walk, one row a step. @@ -152,7 +189,7 @@ export class ObjectExpiry { if (!candidate) break; const key = String(candidate.chain_key); after = key; - const run = await this.chainRun(key, cutoffMs, budget, request); + const run = await this.chainRun(key, windowOf(request, key), budget, request); if (!run) continue; runs.push(run.run); budget -= run.run.rowIds.length; @@ -206,10 +243,11 @@ export class ObjectExpiry { private async chainRun( key: string, - cutoffMs: number, + window: ChainWindow, budget: number, request: AuditExpiryRequest, ): Promise<{ run: AuditExpiryRun; cut: boolean } | null> { + const { cutoffMs } = window; const [firstRow] = await this.find(this.checkpoints, AUDIT_CHECKPOINT_OBJECT, { where: { sealed_object: this.object, chain_key: key }, orderBy: [{ field: 'sequence', order: 'asc' }], @@ -220,17 +258,33 @@ export class ObjectExpiry { if (!first) return null; const latest = await this.latestExpiry(key); - // A sweep that stopped after the amendment was stored: its range is finished first. + // A sweep that stopped after the amendment was stored: its range is finished first. Each checkpoint left in + // it is admitted as in a fresh run, and they must run consecutively to the amendment's last sequence, whose + // digest it carries: a row that is not the platform's own deletes nothing, and neither does its range. if (latest && latest.last_sequence >= first.sequence) { + if (first.sequence < latest.first_sequence) return this.refuseResume(key, latest, first.sequence); const taken: Taken[] = []; + let next = first.sequence; for (const stored of await this.find(this.checkpoints, AUDIT_CHECKPOINT_OBJECT, { where: { sealed_object: this.object, chain_key: key, sequence: { $lte: latest.last_sequence } }, + // Ascending, so complete() removes the newest checkpoint last (see runOf). + orderBy: [{ field: 'sequence', order: 'asc' }], })) { const body = this.parse(key, stored); if (!body) return null; + const admitted = + body.sequence === next && + (await this.options.trust.signature(body.signing_key_id, signedBodyBytes(body), stored.signature)) === 'ok'; + if (!admitted) return this.refuseResume(key, latest, body.sequence); taken.push({ stored, body }); + next += 1; + } + if (taken.length === 0) return null; + const last = taken[taken.length - 1].body; + if (last.sequence !== latest.last_sequence || checkpointDigest(last) !== latest.last_removed_digest) { + return this.refuseResume(key, latest, last.sequence); } - return taken.length === 0 ? null : { run: this.runOf(key, taken), cut: false }; + return { run: this.runOf(key, taken), cut: false }; } const expected = latest ? latest.last_sequence + 1 : 0; @@ -279,12 +333,24 @@ export class ObjectExpiry { if (page.length < PAGE_SIZE) break; } if (taken.length === 0) return null; - await this.writeExpiry(taken, request); + await this.writeExpiry(taken, request.policy, window.policyValue); return { run: this.runOf(key, taken), cut }; } + /** A stored expiry's unfinished range holds a checkpoint that is not admitted: it is not resumed, and that is said once. */ + private refuseResume(key: string, latest: ExpiryAmendmentBody, sequence: number): null { + this.options.say( + `expiry:resume:${this.object}:${key}`, + `AuditSealer: '${this.object}' chain '${key}' is NOT expired further: the range its expiry ` + + `${latest.first_sequence}–${latest.last_sequence} still holds, at checkpoint ${sequence}, one that does not ` + + 'verify under a trusted signing key or does not follow the one before it. Nothing in that range is deleted; ' + + 'os audit verify reports the checkpoint.', + ); + return null; + } + /** Sign and store the chain's `expiry` amendment over `taken` (D8), then hand it to the sink. */ - private async writeExpiry(taken: readonly Taken[], request: AuditExpiryRequest): Promise { + private async writeExpiry(taken: readonly Taken[], policy: string, policyValue: string): Promise { const first = taken[0].body; const last = taken[taken.length - 1].body; let from = first.window_start; @@ -305,8 +371,8 @@ export class ObjectExpiry { covered_from: from, covered_to: to, last_removed_digest: checkpointDigest(last), - policy: request.policy, - policy_value: request.policyValue, + policy, + policy_value: policyValue, }); const { signer } = this.options; // The S1 loop: a signature whose key id differs from the one its bytes name is never stored. diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index fe7ae86de12..cd65bdb8abd 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -538,15 +538,22 @@ export class AuditSealer { * (`expiry.ts`), the LifecycleService's `LifecycleSealedExpiry`. It holds the * pass's locks while it plans and signs — `audit.sealer` and the audit seal * lock on the object's database — so two replicas' sweeps never sign two - * expiries over one range, and a sealer pass never reads a chain head the - * expiry is moving. While another holds either, it answers no run: the rows - * wait for the next sweep. With no crypto provider or no signer it throws, + * expiries over one range. The run's `complete()` runs later, after the + * sweep deleted its rows and with these locks released: what keeps a + * concurrent pass's chain head right then is that a run removes its + * checkpoints oldest first, so the newest goes last, and once it is gone + * the head falls back to the stored expiry, which names the same sequence + * and digest (`headOf`). While another holds either lock, it answers no run: + * the rows wait for the next sweep. With no crypto provider or no signer it throws, * and the sweep keeps every row. */ async expire(request: AuditExpiryRequest): Promise { const plan = this.plans().find((p) => p.name === request.object); if (!plan) return []; - const memo = `${auditExpiryCutoff(Date.parse(request.cutoff))}|${request.policy}|${request.policyValue}`; + const memo = [ + `${auditExpiryCutoff(Date.parse(request.cutoff))}|${request.policy}|${request.policyValue}`, + ...(request.tenants ?? []).map((t) => `${t.tenantId}=${auditExpiryCutoff(Date.parse(t.cutoff))}|${t.policyValue}`).sort(), + ].join(';'); if (this.drainedAt.get(plan.name) === memo) return []; const seams = await this.resolveSeams(); if (!seams) throw new Error('a host seam the sealer needs is registered but could not be resolved (reported at error)'); @@ -612,6 +619,9 @@ export class AuditSealer { } /** One pass over one sealed object. */ +/** Stored expiry amendments one head or floor read walks, newest first, for the newest admitted one. */ +const LAST_EXPIRY_SCAN = 10; + class ObjectPass { private readonly heads = new Map(); private readonly hot: SealStorageDriver; @@ -632,6 +642,8 @@ class ObjectPass { written = 0; /** The key id the last checkpoint of this pass was signed under: the next body's expectation. */ private keyId: string | null = null; + /** D6 trust, built on first use (see {@link ObjectPass.trust}). */ + private trusted: SigningKeyTrust | null = null; constructor( private readonly options: AuditSealerOptions, @@ -932,9 +944,12 @@ class ObjectPass { /** * D8: the stored `expiry` amendment of this object (narrowed by `where`) that - * is highest by `field`, or `undefined`. A malformed one is a chain-local - * fault of its chain (S4). It is read only where no checkpoint answers: a - * chain's head, and the floor of an object whose every checkpoint expired. + * is highest by `field` among those admitted — whose signature verifies under + * a trusted key (D6) — or `undefined`. A row that is not admitted is passed + * over, so a head or a floor never follows one. A malformed one is a + * chain-local fault of its chain (S4). It is read only where no checkpoint + * answers: a chain's head, and the floor of an object whose every checkpoint + * expired. */ private async lastExpiry(where: Row, field: 'last_sequence' | 'covered_to'): Promise { const driver = this.options.engine.getDriverForObject(AUDIT_AMENDMENT_OBJECT); @@ -944,19 +959,33 @@ class ObjectPass { rows = await driver.find(AUDIT_AMENDMENT_OBJECT, { where: { sealed_object: this.plan.name, kind: 'expiry', ...where }, orderBy: [{ field, order: 'desc' }], - limit: 1, + limit: LAST_EXPIRY_SCAN, }); } catch (err) { if (isMissingTableError(err, AUDIT_AMENDMENT_OBJECT)) return undefined; throw err; } - if (!rows[0]) return undefined; - try { - const body = amendmentBodyFromRow(rows[0]); - return body.kind === 'expiry' ? body : undefined; - } catch (err) { - throw new ChainFault(String(rows[0].chain_key), err); + for (const row of rows) { + let body; + try { + body = amendmentBodyFromRow(row); + } catch (err) { + throw new ChainFault(String(row.chain_key), err); + } + if (body.kind !== 'expiry') continue; + if ((await this.trust().signature(body.signing_key_id, signedBodyBytes(body), row.signature)) === 'ok') return body; + } + return undefined; + } + + /** D6: the keys this deployment trusts, as the expiry and the verifier admit them. */ + private trust(): SigningKeyTrust { + if (!this.trusted) { + const { crypto } = this.options; + if (!crypto) throw new Error('no crypto provider, so no expiry amendment can be admitted'); + this.trusted = new SigningKeyTrust(anchoredPublicKeyOf(this.options.engine, crypto, this.signer)); } + return this.trusted; } private async writeChains(chains: Map, start: number, kind: AuditCheckpointKind, watermark: number): Promise { diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 5df6951a0a5..4f5dbbd2bf8 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1176,8 +1176,10 @@ export const LifecycleSchema = lazySchema(() => strictObject({ "the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` " + "`onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their " + '`retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry ' + - 'amendment names them, so the verifier reads them as expired rather than missing; while no sealer is ' + - 'running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error.', + 'amendment names them, so the verifier reads them as expired rather than missing; a tenant-scoped ' + + "retention window applies to that organization's chain, and the window is counted to the start of a UTC " + + 'day, so a row can stay up to a day longer. While no sealer is running, the sweeper keeps them. A ' + + 'deployment with no crypto provider seals nothing and reports that at error.', ), reclaim: z.boolean().optional().describe('Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes.'), }).superRefine((lc, ctx) => { From 48e81f3c55be457dd9f1ea213775c5c75e674f4e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:19:36 +0000 Subject: [PATCH 10/16] fix(plugin-audit): address review 7202871622 on the sealed expiry - M3: the expiry writer and the sealer's chain head check that each checkpoint and stored expiry amendment they use belongs to the chain and links in order, and page through stored amendments; the verifier adds two matching checks. New audit-seal-expiry-admission.test.ts plus two verifier tests, one per check. - S4: a chain expires under the longest tenant window among the owners of its rows (by the column the windows are set on, hot store then archive); `tenantColumn` travels on the request. - S5: the `os audit verify` exit 2 change is in the narrowed list and the BREAKING banner. - Rename the seam types to LifecycleExpiryPrefix, LifecycleExpiryPrefixRequest, LifecycleExpiryPrefixRun. - n4, n5, n7. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt --- .changeset/31908-p4c-sealed-expiry.md | 7 +- content/docs/data-modeling/objects.mdx | 12 +- content/docs/references/data/object.mdx | 4 +- packages/objectql/src/index.ts | 6 +- .../lifecycle-service.sealed-expiry.test.ts | 14 +- .../src/lifecycle/lifecycle-service.ts | 67 +++-- .../audit-seal-expiry-admission.test.ts | 255 ++++++++++++++++++ .../audit-seal-expiry-window.test.ts | 109 +++++++- .../audit-seal/audit-seal-verifier.test.ts | 23 +- .../plugin-audit/src/audit-seal/expiry.ts | 210 +++++++++++---- .../src/audit-seal/seal-store.testkit.ts | 3 +- .../plugin-audit/src/audit-seal/sealer.ts | 71 +++-- .../plugin-audit/src/audit-seal/verifier.ts | 17 +- packages/spec/src/data/object.zod.ts | 11 +- 14 files changed, 677 insertions(+), 132 deletions(-) create mode 100644 packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-admission.test.ts diff --git a/.changeset/31908-p4c-sealed-expiry.md b/.changeset/31908-p4c-sealed-expiry.md index 367fadf30a6..c33a4c7c8b8 100644 --- a/.changeset/31908-p4c-sealed-expiry.md +++ b/.changeset/31908-p4c-sealed-expiry.md @@ -7,7 +7,7 @@ feat(plugin-audit): the audit log is sealed by default, and sealed rows expire by whole checkpoints under a signed expiry amendment -Clause-②: yes (narrowing) — narrowed: because `sys_audit_log` now declares `lifecycle.seal` on every deployment, `os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies` with `--apply` refuse on SQLite or Turso without `--sealer-stopped`, and on Postgres or MySQL take the audit seal lock and refuse when a sealer pass still holds it after ten minutes, where 18.6.0 ran them unlocked on a deployment that sealed nothing; `os audit verify` exits 1 on a row in a window at or before the newest window a trusted `window` checkpoint names that no checkpoint holds (`late`, unsealed), where it read the window unsealed and exited 0; and `verifyAuditLedger` throws for `sys_audit_log` when the `archive` datasource it archives to is not connected and no `archive` is passed. This breaks the bound changeset `35c9a30` (#33675) set, "No object declares `lifecycle.seal` by default, so a deployment that did not opt in sees no change": this release is the one that opts every deployment in. Widened: `@objectstack/objectql` `LifecycleService.registerExpiryPrefix` and the types `LifecycleSealedExpiry`, `LifecycleSealedExpiryRequest` (with its `tenants` windows), `LifecycleSealedExpiryRun`; a sweep entry's `policy` gains `'expiry'` and `skipped[].reason` gains `seal-expiry-pending` and `seal-delete-unsupported`. +Clause-②: yes (narrowing) — narrowed: because `sys_audit_log` now declares `lifecycle.seal` on every deployment, `os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies` with `--apply` refuse on SQLite or Turso without `--sealer-stopped`, and on Postgres or MySQL take the audit seal lock and refuse when a sealer pass still holds it after ten minutes, where 18.6.0 ran them unlocked on a deployment that sealed nothing; `os audit verify` exits 1 on a row in a window at or before the newest window a trusted `window` checkpoint names that no checkpoint holds (`late`, unsealed), where it read the window unsealed and exited 0; `os audit verify` refuses with `archive_not_connected` and exits 2 wherever the `archive` datasource is declared and not connected on its own boot, where 18.6.0 printed that nothing is sealed and exited 0; and `verifyAuditLedger` throws for `sys_audit_log` when the `archive` datasource it archives to is not connected and no `archive` is passed. This breaks the bound changeset `35c9a30` (#33675) set, "No object declares `lifecycle.seal` by default, so a deployment that did not opt in sees no change": this release is the one that opts every deployment in. Widened: `@objectstack/objectql` `LifecycleService.registerExpiryPrefix` and the types `LifecycleExpiryPrefix`, `LifecycleExpiryPrefixRequest` (with its `tenants` windows and `tenantColumn`), `LifecycleExpiryPrefixRun`; a sweep entry's `policy` gains `'expiry'` and `skipped[].reason` gains `seal-expiry-pending` and `seal-delete-unsupported`. Metadata-protocol: semantic — on an object that declares `lifecycle.seal`, the authored `retention.maxAge`, `ttl.expireAfter` and `archive.keep` no longer delete a row at its row cutoff: rows leave by whole checkpoints under a signed expiry amendment, counted to the start of a UTC day, at most 10,000 a sweep, and not at all while no sealer runs Skills-docs: follow-up owed — this claim's second PR (amendment 7193137455) rewrites `skills/objectstack-data/rules/lifecycle.md`, which still says the sweeper deletes sealed rows @@ -18,6 +18,7 @@ Skills-docs: follow-up owed — this claim's second PR (amendment 7193137455) re - **`os migrate audit-* --apply` on SQLite or Turso** stops before writing and names the flag. Fix: stop every server that seals the database, then run it again with `--sealer-stopped`. - **The same run on Postgres or MySQL** waits up to ten minutes for a sealer pass in flight, then refuses having changed nothing. Fix: run it again once that pass has finished. - **`os audit verify` exits 1** on a row it reads `late` and unsealed in a window another chain of the object already sealed. Fix: none is owed by the command; read the rows the report names (a chain a fault left behind), and run it again after the sealer's next pass. +- **`os audit verify` exits 2** (`archive_not_connected`) where the `archive` datasource is declared and the command's boot does not connect it. Fix: declare the datasource with `autoConnect: true`, or make it reachable from where the command runs. - **`verifyAuditLedger`** (`@objectstack/plugin-audit`) throws for `sys_audit_log` when its `archive` datasource is not connected. Fix: pass `archive`, for example `archive: () => 'none'` where the deployment has no archive datasource. Every dry run is unchanged. A deployment's own objects that do not declare `lifecycle.seal` keep the row-cutoff retention they had. @@ -27,8 +28,8 @@ ADR-0154 D8 and D10 (#31908, slice P4c, the last one). - **`sys_audit_log` is sealed.** Its lifecycle declares `seal: { valueFields: ['old_value', 'new_value', 'metadata'] }`, so every deployment whose `AuditPlugin` has a crypto provider (`os serve` hands it one) signs each hour's audit rows into a per-organization checkpoint, and `os audit verify` checks them. The three value columns enter each checkpoint as salted commitments; every other column enters in clear. - **Sealed rows leave only by whole checkpoints.** The LifecycleService no longer deletes a row of an object that declares `lifecycle.seal` by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerExpiryPrefix`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). - **`os migrate audit-* --apply` on SQLite or Turso now needs `--sealer-stopped` for the audit log.** The rule 18.6.0 set for a sealed object now holds on every deployment, since `sys_audit_log` is one: stop every server that seals the database, then run with the flag. That includes the `os migrate audit-side-copies --apply` an upgrade from 18.4.0 or earlier runs. Postgres and MySQL take the audit seal lock, and a dry run is unchanged. -- **No sealer, no deletion.** While no sealed expiry is registered (an `AuditPlugin` with no crypto provider, a one-shot boot), a sealed object's rows past their policy are kept, the archive copy still runs, the sweep reports `seal-expiry-pending`, and the lifecycle service says so once at `warn`; such a host keeps `sys_audit_log` past `archive.keep`, and its sealer reports the missing provider hourly at `error`. An archive store with no `bulkDelete` is never planned (`seal-delete-unsupported`), so no amendment is signed over rows it could not delete. A chain whose first remaining checkpoint does not follow its last expiry (a checkpoint removed outside the platform), or whose next checkpoint does not verify under a trusted key, is not expired past that point, and the sealer says so. A stopped expiry is resumed only over checkpoints that each verify under a trusted key and run on to the amendment's last sequence and digest; otherwise nothing in its range is deleted. An expiry deletes rows for good: a deleted row cannot be restored from the ledger. -- **A tenant-scoped retention override applies to its organization's chain.** The lifecycle service hands each tenant's window, through the same floors, to the sealed expiry (`LifecycleSealedExpiryRequest.tenants`); an organization's chain expires under its own window and its amendment signs that value, and the chain of rows about no organization expires under the longest window configured, so no chain expires under a window shorter than one set for its rows. +- **No sealer, no deletion.** While no sealed expiry is registered (an `AuditPlugin` with no crypto provider, a one-shot boot), a sealed object's rows past their policy are kept, the archive copy still runs, the sweep reports `seal-expiry-pending`, and the lifecycle service says so once at `warn`; such a host keeps `sys_audit_log` past `archive.keep`, and its sealer reports the missing provider hourly at `error`. An archive store with no `bulkDelete` is never planned (`seal-delete-unsupported`), so no amendment is signed over rows it could not delete. A chain whose first remaining checkpoint does not follow its last expiry (a checkpoint removed outside the platform), or whose next checkpoint does not verify under a trusted key, is not expired past that point, and the sealer says so. An expiry acts only on the chain's own checkpoints and amendments, linked in order; a stopped expiry is resumed only over checkpoints that also each verify under a trusted key and run on to the amendment's last sequence and digest; otherwise nothing in its range is deleted, and the sealer says so. The verifier holds an expiry it honours to the same. An expiry deletes rows for good: a deleted row cannot be restored from the ledger. +- **A tenant-scoped retention override applies to the rows its organization owns.** The lifecycle service hands each tenant's window, through the same floors, to the sealed expiry (`LifecycleExpiryPrefixRequest.tenants`), with the column the windows are set on (`LifecycleExpiryPrefixRequest.tenantColumn`), which need not be the chain column. A chain expires under the longest window among the organizations that own its rows by that column (read from the hot store, then the archive), the chain of rows about no organization under the longest window configured, and its amendment signs that value, so no row expires under a window shorter than the one set for it. - **A fully expired chain continues.** Its next checkpoint chains onto the expiry: sequence after the expiry's last, linked to its `last_removed_digest`. - **`os audit verify` stays loud for a chain a fault left behind** (seat ruling 6885452378, ADR-0154 D3 as amended): a window that starts at or before the newest window a trusted `window` checkpoint names is sealed, so a row there that no checkpoint holds reads `late` and unsealed, and the check fails. - **The verify harness hands its crypto provider to `AuditPlugin`.** `bootStack` gives an `AuditPlugin` it mounts (an `extraPlugins` entry, a stack `plugins` entry, or the provider `requires: ['audit']` constructs) the same `harnessCryptoProvider()` instance that settings and the engine get, never a bare `LocalCryptoProvider`; an instance composed with its own provider keeps it. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index d42219befdc..38edb5f6421 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -283,11 +283,13 @@ it is sealed on every deployment whose `AuditPlugin` has a crypto provider. missing. The window is counted to the start of a UTC day, so a row can stay up to a day past it, and at most 10,000 such rows leave per object per sweep, so a backlog drains over several sweeps; once it has, a chain gains at most - one expiry amendment a day. A tenant-scoped retention window applies to that - organization's chain, and the chain of rows about no organization expires - under the longest window configured, so no row leaves before the window set - for it. While no sealer is running (no crypto provider), the sweeper keeps - them and says so once. + one expiry amendment a day. A tenant-scoped retention window is matched to + each row by the column it is set on (`organization_id`), which need not be + the chain column (`tenant_id`, or `seal.chainField`): a chain expires under + the longest window among the organizations whose rows it holds, and the + chain of rows about no organization under the longest window configured, so + no row leaves before the window set for it. While no sealer is running (no + crypto provider), the sweeper keeps them and says so once. - Sealing needs a crypto provider, which the host passes to `AuditPlugin` as `cryptoProvider`. `os serve` passes the one it seals every secret with; an app that puts its own `AuditPlugin` in `plugins` passes one itself. Without diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index ab9cb407aa8..8178f180876 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -82,7 +82,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing; a tenant-scoped retention window applies to that organization's chain, and the window is counted to the start of a UTC day, so a row can stay up to a day longer. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped retention window is matched to each row by the column it is set on: a chain expires under the longest window among the organizations whose rows it holds, and the chain of rows about no organization under the longest window set, so no row leaves before its own window. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Lifecycle.retention` @@ -384,7 +384,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing; a tenant-scoped retention window applies to that organization's chain, and the window is counted to the start of a UTC day, so a row can stay up to a day longer. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped retention window is matched to each row by the column it is set on: a chain expires under the longest window among the organizations whose rows it holds, and the chain of rows about no organization under the longest window set, so no row leaves before its own window. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Object.activityMilestones[number]` diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index ff3621c42db..dfbf0b7d7b3 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -802,9 +802,9 @@ export type { LifecycleGovernanceAlert, LifecycleReapGuard, // [ADR-0154 D8] The sealed-object expiry seam beside the reap guard. - LifecycleSealedExpiry, - LifecycleSealedExpiryRequest, - LifecycleSealedExpiryRun, + LifecycleExpiryPrefix, + LifecycleExpiryPrefixRequest, + LifecycleExpiryPrefixRun, // [#5195] Consumer-declared floors on settings-driven window overrides. LifecycleRetentionFloor, LifecycleFloorViolation, diff --git a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts index cf79ec7b34d..9e50e76e048 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts @@ -4,9 +4,9 @@ import { describe, it, expect, vi } from 'vitest'; import { LifecycleService, type LifecycleObjectLike, - type LifecycleSealedExpiry, - type LifecycleSealedExpiryRequest, - type LifecycleSealedExpiryRun, + type LifecycleExpiryPrefix, + type LifecycleExpiryPrefixRequest, + type LifecycleExpiryPrefixRun, } from './lifecycle-service.js'; import { assertEngineDeleteDispatch } from '@objectstack/metadata-core'; import { parseLifecycleDuration } from './duration.js'; @@ -98,9 +98,9 @@ function service(engine: any, logger = recordingLogger().logger) { function expiryOf(runs: Array<{ chain: string; rowIds: string[] }>) { const completed: string[] = []; - const requests: LifecycleSealedExpiryRequest[] = []; - const expiry: LifecycleSealedExpiry = { - plan: vi.fn(async (request: LifecycleSealedExpiryRequest): Promise => { + const requests: LifecycleExpiryPrefixRequest[] = []; + const expiry: LifecycleExpiryPrefix = { + plan: vi.fn(async (request: LifecycleExpiryPrefixRequest): Promise => { requests.push(request); return runs.map((r) => ({ ...r, complete: async () => void completed.push(r.chain) })); }), @@ -249,6 +249,8 @@ describe('LifecycleService — a sealed object expires only through the sealed e { tenantId: 'org_long', policyValue: '400d', cutoff: isoCutoff('400d') }, { tenantId: 'org_short', policyValue: '10d', cutoff: isoCutoff('10d') }, ]); + // The column the windows are configured on travels with them: the expiry matches a chain to one only there. + expect(requests[0].tenantColumn).toBe('organization_id'); expect(warns.join('\n')).not.toMatch(/do not apply/); }); diff --git a/packages/objectql/src/lifecycle/lifecycle-service.ts b/packages/objectql/src/lifecycle/lifecycle-service.ts index f67c316a1a7..30983c40fc3 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.ts @@ -411,7 +411,7 @@ export interface LifecycleFloorViolation { export interface LifecycleSweepEntry { object: string; class: string; - /** `expiry`: [ADR-0154 D8] a sealed object's whole checkpoints, through {@link LifecycleSealedExpiry}. */ + /** `expiry`: [ADR-0154 D8] a sealed object's whole checkpoints, through {@link LifecycleExpiryPrefix}. */ policy: 'ttl' | 'retention' | 'rotation' | 'rotation-fallback' | 'archive' | 'expiry'; cutoff: string; /** `undefined` when the driver doesn't report a count. */ @@ -527,7 +527,7 @@ export type LifecycleReapGuard = ( * [ADR-0154 D8] What the sweep asks the sealed-object expiry for, once per * sweep and policy of an object that declares `lifecycle.seal`. */ -export interface LifecycleSealedExpiryRequest { +export interface LifecycleExpiryPrefixRequest { readonly object: string; /** The policy whose window expires the rows. */ readonly policy: 'archive.keep' | 'retention.maxAge' | 'ttl.expireAfter'; @@ -537,18 +537,30 @@ export interface LifecycleSealedExpiryRequest { readonly cutoff: string; /** * The tenant-scoped windows of this policy (`retention_overrides` at tenant - * scope), each through the same floors: an organization's chain expires - * under its own organization's window, in place of {@link policyValue} and - * {@link cutoff}. A chain of no one organization (the deployment chain) - * expires under the longest of all of them and the global one, so no chain - * ever expires under a window shorter than one configured for its rows. - * Absent when no tenant overrides the window. + * scope), each through the same floors, in place of {@link policyValue} + * and {@link cutoff} for the rows that organization owns by + * {@link tenantColumn}: a chain expires under the longest window among the + * owners of its rows (an owner with none of its own under the global one), + * and a chain of no one organization (the deployment chain) under the + * longest of all of them and the global one, so no chain ever expires under + * a window shorter than one configured for a row in it. Absent when no + * tenant overrides the window. */ readonly tenants?: ReadonlyArray<{ readonly tenantId: string; readonly policyValue: string; readonly cutoff: string }>; + /** + * The column {@link tenants} are configured on — the partition `reap()` + * uses (`organization_id`, or an attribution column), which need not be + * the object's chain column. Each row is matched to a window by this + * column: a chain expires under the longest window among the owners of the + * rows it holds, the chain of rows about no organization under the longest + * window of all, so no chain is shorter than a window set for a row in it. + * Present exactly when `tenants` is. + */ + readonly tenantColumn?: string; } /** One chain's expiry, planned and signed: the rows the sweep deletes, then {@link complete}. */ -export interface LifecycleSealedExpiryRun { +export interface LifecycleExpiryPrefixRun { /** The chain, for the report. */ readonly chain: string; /** Exactly the rows the removed checkpoints list. The sweep deletes these and no other. */ @@ -564,12 +576,12 @@ export interface LifecycleSealedExpiryRun { * read as `missing`. The sealer's owner (`@objectstack/plugin-audit`) answers * which whole checkpoints of each chain have expired and writes the signed * `expiry` amendment for them before it answers; the sweep then deletes - * exactly the rows they list and only then calls {@link LifecycleSealedExpiryRun.complete}. + * exactly the rows they list and only then calls {@link LifecycleExpiryPrefixRun.complete}. * A plan that throws keeps every row for the next sweep, as a vetoing reap * guard does. */ -export interface LifecycleSealedExpiry { - plan(request: LifecycleSealedExpiryRequest): Promise; +export interface LifecycleExpiryPrefix { + plan(request: LifecycleExpiryPrefixRequest): Promise; } export class LifecycleService { @@ -595,7 +607,7 @@ export class LifecycleService { */ private readonly reapGuards = new Map(); /** [ADR-0154 D8] The one sealed-object expiry, when the sealer's owner registered it. */ - private sealedExpiry: LifecycleSealedExpiry | undefined; + private sealedExpiry: LifecycleExpiryPrefix | undefined; /** [ADR-0154 D8] Sealed objects already said about, by cause, so a standing state is said once. */ private readonly sealedSaid = new Set(); /** @@ -920,7 +932,7 @@ export class LifecycleService { * Until one is registered, a sealed object's expiring rows are KEPT: the * sweep never deletes a sealed row by its own cutoff (see {@link sweepSealed}). */ - registerExpiryPrefix(expiry: LifecycleSealedExpiry): () => void { + registerExpiryPrefix(expiry: LifecycleExpiryPrefix): () => void { if (!expiry || typeof expiry.plan !== 'function') { throw new Error('[lifecycle] registerExpiryPrefix requires an object with a plan(request) method'); } @@ -1673,10 +1685,11 @@ export class LifecycleService { * * A settings override of the window applies as on any object, through the * same floors, and the value applied is the one the amendment signs. A - * tenant-scoped override applies to its organization's chain, on the - * partition {@link tenantWindowsFor} decides for every reap: it travels as - * {@link LifecycleSealedExpiryRequest.tenants}, and each chain's amendment - * signs the window it expired under. + * tenant-scoped override travels as {@link LifecycleExpiryPrefixRequest.tenants}, + * with the column {@link tenantWindowsFor} partitions on: a chain expires + * under the longest window among the owners, by that column, of the rows it + * holds (the chain of rows about no organization under the longest of all), + * and each chain's amendment signs the window it expired under. */ private async reapSealed( engine: LifecycleEngineLike, @@ -1687,7 +1700,7 @@ export class LifecycleService { const object = obj.name; const ov = this.governance.overrides[object] ?? {}; const legs: Array<{ - policy: LifecycleSealedExpiryRequest['policy']; + policy: LifecycleExpiryPrefixRequest['policy']; kind: 'ttl' | 'retention'; key: 'expireAfter' | 'maxAge'; declared: string; @@ -1715,7 +1728,12 @@ export class LifecycleService { engine, obj, lc, - { policy: leg.policy, policyValue, cutoffMs: this.now() - windowMs, ...(tenants.length > 0 ? { tenants } : {}) }, + { + policy: leg.policy, + policyValue, + cutoffMs: this.now() - windowMs, + ...(partition && tenants.length > 0 ? { tenants, tenantColumn: partition.column } : {}), + }, report, null, ), @@ -1726,7 +1744,7 @@ export class LifecycleService { /** * [ADR-0154 D8] One policy's expiry of a sealed object. The registered - * {@link LifecycleSealedExpiry} plans it and signs each chain's `expiry` + * {@link LifecycleExpiryPrefix} plans it and signs each chain's `expiry` * amendment first; then exactly the rows each run lists are deleted — from * `stores` (the hot store and the archive, by id) when the object archives, * else through the engine like any reap, its guards asked — and only then @@ -1741,10 +1759,11 @@ export class LifecycleService { obj: LifecycleObjectLike, lc: Lifecycle, leg: { - policy: LifecycleSealedExpiryRequest['policy']; + policy: LifecycleExpiryPrefixRequest['policy']; policyValue: string; cutoffMs: number; - tenants?: LifecycleSealedExpiryRequest['tenants']; + tenants?: LifecycleExpiryPrefixRequest['tenants']; + tenantColumn?: string; }, report: LifecycleSweepReport, stores: readonly ArchiveCapableDriver[] | null, @@ -1780,7 +1799,7 @@ export class LifecycleService { policy: leg.policy, policyValue: leg.policyValue, cutoff, - ...(leg.tenants ? { tenants: leg.tenants } : {}), + ...(leg.tenants ? { tenants: leg.tenants, tenantColumn: leg.tenantColumn } : {}), }); let deleted = 0; for (const run of runs) { diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-admission.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-admission.test.ts new file mode 100644 index 00000000000..03c45b75093 --- /dev/null +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-admission.test.ts @@ -0,0 +1,255 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { AuditSealer } from './sealer.js'; +import { bindingCrypto, memoryEngine, recordingLogger } from './seal-store.testkit.js'; +import { + amendmentRow, + checkpointBodyFromRow, + checkpointDigest, + signedBodyBytes, + type ExpiryAmendmentBody, +} from './signed-body.js'; +import { LocalCheckpointSigner } from './signer.js'; +import type { AuditExpiryRun } from './expiry.js'; + +/** + * ADR-0154 D8 — what an expiry admits before it signs or deletes anything, + * one check per test, over an in-memory engine double: each checkpoint it + * takes and each stored expiry it follows is bound to the chain it is stored + * under (its signed object and organization, not its unsigned columns), each + * links to the one before it, and the stored amendments are read until an + * admitted one answers. The sealer's chain head is read under the same rule. + * + * Every test here goes red when its one check is taken out alone. Fixtures + * that need a body no sweep would write are signed here with the test's own + * platform key: what is pinned is the check, not how such a row came to be. + */ + +type Row = Record; + +const H = 60 * 60 * 1000; +const DAY = 24 * H; +const DAY0 = Date.UTC(2026, 10, 10); +const at = (h: number, m: number) => new Date(DAY0 + h * H + m * 60_000).toISOString(); +const iso = (ms: number) => new Date(ms).toISOString(); +const NO_SIGNATURE = Buffer.alloc(64).toString('base64'); + +const LEDGER = { + name: 'ledger_probe', + fields: { id: { type: 'text' }, created_at: { type: 'datetime' }, action: { type: 'text' }, tenant_id: { type: 'lookup' }, payload: { type: 'textarea' } }, + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, archive: { after: '90d', to: 'archive' }, seal: { valueFields: ['payload'] } }, +}; +const AMENDMENTS = { name: 'sys_audit_amendment', fields: {} }; + +const row = (id: string, created: string, tenant: string) => ({ id, created_at: created, action: 'update', tenant_id: tenant, payload: `{"v":"${id}"}` }); + +/** org_a sealed in windows 08, 09 and 10 (sequences 0–2), org_b in 08 and 09 (0–1), at 12:30. */ +async function sealedLedger() { + const store = memoryEngine([LEDGER, AMENDMENTS] as never); + const crypto = bindingCrypto(); + const signer = new LocalCheckpointSigner({ engine: store.engine, crypto }); + const clock = { now: DAY0 + 12 * H + 30 * 60_000 }; + const logger = recordingLogger(); + const sealer = new AuditSealer({ engine: store.engine, crypto, signer: () => signer, logger, now: () => clock.now }); + const ledger = store.hot.table('ledger_probe'); + ledger.push( + row('a0', at(8, 10), 'org_a'), row('a1', at(9, 10), 'org_a'), row('a2', at(10, 10), 'org_a'), + row('b0', at(8, 20), 'org_b'), row('b1', at(9, 20), 'org_b'), + ); + await sealer.runPass(); + const keyId = (await signer.activeKeyId())!; + const checkpoints = () => store.hot.table('sys_audit_checkpoint'); + const checkpoint = (chain: string, sequence: number) => checkpoints().find((r) => r.chain_key === chain && r.sequence === sequence)!; + const bodyOf = (chain: string, sequence: number) => checkpointBodyFromRow(checkpoint(chain, sequence)); + const digestOf = (chain: string, sequence: number) => checkpointDigest(bodyOf(chain, sequence)); + const amendments = () => store.hot.table('sys_audit_amendment'); + /** Replace a stored checkpoint row. */ + const put = (chain: string, sequence: number, next: Row) => { + const list = checkpoints(); + list.splice(list.indexOf(checkpoint(chain, sequence)), 1, next); + }; + /** Remove a chain's checkpoint and the rows it lists, as a finished expiry leaves it. */ + const removeExpired = (chain: string, sequence: number) => { + const body = bodyOf(chain, sequence); + for (const id of body.row_ids) ledger.splice(ledger.findIndex((r) => r.id === id), 1); + checkpoints().splice(checkpoints().indexOf(checkpoint(chain, sequence)), 1); + }; + /** A stored checkpoint with `change` applied to its signed body, signed again under the platform key. */ + const resigned = async (stored: Row, change: Row): Promise => { + const body = checkpointBodyFromRow({ ...stored, ...change }); + const { signature } = await signer.sign(signedBodyBytes(body)); + return { ...stored, ...change, signature }; + }; + /** An expiry amendment row of org_a's chain, signed under the platform key unless `signature` is given. */ + const expiryRow = async ( + fields: { first: number; last: number; digest: string; tenant?: string; from?: string; to?: string }, + stored: { id?: string; signature?: string; chainKey?: string } = {}, + ): Promise => { + const body: ExpiryAmendmentBody = { + kind: 'expiry', + sealed_object: 'ledger_probe', + tenant_id: fields.tenant ?? 'org_a', + amended_at: iso(clock.now), + signing_key_id: keyId, + first_sequence: fields.first, + last_sequence: fields.last, + covered_from: fields.from ?? at(8, 0), + covered_to: fields.to ?? at(9, 0), + last_removed_digest: fields.digest, + policy: 'archive.keep', + policy_value: '7d', + }; + const signature = stored.signature ?? (await signer.sign(signedBodyBytes(body))).signature; + const out = amendmentRow(body, { id: stored.id ?? `am_${amendments().length}`, signature }); + return stored.chainKey ? { ...out, chain_key: stored.chainKey } : out; + }; + const amend = async (...args: Parameters) => { + const stored = await expiryRow(...args); + amendments().push(stored); + return stored; + }; + /** One sweep's expiry, 30 days on, under `archive.keep: 7d`. */ + const expireNow = async (): Promise => { + clock.now = DAY0 + 30 * DAY; + return sealer.expire({ object: 'ledger_probe', policy: 'archive.keep', policyValue: '7d', cutoff: iso(clock.now - 7 * DAY) }); + }; + const warned = (pattern: RegExp) => logger.lines.filter((l) => l.level === 'warn' && pattern.test(l.message)).length; + return { store, signer, sealer, clock, ledger, checkpoints, checkpoint, bodyOf, digestOf, amendments, put, removeExpired, resigned, amend, expiryRow, expireNow, warned }; +} + +const chainsOf = (runs: readonly AuditExpiryRun[]) => runs.map((r) => r.chain).sort(); +const rowsOf = (runs: readonly AuditExpiryRun[], chain: string) => runs.find((r) => r.chain === chain)?.rowIds; + +describe('a fresh expiry takes only checkpoints bound to the chain, each linked to the one before (ADR-0154 D8)', () => { + it('a checkpoint stored under a chain it is not signed for expires nothing there', async () => { + const s = await sealedLedger(); + s.checkpoints().push({ ...s.checkpoint('org:org_b', 0), id: 'misfiled', chain_key: 'org:aaa' }); + const runs = await s.expireNow(); + expect(chainsOf(runs)).toEqual(['org:org_a', 'org:org_b']); + expect(s.warned(/chain 'org:aaa' is NOT expired: the checkpoint 0 stored under it is signed for another object or organization/)).toBe(1); + }); + + it('a chain whose checkpoints do not link one to the next is not expired at all', async () => { + const s = await sealedLedger(); + s.put('org:org_a', 1, await s.resigned(s.checkpoint('org:org_a', 1), { previous_digest: 'f'.repeat(64) })); + const runs = await s.expireNow(); + expect(chainsOf(runs)).toEqual(['org:org_b']); + expect(s.warned(/chain 'org:org_a' is NOT expired: its checkpoint 1 does not link to the one before it/)).toBe(1); + }); + + it('the first remaining checkpoint links to the last expiry\'s last removed digest, or the chain is not expired', async () => { + const s = await sealedLedger(); + await s.amend({ first: 0, last: 0, digest: 'f'.repeat(64) }); + s.removeExpired('org:org_a', 0); + const runs = await s.expireNow(); + expect(chainsOf(runs)).toEqual(['org:org_b']); + expect(s.warned(/chain 'org:org_a' is NOT expired: its checkpoint 1 does not link to the one before it \(or to the last expiry\)/)).toBe(1); + }); +}); + +describe('a stored expiry is resumed only over its own chain\'s checkpoints, as it signed them (ADR-0154 D8)', () => { + const resumeRefused = /chain 'org:org_a' is NOT expired further: the range its expiry/; + + it('a checkpoint in the range that is signed for another chain deletes nothing', async () => { + const s = await sealedLedger(); + s.put('org:org_a', 0, { ...s.checkpoint('org:org_b', 0), id: 'misfiled', chain_key: 'org:org_a' }); + await s.amend({ first: 0, last: 0, digest: s.digestOf('org:org_b', 0) }); + const runs = await s.expireNow(); + expect(rowsOf(runs, 'org:org_a')).toBeUndefined(); + expect(s.warned(/chain 'org:org_a' is NOT expired: the checkpoint 0 stored under it is signed for another/)).toBe(1); + }); + + it('the checkpoints of the range run consecutively', async () => { + const s = await sealedLedger(); + // Sequence 1 gone, and a sequence 2 that links straight to 0: every other check passes. + const skipping = await s.resigned(s.checkpoint('org:org_a', 2), { previous_digest: s.digestOf('org:org_a', 0) }); + s.put('org:org_a', 2, skipping); + s.checkpoints().splice(s.checkpoints().indexOf(s.checkpoint('org:org_a', 1)), 1); + await s.amend({ first: 0, last: 2, digest: checkpointDigest(checkpointBodyFromRow(skipping)), to: at(11, 0) }); + const runs = await s.expireNow(); + expect(rowsOf(runs, 'org:org_a')).toBeUndefined(); + expect(s.warned(resumeRefused)).toBe(1); + }); + + it('each checkpoint of the range links to the one before it', async () => { + const s = await sealedLedger(); + const unlinked = await s.resigned(s.checkpoint('org:org_a', 1), { previous_digest: 'f'.repeat(64) }); + s.put('org:org_a', 1, unlinked); + await s.amend({ first: 0, last: 1, digest: checkpointDigest(checkpointBodyFromRow(unlinked)), to: at(10, 0) }); + const runs = await s.expireNow(); + expect(rowsOf(runs, 'org:org_a')).toBeUndefined(); + expect(s.warned(resumeRefused)).toBe(1); + }); + + it('each checkpoint of the range verifies under a trusted key, though its body is the one the amendment names', async () => { + const s = await sealedLedger(); + s.put('org:org_a', 0, { ...s.checkpoint('org:org_a', 0), signature: NO_SIGNATURE }); + await s.amend({ first: 0, last: 0, digest: s.digestOf('org:org_a', 0) }); + const runs = await s.expireNow(); + expect(rowsOf(runs, 'org:org_a')).toBeUndefined(); + expect(s.warned(resumeRefused)).toBe(1); + }); + + it('the range ends at the checkpoint whose digest the amendment carries', async () => { + const s = await sealedLedger(); + await s.amend({ first: 0, last: 1, digest: 'f'.repeat(64), to: at(10, 0) }); + const runs = await s.expireNow(); + expect(rowsOf(runs, 'org:org_a')).toBeUndefined(); + expect(s.warned(resumeRefused)).toBe(1); + }); + + it('a checkpoint before the range is never taken into it', async () => { + const s = await sealedLedger(); + await s.amend({ first: 1, last: 1, digest: s.digestOf('org:org_a', 1), from: at(9, 0), to: at(10, 0) }); + const runs = await s.expireNow(); + expect(rowsOf(runs, 'org:org_a')).toBeUndefined(); + expect(s.warned(resumeRefused)).toBe(1); + }); + + it('a stored expiry under the chain that is signed for another organization is never followed', async () => { + const s = await sealedLedger(); + await s.amend({ first: 0, last: 0, digest: s.digestOf('org:org_a', 0), tenant: 'org_b' }, { id: 'misfiled_am', chainKey: 'org:org_a' }); + const runs = await s.expireNow(); + expect(rowsOf(runs, 'org:org_a')).toBeUndefined(); + expect(s.warned(/chain 'org:org_a' is NOT expired: the expiry amendment misfiled_am stored under it is signed for another/)).toBe(1); + }); + + it('a chain\'s last admitted expiry is found past any number of stored ones that are not admitted', async () => { + const s = await sealedLedger(); + await s.amend({ first: 0, last: 0, digest: s.digestOf('org:org_a', 0) }); + s.removeExpired('org:org_a', 0); + for (let i = 0; i < 50; i++) await s.amend({ first: 3, last: 10 + i, digest: 'f'.repeat(64) }, { id: `unsigned_${i}`, signature: NO_SIGNATURE }); + const runs = await s.expireNow(); + expect(rowsOf(runs, 'org:org_a')).toEqual(['a1', 'a2']); + }); +}); + +describe('the sealer\'s chain head follows only an admitted expiry bound to the chain (ADR-0154 D8)', () => { + /** org_a expired whole (0–2), then a new row in window 13 sealed onto its head. */ + const sealedAfterExpiry = async (plant: (s: Awaited>) => Promise) => { + const s = await sealedLedger(); + const last = s.digestOf('org:org_a', 2); + await s.amend({ first: 0, last: 2, digest: last, to: at(11, 0) }); + for (const sequence of [0, 1, 2]) s.removeExpired('org:org_a', sequence); + await plant(s); + s.clock.now = DAY0 + 15 * H + 30 * 60_000; + s.ledger.push(row('a3', at(13, 10), 'org_a')); + await s.sealer.runPass(); + return { s, last }; + }; + + it('never follows an expiry stored under the chain that is signed for another organization', async () => { + const { s, last } = await sealedAfterExpiry(async (s) => { + await s.amend({ first: 3, last: 9, digest: 'e'.repeat(64), tenant: 'org_b' }, { chainKey: 'org:org_a' }); + }); + expect(s.bodyOf('org:org_a', 3)).toMatchObject({ row_ids: ['a3'], previous_digest: last }); + }); + + it('finds the admitted expiry past any number of stored ones that are not admitted', async () => { + const { s, last } = await sealedAfterExpiry(async (s) => { + for (let i = 0; i < 50; i++) await s.amend({ first: 3, last: 10 + i, digest: 'f'.repeat(64) }, { id: `unsigned_${i}`, signature: NO_SIGNATURE }); + }); + expect(s.bodyOf('org:org_a', 3)).toMatchObject({ row_ids: ['a3'], previous_digest: last }); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts index 8e863c3e72d..3a679afa8f7 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts @@ -2,11 +2,18 @@ import { describe, expect, it } from 'vitest'; import { auditExpiryCutoff, windowOf, type AuditExpiryRequest } from './expiry.js'; +import { bindingCrypto, memoryEngine, recordingLogger } from './seal-store.testkit.js'; +import { AuditSealer } from './sealer.js'; +import { amendmentBodyFromRow, type ExpiryAmendmentBody } from './signed-body.js'; +import { LocalCheckpointSigner } from './signer.js'; /** * ADR-0154 D8, seat ruling on review 7198128323 S1: a tenant-scoped retention * window applies to its organization's chain, and no chain expires under a - * window shorter than one configured for its rows. + * window shorter than one configured for its rows; review 7202871622 S4: a + * window is matched to each row by the column it is configured on, which need + * not be the chain column: a chain expires under the longest window among the + * owners of its rows, the deployment chain under the longest of all. */ const DAY = 24 * 60 * 60 * 1000; @@ -18,6 +25,7 @@ const request: AuditExpiryRequest = { policy: 'retention.maxAge', policyValue: '30d', cutoff: at(30), + tenantColumn: 'tenant_id', tenants: [ { tenantId: 'org_long', policyValue: '400d', cutoff: at(400) }, { tenantId: 'org_short', policyValue: '10d', cutoff: at(10) }, @@ -26,22 +34,109 @@ const request: AuditExpiryRequest = { describe('windowOf — the window each chain of a sealed object expires under', () => { it("an organization's chain takes its own tenant-scoped window, shorter or longer than the global one", () => { - expect(windowOf(request, 'org:org_long')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 400 * DAY), policyValue: '400d' }); - expect(windowOf(request, 'org:org_short')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 10 * DAY), policyValue: '10d' }); + expect(windowOf(request, 'org:org_long', 'tenant_id')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 400 * DAY), policyValue: '400d' }); + expect(windowOf(request, 'org:org_short', 'tenant_id')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 10 * DAY), policyValue: '10d' }); }); it('an organization with no window of its own takes the global one', () => { - expect(windowOf(request, 'org:org_plain')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }); + expect(windowOf(request, 'org:org_plain', 'tenant_id')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }); }); it('a chain of no one organization takes the longest of all of them', () => { - expect(windowOf(request, 'deployment')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 400 * DAY), policyValue: '400d' }); - expect(windowOf({ ...request, tenants: [{ tenantId: 'org_short', policyValue: '10d', cutoff: at(10) }] }, 'deployment')) + expect(windowOf(request, 'deployment', 'tenant_id')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 400 * DAY), policyValue: '400d' }); + expect(windowOf({ ...request, tenants: [{ tenantId: 'org_short', policyValue: '10d', cutoff: at(10) }] }, 'deployment', 'tenant_id')) .toEqual({ cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }); }); + it('where the windows are configured on another column than the chain column, a chain whose owners are not read takes the longest', () => { + const other = { ...request, tenantColumn: 'organization_id' }; + for (const key of ['org:org_short', 'org:org_long', 'org:org_plain', 'deployment']) { + expect(windowOf(other, key, 'tenant_id')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 400 * DAY), policyValue: '400d' }); + } + }); + + it('where the windows are configured on another column, a chain takes the longest window among the owners of its rows', () => { + // A ledger chained on `tenant_id` whose windows are configured on `organization_id`: the chain key names no owner. + const other = { ...request, tenantColumn: 'organization_id' }; + const short = { cutoffMs: auditExpiryCutoff(NOW - 10 * DAY), policyValue: '10d' }; + const long = { cutoffMs: auditExpiryCutoff(NOW - 400 * DAY), policyValue: '400d' }; + const global = { cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }; + expect(windowOf(other, 'org:org_long', 'tenant_id', ['org_short'])).toEqual(short); + expect(windowOf(other, 'org:org_short', 'tenant_id', ['org_short', 'org_long'])).toEqual(long); + expect(windowOf(other, 'org:org_short', 'tenant_id', ['org_short', 'org_plain'])).toEqual(global); + expect(windowOf(other, 'org:org_short', 'tenant_id', ['org_short', null])).toEqual(global); + // A row that could not be read may be anyone's. + expect(windowOf(other, 'org:org_short', 'tenant_id', ['org_short', undefined])).toEqual(long); + // The deployment chain takes the longest of all, whoever owns its rows. + expect(windowOf(other, 'deployment', 'tenant_id', ['org_short'])).toEqual(long); + }); + it('with no tenant window every chain takes the global one', () => { const { tenants: _, ...plain } = request; - expect(windowOf(plain, 'org:org_long')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }); + expect(windowOf(plain, 'org:org_long', 'tenant_id')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }); + }); +}); + +describe('a ledger chained on `tenant_id` beside an injected `organization_id`: each row expires under its owner\'s window (review 7202871622 S4)', () => { + const H = 60 * 60 * 1000; + const DAY0 = Date.UTC(2026, 10, 10); + const hour = (h: number, m: number) => new Date(DAY0 + h * H + m * 60_000).toISOString(); + const LEDGER = { + name: 'policy_change_log', + fields: { + id: { type: 'text' }, created_at: { type: 'datetime' }, tenant_id: { type: 'lookup' }, + organization_id: { type: 'lookup' }, new_value: { type: 'textarea' }, + }, + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal: { valueFields: ['new_value'] } }, + }; + const entry = (id: string, created: string, tenant: string | null, organization: string) => + ({ id, created_at: created, tenant_id: tenant, organization_id: organization, new_value: `{"v":"${id}"}` }); + + /** Seal the four rows at 12:30, move `archived` to the archive, and expire 60 days on: org_short 10d, org_long 400d. */ + const expireShape = async (archived: readonly string[] = []) => { + const ledger = archived.length > 0 ? { ...LEDGER, lifecycle: { ...LEDGER.lifecycle, archive: { after: '30d', to: 'archive' } } } : LEDGER; + const store = memoryEngine([ledger, { name: 'sys_audit_amendment', fields: {} }] as never); + const crypto = bindingCrypto(); + const signer = new LocalCheckpointSigner({ engine: store.engine, crypto }); + const clock = { now: DAY0 + 12 * H + 30 * 60_000 }; + const sealer = new AuditSealer({ engine: store.engine, crypto, signer: () => signer, logger: recordingLogger(), now: () => clock.now }); + store.hot.table('policy_change_log').push( + entry('s0', hour(8, 10), 'org_short', 'org_short'), // chain org:org_short, sequence 0 + entry('s1', hour(9, 10), 'org_short', 'org_long'), // chain org:org_short, sequence 1: org_long's row + entry('l0', hour(8, 20), 'org_long', 'org_short'), // chain org:org_long: org_short's row + entry('d0', hour(8, 30), null, 'org_short'), // the deployment chain + ); + await sealer.runPass(); + for (const id of archived) { + const hot = store.hot.table('policy_change_log'); + store.archive.table('policy_change_log').push(...hot.splice(hot.findIndex((r) => r.id === id), 1)); + } + clock.now = DAY0 + 60 * DAY; + const since = (days: number) => new Date(clock.now - days * DAY).toISOString(); + const runs = await sealer.expire({ + object: 'policy_change_log', policy: 'retention.maxAge', policyValue: '90d', cutoff: since(90), + tenantColumn: 'organization_id', + tenants: [ + { tenantId: 'org_short', policyValue: '10d', cutoff: since(10) }, + { tenantId: 'org_long', policyValue: '400d', cutoff: since(400) }, + ], + }); + const signed = store.hot.table('sys_audit_amendment').map((row) => amendmentBodyFromRow(row) as ExpiryAmendmentBody); + return { + runs: Object.fromEntries(runs.map((r) => [r.chain, r.rowIds])), + signed: Object.fromEntries(signed.map((b) => [b.tenant_id, [b.first_sequence, b.last_sequence, b.policy_value]])), + }; + }; + + it('a chain takes the longest window among the organizations that own its rows, whatever its chain key names', async () => { + const { runs, signed } = await expireShape(); + expect(runs).toEqual({ 'org:org_short': ['s0'], 'org:org_long': ['l0'] }); + expect(signed).toEqual({ org_short: [0, 0, '10d'], org_long: [0, 0, '10d'] }); + }); + + it('the owner of a row already archived is read from the archive', async () => { + const { runs, signed } = await expireShape(['l0']); + expect(runs).toEqual({ 'org:org_short': ['s0'], 'org:org_long': ['l0'] }); + expect(signed).toEqual({ org_short: [0, 0, '10d'], org_long: [0, 0, '10d'] }); }); }); diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-verifier.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-verifier.test.ts index 7f438065ff9..668cd12c5d1 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-verifier.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-verifier.test.ts @@ -422,7 +422,7 @@ describe('redaction amendments (D7)', () => { describe('expiry amendments (D8)', () => { /** Expire org_a's sequence 0 (window 08:00): rows first, then the checkpoint — or stop between the two. */ - const expire = async (s: Awaited>, options: { keep?: string; first?: number; last?: number; digest?: string; removeCheckpoint?: boolean } = {}) => { + const expire = async (s: Awaited>, options: { keep?: string; first?: number; last?: number; digest?: string; removeCheckpoint?: boolean; coveredTo?: string } = {}) => { const cp = s.checkpoint('org:org_a', 0); const body = checkpointBodyFromRow(cp); await s.amend({ @@ -433,7 +433,7 @@ describe('expiry amendments (D8)', () => { first_sequence: options.first ?? 0, last_sequence: options.last ?? 0, covered_from: body.window_start, - covered_to: body.window_end, + covered_to: options.coveredTo ?? body.window_end, last_removed_digest: options.digest ?? checkpointDigest(body), policy: 'archive.keep', policy_value: options.keep ?? '7d', @@ -482,6 +482,25 @@ describe('expiry amendments (D8)', () => { expect(faultKinds(await s.verifyNow())).toEqual(['org:org_a#1:link']); }); + it('never reads a checkpoint of an honoured range expired when its own window ends later than the range covers', async () => { + const s = await sealedLedger(); + s.clock.now = DAY0 + 30 * 24 * H; + // Sequences 0–1 of org_a, signed as covering only window 08:00: checkpoint 1 (window 10:00) was not expired by it. + await expire(s, { last: 1, digest: checkpointDigest(checkpointBodyFromRow(s.checkpoint('org:org_a', 1))) }); + const report = await s.verifyNow(); + expect(faultKinds(report)).toEqual(['org:org_a#1:expiry']); + expect(verdicts(report)).toEqual({}); // r4 is judged, and unmodified + }); + + it('reports an amendment stored under a chain other than its signed organization, as it does a checkpoint', async () => { + const s = await sealedLedger(); + s.clock.now = DAY0 + 30 * 24 * H; + await expire(s); + const [stored] = s.hot.table('sys_audit_amendment'); + stored.chain_key = 'org:org_b'; + expect(faultKinds(await s.verifyNow())).toEqual(['org:org_a#-:chain_key']); + }); + it('never reads a row written back into an expired window as expired: no checkpoint holds it', async () => { const s = await sealedLedger(); s.clock.now = DAY0 + 30 * 24 * H; diff --git a/packages/plugins/plugin-audit/src/audit-seal/expiry.ts b/packages/plugins/plugin-audit/src/audit-seal/expiry.ts index 605532aa123..d9174881ed2 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/expiry.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/expiry.ts @@ -21,7 +21,7 @@ import type { SigningKeyTrust } from './verifier.js'; /** * ADR-0154 D8 — expiry removes a sealed prefix of each chain and writes a * signed amendment. This is the audit plugin's half of the seam the - * LifecycleService calls (`LifecycleSealedExpiry` in `@objectstack/objectql`): + * LifecycleService calls (`LifecycleExpiryPrefix` in `@objectstack/objectql`): * it answers, per chain, the run of whole checkpoints that expired and the * rows they list, having signed and stored the chain's `expiry` amendment * first. The sweep then deletes exactly those rows, and only after them @@ -63,8 +63,10 @@ export const AUDIT_EXPIRY_MAX_ROWS_PER_SWEEP = 10_000; const DAY_MS = 24 * 60 * 60 * 1000; /** Checkpoints read per page of one chain's run. A checkpoint lists up to 10,000 row ids, so pages stay small. */ const PAGE_SIZE = 20; -/** Expiry amendments read from the top of a chain to find its last admitted one. */ -const LATEST_EXPIRY_SCAN = 10; +/** Stored expiry amendments read per page while looking for a chain's newest admitted one. */ +const AMENDMENT_PAGE_SIZE = 50; +/** Row ids per read of their owners (S4). */ +const OWNER_READ_BATCH = 500; const MAX_SIGN_ATTEMPTS = 3; const NO_KEY_YET = 'unknown'; @@ -75,14 +77,16 @@ export function auditExpiryCutoff(cutoffMs: number): number { return Math.floor(cutoffMs / DAY_MS) * DAY_MS; } -/** What the sweep asks (`LifecycleSealedExpiryRequest`, `@objectstack/objectql`). */ +/** What the sweep asks (`LifecycleExpiryPrefixRequest`, `@objectstack/objectql`). */ export interface AuditExpiryRequest { readonly object: string; readonly policy: string; readonly policyValue: string; readonly cutoff: string; - /** Tenant-scoped windows: an organization's chain expires under its own (see {@link windowOf}). */ + /** Tenant-scoped windows, each for the rows its organization owns by {@link tenantColumn} (see {@link windowOf}). */ readonly tenants?: ReadonlyArray<{ readonly tenantId: string; readonly policyValue: string; readonly cutoff: string }>; + /** The column {@link tenants} are configured on, which need not be the chain column. */ + readonly tenantColumn?: string; } /** The window one chain expires under: its day-aligned cutoff and the policy value its amendment signs. */ @@ -98,26 +102,49 @@ const cutoffOf = (cutoff: string): number => { }; /** - * The window chain `key` expires under. An organization's chain (`org:`) - * takes its organization's tenant-scoped window where one is set, else the - * global one. Any other chain — the deployment chain, of no one organization — - * takes the longest of the global window and every tenant window, so no chain - * expires under a window shorter than one configured for its rows. + * The window chain `key` expires under, for an object chained on `chainField`, + * never shorter than the window configured for any row it holds (seat ruling + * on review 7202871622 S4). + * + * - No tenant window: the global one. + * - Not an organization's chain (the deployment chain): the longest of the + * global window and every tenant window. + * - The tenant windows are configured on the chain column itself: the chain + * holds its organization's rows alone, so it takes that organization's + * window, else the global one. + * - Otherwise a chain may hold rows several organizations own, by the column + * the windows are configured on. `owners` are those owners, one per row + * (`null` for a row about no organization, `undefined` for a row that could + * not be read): the chain takes the longest window among them, an owner + * with no window of its own taking the global one and an unread row the + * longest of all. Without `owners`, the longest of all. */ -export function windowOf(request: AuditExpiryRequest, key: string): ChainWindow { +export function windowOf( + request: AuditExpiryRequest, + key: string, + chainField: string, + owners?: ReadonlyArray, +): ChainWindow { const global: ChainWindow = { cutoffMs: cutoffOf(request.cutoff), policyValue: request.policyValue }; const tenants = request.tenants ?? []; if (tenants.length === 0) return global; const windowOfTenant = (t: (typeof tenants)[number]): ChainWindow => ({ cutoffMs: cutoffOf(t.cutoff), policyValue: t.policyValue }); - if (key.startsWith('org:')) { - const own = tenants.find((t) => chainKeyOf(t.tenantId) === key); - return own ? windowOfTenant(own) : global; - } // The longest window is the earliest cutoff. - return tenants.map(windowOfTenant).reduce((longest, t) => (t.cutoffMs < longest.cutoffMs ? t : longest), global); + const longest = (windows: readonly ChainWindow[]): ChainWindow => + windows.length === 0 ? global : windows.reduce((a, b) => (b.cutoffMs < a.cutoffMs ? b : a)); + const longestOfAll = longest([global, ...tenants.map(windowOfTenant)]); + if (!key.startsWith('org:')) return longestOfAll; + const ownerWindow = (owner: string | null): ChainWindow => { + const own = owner === null ? undefined : tenants.find((t) => t.tenantId === owner); + return own ? windowOfTenant(own) : global; + }; + if (request.tenantColumn === chainField) return ownerWindow(key.slice('org:'.length)); + if (!owners) return longestOfAll; + if (owners.some((o) => o === undefined)) return longestOfAll; + return longest([...new Set(owners as ReadonlyArray)].map(ownerWindow)); } -/** One chain's planned expiry (`LifecycleSealedExpiryRun`, `@objectstack/objectql`). */ +/** One chain's planned expiry (`LifecycleExpiryPrefixRun`, `@objectstack/objectql`). */ export interface AuditExpiryRun { readonly chain: string; readonly rowIds: readonly string[]; @@ -128,6 +155,10 @@ export interface AuditExpiryRun { export interface ObjectExpiryOptions { readonly engine: SealStorageEngine; readonly object: string; + /** The object's chain column (`lifecycle.seal.chainField`, default `tenant_id`). */ + readonly chainField: string; + /** The object's `archive.to` datasource, if it has one: owners of archived rows are read there (S4). */ + readonly archive?: SealStorageDriver; readonly signer: IAuditCheckpointSigner & { activeKeyId?(): Promise }; readonly sink?: IAuditCheckpointSink; readonly trust: SigningKeyTrust; @@ -189,7 +220,7 @@ export class ObjectExpiry { if (!candidate) break; const key = String(candidate.chain_key); after = key; - const run = await this.chainRun(key, windowOf(request, key), budget, request); + const run = await this.chainRun(key, budget, request); if (!run) continue; runs.push(run.run); budget -= run.run.rowIds.length; @@ -220,34 +251,92 @@ export class ObjectExpiry { } } - /** The chain's last expiry that is admitted (its signature verifies under a trusted key), if any. */ - private async latestExpiry(key: string): Promise { + /** + * Whether a stored body belongs where it is stored: its signed object is this + * one and its signed organization is chain `key`. The row's `sealed_object` + * and `chain_key` columns are not signed; the body is. + */ + private bound(key: string, body: { readonly sealed_object: string; readonly tenant_id: string | null }): boolean { + return body.sealed_object === this.object && chainKeyOf(body.tenant_id) === key; + } + + /** A chain holding a row that is not bound to it is not expired at all, and that is said once. */ + private refuseUnbound(key: string, what: string): null { + this.options.say( + `expiry:unbound:${this.object}:${key}`, + `AuditSealer: '${this.object}' chain '${key}' is NOT expired: ${what} stored under it is signed for another ` + + 'object or organization. Nothing in the chain is deleted; os audit verify reports it.', + ); + return null; + } + + /** A chain whose checkpoints do not link one to the next is not expired at all, and that is said once. */ + private refuseUnlinked(key: string, sequence: number): null { + this.options.say( + `expiry:link:${this.object}:${key}`, + `AuditSealer: '${this.object}' chain '${key}' is NOT expired: its checkpoint ${sequence} does not link to the ` + + 'one before it (or to the last expiry). Nothing in the chain is deleted; os audit verify reports the link.', + ); + return null; + } + + /** + * The chain's last expiry that is admitted — bound to the chain and signed + * under a trusted key — if any, walking every stored one newest first. A + * stored expiry under the chain that is bound elsewhere answers `null`: the + * chain is not expired at all. + */ + private async latestExpiry(key: string): Promise { if (!this.amendments) return undefined; - const rows = await this.find(this.amendments, AUDIT_AMENDMENT_OBJECT, { - where: { sealed_object: this.object, chain_key: key, kind: 'expiry' }, - orderBy: [{ field: 'last_sequence', order: 'desc' }], - limit: LATEST_EXPIRY_SCAN, - }); - for (const stored of rows) { - let body; - try { - body = amendmentBodyFromRow(stored); - } catch { - continue; + for (let offset = 0; ; offset += AMENDMENT_PAGE_SIZE) { + const rows = await this.find(this.amendments, AUDIT_AMENDMENT_OBJECT, { + where: { sealed_object: this.object, chain_key: key, kind: 'expiry' }, + orderBy: [{ field: 'last_sequence', order: 'desc' }, { field: 'id', order: 'asc' }], + limit: AMENDMENT_PAGE_SIZE, + offset, + }); + for (const stored of rows) { + let body; + try { + body = amendmentBodyFromRow(stored); + } catch { + continue; + } + if (body.kind !== 'expiry') continue; + if (!this.bound(key, body)) return this.refuseUnbound(key, `the expiry amendment ${String(stored.id)}`); + if ((await this.options.trust.signature(body.signing_key_id, signedBodyBytes(body), stored.signature)) === 'ok') return body; + } + if (rows.length < AMENDMENT_PAGE_SIZE) return undefined; + } + } + + /** + * The owners of `ids` by `column`, one per id, read from the object's hot + * store and then its archive for the ids the hot store does not hold + * (`undefined` for a row neither holds). + */ + private async ownersOf(ids: readonly string[], column: string): Promise> { + const byId = new Map(); + const hot = this.options.engine.getDriverForObject(this.object); + for (const store of [hot, this.options.archive]) { + if (!store) continue; + const unread = ids.filter((id) => !byId.has(id)); + for (let at = 0; at < unread.length; at += OWNER_READ_BATCH) { + const batch = unread.slice(at, at + OWNER_READ_BATCH); + for (const row of await this.find(store, this.object, { where: { id: { $in: batch } }, limit: batch.length })) { + const owner = row[column]; + byId.set(String(row.id), owner === null || owner === undefined || owner === '' ? null : String(owner)); + } } - if (body.kind !== 'expiry' || body.sealed_object !== this.object) continue; - if ((await this.options.trust.signature(body.signing_key_id, signedBodyBytes(body), stored.signature)) === 'ok') return body; } - return undefined; + return ids.map((id) => (byId.has(id) ? byId.get(id)! : undefined)); } private async chainRun( key: string, - window: ChainWindow, budget: number, request: AuditExpiryRequest, ): Promise<{ run: AuditExpiryRun; cut: boolean } | null> { - const { cutoffMs } = window; const [firstRow] = await this.find(this.checkpoints, AUDIT_CHECKPOINT_OBJECT, { where: { sealed_object: this.object, chain_key: key }, orderBy: [{ field: 'sequence', order: 'asc' }], @@ -256,11 +345,14 @@ export class ObjectExpiry { if (!firstRow) return null; const first = this.parse(key, firstRow); if (!first) return null; + // Each checkpoint either branch takes, this first one included, is bound to the chain before it is taken. const latest = await this.latestExpiry(key); + if (latest === null) return null; // A sweep that stopped after the amendment was stored: its range is finished first. Each checkpoint left in - // it is admitted as in a fresh run, and they must run consecutively to the amendment's last sequence, whose - // digest it carries: a row that is not the platform's own deletes nothing, and neither does its range. + // it is admitted as in a fresh run — bound to the chain, signed under a trusted key — and they must run + // consecutively, each linked to the one before, to the amendment's last sequence, whose digest it carries: + // a row that is not the platform's own deletes nothing, and neither does its range. if (latest && latest.last_sequence >= first.sequence) { if (first.sequence < latest.first_sequence) return this.refuseResume(key, latest, first.sequence); const taken: Taken[] = []; @@ -272,10 +364,13 @@ export class ObjectExpiry { })) { const body = this.parse(key, stored); if (!body) return null; - const admitted = - body.sequence === next && - (await this.options.trust.signature(body.signing_key_id, signedBodyBytes(body), stored.signature)) === 'ok'; - if (!admitted) return this.refuseResume(key, latest, body.sequence); + if (!this.bound(key, body)) return this.refuseUnbound(key, `the checkpoint ${body.sequence}`); + if (body.sequence !== next) return this.refuseResume(key, latest, body.sequence); + const previous = taken[taken.length - 1]; + if (previous && body.previous_digest !== checkpointDigest(previous.body)) return this.refuseResume(key, latest, body.sequence); + if ((await this.options.trust.signature(body.signing_key_id, signedBodyBytes(body), stored.signature)) !== 'ok') { + return this.refuseResume(key, latest, body.sequence); + } taken.push({ stored, body }); next += 1; } @@ -298,6 +393,15 @@ export class ObjectExpiry { ); return null; } + // The first links to the last expiry's last removed checkpoint (sequence 0 links to nothing: `parse` holds it). + if (latest && first.previous_digest !== latest.last_removed_digest) return this.refuseUnlinked(key, first.sequence); + + // Where a chain may hold rows several organizations own, each checkpoint's owners decide its window (S4). + const byOwners = + key.startsWith('org:') && (request.tenants?.length ?? 0) > 0 && request.tenantColumn !== undefined && + request.tenantColumn !== this.options.chainField; + const owners: Array = []; + let window = windowOf(request, key, this.options.chainField, byOwners ? [] : undefined); const taken: Taken[] = []; let rows = 0; @@ -312,7 +416,15 @@ export class ObjectExpiry { for (const stored of page) { const body = this.parse(key, stored); if (!body || body.sequence !== next) break walk; // a malformed checkpoint or a gap ends the run - if (Date.parse(canonicalDatetime(body.window_end, 'window_end')) > cutoffMs) break walk; + if (!this.bound(key, body)) return this.refuseUnbound(key, `the checkpoint ${body.sequence}`); + const previous = taken[taken.length - 1]; + if (previous && body.previous_digest !== checkpointDigest(previous.body)) return this.refuseUnlinked(key, body.sequence); + let candidate = window; + if (byOwners) { + owners.push(...(await this.ownersOf(body.row_ids, request.tenantColumn!))); + candidate = windowOf(request, key, this.options.chainField, owners); + } + if (Date.parse(canonicalDatetime(body.window_end, 'window_end')) > candidate.cutoffMs) break walk; if (taken.length > 0 && rows + body.row_ids.length > budget) { cut = true; break walk; @@ -326,6 +438,8 @@ export class ObjectExpiry { ); break walk; } + // The window only lengthens as owners join, and windows end in order: every checkpoint taken ended by it. + window = candidate; taken.push({ stored, body }); rows += body.row_ids.length; next += 1; @@ -407,7 +521,7 @@ export class ObjectExpiry { } } - /** The rows `taken` list, and the removal of its checkpoints and then their seeds, once the rows are gone. */ + /** The rows `taken` list, and the removal of their seeds and checkpoints, once the rows are gone. */ private runOf(key: string, taken: readonly Taken[]): AuditExpiryRun { const ids = new Set(); for (const { body } of taken) for (const id of body.row_ids) ids.add(id); @@ -417,8 +531,12 @@ export class ObjectExpiry { chain: key, rowIds: [...ids], async complete() { - for (const { stored } of taken) await checkpoints.delete!(AUDIT_CHECKPOINT_OBJECT, String(stored.id)); - for (const { body } of taken) await dropAuditSealSecret(engine, body.seed_handle); + // Oldest first, each seed before its checkpoint: a stop part way leaves no seed whose checkpoint is gone, + // and the checkpoints left are this range's, which the next sweep resumes. + for (const { stored, body } of taken) { + await dropAuditSealSecret(engine, body.seed_handle); + await checkpoints.delete!(AUDIT_CHECKPOINT_OBJECT, String(stored.id)); + } }, }; } diff --git a/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts b/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts index e8cc3a75719..9983d2f72d4 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts @@ -28,10 +28,11 @@ function matches(row: Row, where: Record = {}): boolean { const ops = cond as Record; const isNull = value === null || value === undefined; if ('$null' in ops && ops.$null !== isNull) return false; - if (isNull && ['$gte', '$gt', '$lt', '$in'].some((op) => op in ops)) return false; + if (isNull && ['$gte', '$gt', '$lt', '$lte', '$in'].some((op) => op in ops)) return false; if ('$gte' in ops && !((value as number) >= (comparable(ops.$gte) as number))) return false; if ('$gt' in ops && !((value as number) > (comparable(ops.$gt) as number))) return false; if ('$lt' in ops && !((value as number) < (comparable(ops.$lt) as number))) return false; + if ('$lte' in ops && !((value as number) <= (comparable(ops.$lte) as number))) return false; if ('$in' in ops && !(ops.$in as unknown[]).some((v) => comparable(v) === value)) return false; return true; } diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index cd65bdb8abd..2d93151da2c 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -535,7 +535,7 @@ export class AuditSealer { /** * ADR-0154 D8: plan one sweep's expiry of sealed object `request.object` - * (`expiry.ts`), the LifecycleService's `LifecycleSealedExpiry`. It holds the + * (`expiry.ts`), the LifecycleService's `LifecycleExpiryPrefix`. It holds the * pass's locks while it plans and signs — `audit.sealer` and the audit seal * lock on the object's database — so two replicas' sweeps never sign two * expiries over one range. The run's `complete()` runs later, after the @@ -552,6 +552,7 @@ export class AuditSealer { if (!plan) return []; const memo = [ `${auditExpiryCutoff(Date.parse(request.cutoff))}|${request.policy}|${request.policyValue}`, + `on:${request.tenantColumn ?? ''}`, ...(request.tenants ?? []).map((t) => `${t.tenantId}=${auditExpiryCutoff(Date.parse(t.cutoff))}|${t.policyValue}`).sort(), ].join(';'); if (this.drainedAt.get(plan.name) === memo) return []; @@ -568,9 +569,17 @@ export class AuditSealer { const session = await trySealPassLocks(this.options.engine, [plan.name]); if (session.held) return []; try { + let archive: SealStorageDriver | undefined; + try { + archive = plan.archiveTo ? this.options.engine.datasource?.(plan.archiveTo) : undefined; + } catch { + archive = undefined; + } const expiry = new ObjectExpiry({ engine: this.options.engine, object: plan.name, + chainField: plan.chainField, + ...(archive ? { archive } : {}), signer, ...(seams.sink ? { sink: seams.sink } : {}), trust: new SigningKeyTrust(anchoredPublicKeyOf(this.options.engine, crypto, signer)), @@ -618,10 +627,10 @@ export class AuditSealer { } } -/** One pass over one sealed object. */ -/** Stored expiry amendments one head or floor read walks, newest first, for the newest admitted one. */ -const LAST_EXPIRY_SCAN = 10; +/** Stored expiry amendments one page of a head or floor read takes, newest first, while it looks for an admitted one. */ +const LAST_EXPIRY_PAGE = 50; +/** One pass over one sealed object. */ class ObjectPass { private readonly heads = new Map(); private readonly hot: SealStorageDriver; @@ -944,38 +953,44 @@ class ObjectPass { /** * D8: the stored `expiry` amendment of this object (narrowed by `where`) that - * is highest by `field` among those admitted — whose signature verifies under - * a trusted key (D6) — or `undefined`. A row that is not admitted is passed - * over, so a head or a floor never follows one. A malformed one is a - * chain-local fault of its chain (S4). It is read only where no checkpoint - * answers: a chain's head, and the floor of an object whose every checkpoint - * expired. + * is highest by `field` among those admitted — bound where it is stored (its + * signed object is this one and its signed organization is the chain it is + * stored under) and signed under a trusted key (D6) — or `undefined`. Every + * stored one is walked, page by page, so no run of rows that are not admitted + * hides an admitted one; a row that is not admitted is passed over, so a head + * or a floor never follows one. A malformed one is a chain-local fault of its + * chain (S4). It is read only where no checkpoint answers: a chain's head, and + * the floor of an object whose every checkpoint expired. */ private async lastExpiry(where: Row, field: 'last_sequence' | 'covered_to'): Promise { const driver = this.options.engine.getDriverForObject(AUDIT_AMENDMENT_OBJECT); if (!driver) return undefined; - let rows: Row[]; - try { - rows = await driver.find(AUDIT_AMENDMENT_OBJECT, { - where: { sealed_object: this.plan.name, kind: 'expiry', ...where }, - orderBy: [{ field, order: 'desc' }], - limit: LAST_EXPIRY_SCAN, - }); - } catch (err) { - if (isMissingTableError(err, AUDIT_AMENDMENT_OBJECT)) return undefined; - throw err; - } - for (const row of rows) { - let body; + for (let offset = 0; ; offset += LAST_EXPIRY_PAGE) { + let rows: Row[]; try { - body = amendmentBodyFromRow(row); + rows = await driver.find(AUDIT_AMENDMENT_OBJECT, { + where: { sealed_object: this.plan.name, kind: 'expiry', ...where }, + orderBy: [{ field, order: 'desc' }, { field: 'id', order: 'asc' }], + limit: LAST_EXPIRY_PAGE, + offset, + }); } catch (err) { - throw new ChainFault(String(row.chain_key), err); + if (isMissingTableError(err, AUDIT_AMENDMENT_OBJECT)) return undefined; + throw err; + } + for (const row of rows) { + let body; + try { + body = amendmentBodyFromRow(row); + } catch (err) { + throw new ChainFault(String(row.chain_key), err); + } + if (body.kind !== 'expiry') continue; + if (body.sealed_object !== this.plan.name || chainKeyOf(body.tenant_id) !== String(row.chain_key)) continue; + if ((await this.trust().signature(body.signing_key_id, signedBodyBytes(body), row.signature)) === 'ok') return body; } - if (body.kind !== 'expiry') continue; - if ((await this.trust().signature(body.signing_key_id, signedBodyBytes(body), row.signature)) === 'ok') return body; + if (rows.length < LAST_EXPIRY_PAGE) return undefined; } - return undefined; } /** D6: the keys this deployment trusts, as the expiry and the verifier admit them. */ diff --git a/packages/plugins/plugin-audit/src/audit-seal/verifier.ts b/packages/plugins/plugin-audit/src/audit-seal/verifier.ts index 0afbe93d65c..5fd503d062f 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/verifier.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/verifier.ts @@ -644,6 +644,12 @@ export abstract class ChainCheck { continue; } const chain = chainKeyOf(body.tenant_id); + if (row.chain_key !== chain) { + this.check.fault({ + object: this.name, chain, kind: 'chain_key', amendment: String(row.id), + message: `${body.kind} amendment ${String(row.id)}: stored under chain '${String(row.chain_key)}', but its signed organization is chain '${chain}'`, + }); + } const signed = await this.check.signature(body.signing_key_id, signedBodyBytes(body), row.signature); if (signed !== 'ok') { // An amendment nothing vouches for is ignored: the row it would explain reads as what it is. @@ -750,7 +756,16 @@ export abstract class ChainCheck { ): Promise { const body = checkpointBodyFromRow(row); const at = { object: this.name, chain: head.chain }; - if (this.expiryCovering(head.chain, head.sequence)) { + const covering = this.expiryCovering(head.chain, head.sequence); + if (covering && Date.parse(body.window_end) > Date.parse(covering.covered_to)) { + // D8: an honoured range expires only the windows it covers. A checkpoint in it whose own window ends later + // was never expired by it, so its rows are judged as what they are. + this.check.fault({ + ...at, kind: 'expiry', sequence: body.sequence, + message: `checkpoint ${body.sequence}: its window ends ${body.window_end}, later than the honoured expiry of sequences ` + + `${covering.first_sequence}–${covering.last_sequence} covers (${covering.covered_to}) — its rows are judged, not expired`, + }); + } else if (covering) { // D8: a row a checkpoint inside an honoured range lists is expired, gone or not yet gone. for (const id of body.row_ids) { this.held.add(id); diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 4f5dbbd2bf8..f7ee84025d6 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1176,10 +1176,13 @@ export const LifecycleSchema = lazySchema(() => strictObject({ "the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` " + "`onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their " + '`retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry ' + - 'amendment names them, so the verifier reads them as expired rather than missing; a tenant-scoped ' + - "retention window applies to that organization's chain, and the window is counted to the start of a UTC " + - 'day, so a row can stay up to a day longer. While no sealer is running, the sweeper keeps them. A ' + - 'deployment with no crypto provider seals nothing and reports that at error.', + 'amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped ' + + 'retention window is matched to each row by the column it is set on: a chain expires under the longest ' + + 'window among the organizations whose rows it holds, and the chain of rows about no organization under ' + + 'the longest window set, so no row leaves before its own window. The window is counted to the start of a ' + + 'UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a ' + + 'backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto ' + + 'provider seals nothing and reports that at error.', ), reclaim: z.boolean().optional().describe('Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes.'), }).superRefine((lc, ctx) => { From c05884d460b1e3b8aa6dbe33a588175f47d7a822 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:19:37 +0000 Subject: [PATCH 11/16] test(dogfood): pass --sealer-stopped to the SQLite os migrate audit-* --apply runs sys_audit_log is sealed by default, so an --apply run over SQLite needs the flag (ADR-0154 D3 amended, B), as the CLI integration tests already do. No server seals these fixtures while the command runs. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt --- packages/qa/dogfood/test/audit-key-material.dogfood.test.ts | 6 ++++-- packages/qa/dogfood/test/audit-mail-bodies.dogfood.test.ts | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/qa/dogfood/test/audit-key-material.dogfood.test.ts b/packages/qa/dogfood/test/audit-key-material.dogfood.test.ts index 31b48b476e1..60be30104c2 100644 --- a/packages/qa/dogfood/test/audit-key-material.dogfood.test.ts +++ b/packages/qa/dogfood/test/audit-key-material.dogfood.test.ts @@ -193,7 +193,9 @@ describe('os migrate audit-key-material over an 18.0 database', () => { }, 300_000); it('2. --apply leaves 0 copies carrying one, and moves no byte but the removed columns', () => { - const run = runCommand(file, ['--apply', '--yes']); + // [#31908] sys_audit_log declares lifecycle.seal, and SQLite offers no session lock: an --apply run + // needs --sealer-stopped (ADR-0154 D3 amended, B). No server seals this fixture while the command runs. + const run = runCommand(file, ['--apply', '--yes', '--sealer-stopped']); expect(run.status, run.out).toBe(0); expect(run.report?.failures).toBe(0); expect(run.report?.rewritten).toBe(fixtureCopies.audit + fixtureCopies.activity); @@ -229,7 +231,7 @@ describe('os migrate audit-key-material over an 18.0 database', () => { it('3. a second --apply rewrites nothing and changes no byte', () => { const before = snapshot(file); - const again = runCommand(file, ['--apply', '--yes']); + const again = runCommand(file, ['--apply', '--yes', '--sealer-stopped']); expect(again.status, again.out).toBe(0); expect(again.report?.rewritten).toBe(0); expect(again.report?.failures).toBe(0); diff --git a/packages/qa/dogfood/test/audit-mail-bodies.dogfood.test.ts b/packages/qa/dogfood/test/audit-mail-bodies.dogfood.test.ts index 6384128dc75..99d83c1b59a 100644 --- a/packages/qa/dogfood/test/audit-mail-bodies.dogfood.test.ts +++ b/packages/qa/dogfood/test/audit-mail-bodies.dogfood.test.ts @@ -184,7 +184,9 @@ describe('[#24693] os migrate audit-mail-bodies over an 18.0 database', () => { }, 300_000); it('2. --apply leaves 0 clear copies, and moves no byte but the masked bodies', () => { - const run = runCommand(file, ['--apply', '--yes']); + // [#31908] sys_audit_log declares lifecycle.seal, and SQLite offers no session lock: an --apply run + // needs --sealer-stopped (ADR-0154 D3 amended, B). No server seals this fixture while the command runs. + const run = runCommand(file, ['--apply', '--yes', '--sealer-stopped']); expect(run.status, run.out).toBe(0); expect(run.report?.failures).toBe(0); expect(run.report?.rewritten).toBe(fixtureClear.audit + fixtureClear.activity); @@ -219,7 +221,7 @@ describe('[#24693] os migrate audit-mail-bodies over an 18.0 database', () => { it('3. a second --apply masks nothing and changes no byte', () => { const before = snapshot(file); - const again = runCommand(file, ['--apply', '--yes']); + const again = runCommand(file, ['--apply', '--yes', '--sealer-stopped']); expect(again.status, again.out).toBe(0); expect(again.report?.rewritten).toBe(0); expect(again.report?.failures).toBe(0); From 65a5d7dcb676ca89ad7f054bce4c2fc51d43b385 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:36:06 +0000 Subject: [PATCH 12/16] fix(plugin-audit): address review 7205485052 on the sealed expiry - S4 (seat ruling, option 3): a tenant's own window applies to a chain only where the windows are set on the chain column; every other chain takes the longest window configured. No row is read to pick a window. Every sentence stating the rule says so, with its cost: on an object whose windows sit on another column, a shorter tenant window has no effect on its sealed rows. - An expiry drops a seed only when it is the secret sealed under that checkpoint's own coordinate. - The resumed range is read a page at a time; the chain walk never takes a row with no chain_key as its key. - n9, n10, and the jsdoc of the stored-expiry read. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt --- .changeset/31908-p4c-sealed-expiry.md | 2 +- content/docs/data-modeling/objects.mdx | 16 +- content/docs/references/data/object.mdx | 4 +- .../src/lifecycle/lifecycle-service.ts | 32 ++-- .../audit-seal-expiry-admission.test.ts | 20 ++- .../audit-seal-expiry-window.test.ts | 68 +++---- .../plugin-audit/src/audit-seal/expiry.ts | 167 +++++++----------- .../plugin-audit/src/audit-seal/sealer.ts | 15 +- .../plugin-audit/src/audit-seal/signer.ts | 21 ++- .../plugin-audit/src/audit-seal/verifier.ts | 6 +- packages/spec/src/data/object.zod.ts | 6 +- 11 files changed, 168 insertions(+), 189 deletions(-) diff --git a/.changeset/31908-p4c-sealed-expiry.md b/.changeset/31908-p4c-sealed-expiry.md index c33a4c7c8b8..2665a9bfab5 100644 --- a/.changeset/31908-p4c-sealed-expiry.md +++ b/.changeset/31908-p4c-sealed-expiry.md @@ -29,7 +29,7 @@ ADR-0154 D8 and D10 (#31908, slice P4c, the last one). - **Sealed rows leave only by whole checkpoints.** The LifecycleService no longer deletes a row of an object that declares `lifecycle.seal` by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerExpiryPrefix`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). - **`os migrate audit-* --apply` on SQLite or Turso now needs `--sealer-stopped` for the audit log.** The rule 18.6.0 set for a sealed object now holds on every deployment, since `sys_audit_log` is one: stop every server that seals the database, then run with the flag. That includes the `os migrate audit-side-copies --apply` an upgrade from 18.4.0 or earlier runs. Postgres and MySQL take the audit seal lock, and a dry run is unchanged. - **No sealer, no deletion.** While no sealed expiry is registered (an `AuditPlugin` with no crypto provider, a one-shot boot), a sealed object's rows past their policy are kept, the archive copy still runs, the sweep reports `seal-expiry-pending`, and the lifecycle service says so once at `warn`; such a host keeps `sys_audit_log` past `archive.keep`, and its sealer reports the missing provider hourly at `error`. An archive store with no `bulkDelete` is never planned (`seal-delete-unsupported`), so no amendment is signed over rows it could not delete. A chain whose first remaining checkpoint does not follow its last expiry (a checkpoint removed outside the platform), or whose next checkpoint does not verify under a trusted key, is not expired past that point, and the sealer says so. An expiry acts only on the chain's own checkpoints and amendments, linked in order; a stopped expiry is resumed only over checkpoints that also each verify under a trusted key and run on to the amendment's last sequence and digest; otherwise nothing in its range is deleted, and the sealer says so. The verifier holds an expiry it honours to the same. An expiry deletes rows for good: a deleted row cannot be restored from the ledger. -- **A tenant-scoped retention override applies to the rows its organization owns.** The lifecycle service hands each tenant's window, through the same floors, to the sealed expiry (`LifecycleExpiryPrefixRequest.tenants`), with the column the windows are set on (`LifecycleExpiryPrefixRequest.tenantColumn`), which need not be the chain column. A chain expires under the longest window among the organizations that own its rows by that column (read from the hot store, then the archive), the chain of rows about no organization under the longest window configured, and its amendment signs that value, so no row expires under a window shorter than the one set for it. +- **A tenant-scoped retention override applies to its organization's chain where it is set on the chain column.** The lifecycle service hands each tenant's window, through the same floors, to the sealed expiry (`LifecycleExpiryPrefixRequest.tenants`), with the column the windows are set on (`LifecycleExpiryPrefixRequest.tenantColumn`). Where that is the object's chain column, an organization's chain expires under its own window and its amendment signs that value. Every other chain expires under the longest window configured: the chain of rows about no organization, and every chain of an object whose windows are set on another column than its chain column, which may hold rows of several organizations. On such an object a shorter tenant window has no effect on its sealed rows: they are kept to the longest. No row expires under a window shorter than one set for it. - **A fully expired chain continues.** Its next checkpoint chains onto the expiry: sequence after the expiry's last, linked to its `last_removed_digest`. - **`os audit verify` stays loud for a chain a fault left behind** (seat ruling 6885452378, ADR-0154 D3 as amended): a window that starts at or before the newest window a trusted `window` checkpoint names is sealed, so a row there that no checkpoint holds reads `late` and unsealed, and the check fails. - **The verify harness hands its crypto provider to `AuditPlugin`.** `bootStack` gives an `AuditPlugin` it mounts (an `extraPlugins` entry, a stack `plugins` entry, or the provider `requires: ['audit']` constructs) the same `harnessCryptoProvider()` instance that settings and the engine get, never a bare `LocalCryptoProvider`; an instance composed with its own provider keeps it. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 38edb5f6421..0fd584e69e3 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -283,13 +283,15 @@ it is sealed on every deployment whose `AuditPlugin` has a crypto provider. missing. The window is counted to the start of a UTC day, so a row can stay up to a day past it, and at most 10,000 such rows leave per object per sweep, so a backlog drains over several sweeps; once it has, a chain gains at most - one expiry amendment a day. A tenant-scoped retention window is matched to - each row by the column it is set on (`organization_id`), which need not be - the chain column (`tenant_id`, or `seal.chainField`): a chain expires under - the longest window among the organizations whose rows it holds, and the - chain of rows about no organization under the longest window configured, so - no row leaves before the window set for it. While no sealer is running (no - crypto provider), the sweeper keeps them and says so once. + one expiry amendment a day. A tenant-scoped retention window applies to + that organization's chain only where it is set on the chain column + (`tenant_id`, or `seal.chainField`). Every other chain keeps its rows to the + longest window configured: the chain of rows about no organization, and + every chain of an object whose windows are set on another column (an + `organization_id` beside a declared `tenant_id`), so on such an object a + shorter tenant window has no effect on its sealed rows. No row leaves before + the window set for it. While no sealer is running (no crypto provider), the + sweeper keeps them and says so once. - Sealing needs a crypto provider, which the host passes to `AuditPlugin` as `cryptoProvider`. `os serve` passes the one it seals every secret with; an app that puts its own `AuditPlugin` in `plugins` passes one itself. Without diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 8178f180876..8da24017ae2 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -82,7 +82,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped retention window is matched to each row by the column it is set on: a chain expires under the longest window among the organizations whose rows it holds, and the chain of rows about no organization under the longest window set, so no row leaves before its own window. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped retention window set on the chain column applies to that organization's chain; every other chain (the chain of rows about no organization, and every chain of an object whose windows are set on another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Lifecycle.retention` @@ -384,7 +384,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped retention window is matched to each row by the column it is set on: a chain expires under the longest window among the organizations whose rows it holds, and the chain of rows about no organization under the longest window set, so no row leaves before its own window. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped retention window set on the chain column applies to that organization's chain; every other chain (the chain of rows about no organization, and every chain of an object whose windows are set on another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Object.activityMilestones[number]` diff --git a/packages/objectql/src/lifecycle/lifecycle-service.ts b/packages/objectql/src/lifecycle/lifecycle-service.ts index 30983c40fc3..6772387098a 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.ts @@ -538,23 +538,23 @@ export interface LifecycleExpiryPrefixRequest { /** * The tenant-scoped windows of this policy (`retention_overrides` at tenant * scope), each through the same floors, in place of {@link policyValue} - * and {@link cutoff} for the rows that organization owns by - * {@link tenantColumn}: a chain expires under the longest window among the - * owners of its rows (an owner with none of its own under the global one), - * and a chain of no one organization (the deployment chain) under the - * longest of all of them and the global one, so no chain ever expires under - * a window shorter than one configured for a row in it. Absent when no - * tenant overrides the window. + * and {@link cutoff}. Where {@link tenantColumn} is the object's chain + * column, an organization's chain expires under its own organization's + * window (or the global one). Any other chain — the deployment chain, or + * every chain of an object whose windows sit on another column, which may + * hold rows of several organizations — expires under the longest of all of + * them and the global one, so no chain ever expires under a window shorter + * than one configured for a row in it. Absent when no tenant overrides the + * window. */ readonly tenants?: ReadonlyArray<{ readonly tenantId: string; readonly policyValue: string; readonly cutoff: string }>; /** * The column {@link tenants} are configured on — the partition `reap()` * uses (`organization_id`, or an attribution column), which need not be - * the object's chain column. Each row is matched to a window by this - * column: a chain expires under the longest window among the owners of the - * rows it holds, the chain of rows about no organization under the longest - * window of all, so no chain is shorter than a window set for a row in it. - * Present exactly when `tenants` is. + * the object's chain column. Only where it is does a tenant's own window + * apply to a chain; elsewhere every chain takes the longest (see + * {@link tenants}), and a shorter tenant window has no effect on that + * object's sealed rows. Present exactly when `tenants` is. */ readonly tenantColumn?: string; } @@ -1686,10 +1686,10 @@ export class LifecycleService { * A settings override of the window applies as on any object, through the * same floors, and the value applied is the one the amendment signs. A * tenant-scoped override travels as {@link LifecycleExpiryPrefixRequest.tenants}, - * with the column {@link tenantWindowsFor} partitions on: a chain expires - * under the longest window among the owners, by that column, of the rows it - * holds (the chain of rows about no organization under the longest of all), - * and each chain's amendment signs the window it expired under. + * with the column {@link tenantWindowsFor} partitions on: where that is the + * chain column an organization's chain expires under its own window, any + * other chain under the longest, and each chain's amendment signs the + * window it expired under. */ private async reapSealed( engine: LifecycleEngineLike, diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-admission.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-admission.test.ts index 03c45b75093..88295c0ea01 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-admission.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-admission.test.ts @@ -127,7 +127,7 @@ describe('a fresh expiry takes only checkpoints bound to the chain, each linked s.checkpoints().push({ ...s.checkpoint('org:org_b', 0), id: 'misfiled', chain_key: 'org:aaa' }); const runs = await s.expireNow(); expect(chainsOf(runs)).toEqual(['org:org_a', 'org:org_b']); - expect(s.warned(/chain 'org:aaa' is NOT expired: the checkpoint 0 stored under it is signed for another object or organization/)).toBe(1); + expect(s.warned(/chain 'org:aaa' is NOT expired: the checkpoint 0 stored under it is signed for another organization/)).toBe(1); }); it('a chain whose checkpoints do not link one to the next is not expired at all', async () => { @@ -253,3 +253,21 @@ describe('the sealer\'s chain head follows only an admitted expiry bound to the expect(s.bodyOf('org:org_a', 3)).toMatchObject({ row_ids: ['a3'], previous_digest: last }); }); }); + +describe('an expiry removes only the seed sealed under each checkpoint\'s own coordinate (ADR-0154 D2, D8)', () => { + it('a checkpoint whose seed handle names another secret removes nothing but its own row', async () => { + const s = await sealedLedger(); + const secrets = () => s.store.hot.table('sys_secret'); + const keyHalf = secrets().find((r) => r.namespace === 'sys_audit_signing_key')!; + const ownSeed = String(s.checkpoint('org:org_a', 1).seed_handle); + // The chain's last checkpoint, so nothing that links to it changes. + s.put('org:org_a', 2, await s.resigned(s.checkpoint('org:org_a', 2), { seed_handle: String(keyHalf.id) })); + const runs = await s.expireNow(); + const run = runs.find((r) => r.chain === 'org:org_a')!; + expect(run.rowIds).toEqual(['a0', 'a1', 'a2']); + await run.complete(); + expect(secrets().some((r) => r.id === keyHalf.id)).toBe(true); + expect(secrets().some((r) => r.id === ownSeed)).toBe(false); + expect(s.checkpoints().filter((r) => r.chain_key === 'org:org_a')).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts index 3a679afa8f7..7e663da9d72 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-expiry-window.test.ts @@ -11,9 +11,8 @@ import { LocalCheckpointSigner } from './signer.js'; * ADR-0154 D8, seat ruling on review 7198128323 S1: a tenant-scoped retention * window applies to its organization's chain, and no chain expires under a * window shorter than one configured for its rows; review 7202871622 S4: a - * window is matched to each row by the column it is configured on, which need - * not be the chain column: a chain expires under the longest window among the - * owners of its rows, the deployment chain under the longest of all. + * tenant's own window applies only where the windows are set on the chain + * column; every other chain, the deployment chain included, takes the longest. */ const DAY = 24 * 60 * 60 * 1000; @@ -48,36 +47,22 @@ describe('windowOf — the window each chain of a sealed object expires under', .toEqual({ cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }); }); - it('where the windows are configured on another column than the chain column, a chain whose owners are not read takes the longest', () => { + it('where the windows are configured on another column than the chain column, every chain takes the longest', () => { + // A ledger chained on `tenant_id` whose windows are configured on `organization_id`: a chain may hold rows of + // several organizations, and the chain key names none of them, so no row is read to pick one. const other = { ...request, tenantColumn: 'organization_id' }; for (const key of ['org:org_short', 'org:org_long', 'org:org_plain', 'deployment']) { expect(windowOf(other, key, 'tenant_id')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 400 * DAY), policyValue: '400d' }); } }); - it('where the windows are configured on another column, a chain takes the longest window among the owners of its rows', () => { - // A ledger chained on `tenant_id` whose windows are configured on `organization_id`: the chain key names no owner. - const other = { ...request, tenantColumn: 'organization_id' }; - const short = { cutoffMs: auditExpiryCutoff(NOW - 10 * DAY), policyValue: '10d' }; - const long = { cutoffMs: auditExpiryCutoff(NOW - 400 * DAY), policyValue: '400d' }; - const global = { cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }; - expect(windowOf(other, 'org:org_long', 'tenant_id', ['org_short'])).toEqual(short); - expect(windowOf(other, 'org:org_short', 'tenant_id', ['org_short', 'org_long'])).toEqual(long); - expect(windowOf(other, 'org:org_short', 'tenant_id', ['org_short', 'org_plain'])).toEqual(global); - expect(windowOf(other, 'org:org_short', 'tenant_id', ['org_short', null])).toEqual(global); - // A row that could not be read may be anyone's. - expect(windowOf(other, 'org:org_short', 'tenant_id', ['org_short', undefined])).toEqual(long); - // The deployment chain takes the longest of all, whoever owns its rows. - expect(windowOf(other, 'deployment', 'tenant_id', ['org_short'])).toEqual(long); - }); - it('with no tenant window every chain takes the global one', () => { const { tenants: _, ...plain } = request; expect(windowOf(plain, 'org:org_long', 'tenant_id')).toEqual({ cutoffMs: auditExpiryCutoff(NOW - 30 * DAY), policyValue: '30d' }); }); }); -describe('a ledger chained on `tenant_id` beside an injected `organization_id`: each row expires under its owner\'s window (review 7202871622 S4)', () => { +describe('a ledger chained on `tenant_id` beside an injected `organization_id` (review 7202871622 S4)', () => { const H = 60 * 60 * 1000; const DAY0 = Date.UTC(2026, 10, 10); const hour = (h: number, m: number) => new Date(DAY0 + h * H + m * 60_000).toISOString(); @@ -92,33 +77,31 @@ describe('a ledger chained on `tenant_id` beside an injected `organization_id`: const entry = (id: string, created: string, tenant: string | null, organization: string) => ({ id, created_at: created, tenant_id: tenant, organization_id: organization, new_value: `{"v":"${id}"}` }); - /** Seal the four rows at 12:30, move `archived` to the archive, and expire 60 days on: org_short 10d, org_long 400d. */ - const expireShape = async (archived: readonly string[] = []) => { - const ledger = archived.length > 0 ? { ...LEDGER, lifecycle: { ...LEDGER.lifecycle, archive: { after: '30d', to: 'archive' } } } : LEDGER; - const store = memoryEngine([ledger, { name: 'sys_audit_amendment', fields: {} }] as never); + /** + * Seal the four rows at 12:30, then expire 60 days on with the windows set on `tenantColumn`: global 20d, + * org_short 10d, org_long 100d. Every row is 60 days old: past 20d and 10d, within 100d. + */ + const expireShape = async (tenantColumn: string) => { + const store = memoryEngine([LEDGER, { name: 'sys_audit_amendment', fields: {} }] as never); const crypto = bindingCrypto(); const signer = new LocalCheckpointSigner({ engine: store.engine, crypto }); const clock = { now: DAY0 + 12 * H + 30 * 60_000 }; const sealer = new AuditSealer({ engine: store.engine, crypto, signer: () => signer, logger: recordingLogger(), now: () => clock.now }); store.hot.table('policy_change_log').push( entry('s0', hour(8, 10), 'org_short', 'org_short'), // chain org:org_short, sequence 0 - entry('s1', hour(9, 10), 'org_short', 'org_long'), // chain org:org_short, sequence 1: org_long's row - entry('l0', hour(8, 20), 'org_long', 'org_short'), // chain org:org_long: org_short's row + entry('s1', hour(9, 10), 'org_short', 'org_long'), // chain org:org_short, sequence 1: organization_id differs + entry('l0', hour(8, 20), 'org_long', 'org_short'), // chain org:org_long: organization_id differs entry('d0', hour(8, 30), null, 'org_short'), // the deployment chain ); await sealer.runPass(); - for (const id of archived) { - const hot = store.hot.table('policy_change_log'); - store.archive.table('policy_change_log').push(...hot.splice(hot.findIndex((r) => r.id === id), 1)); - } clock.now = DAY0 + 60 * DAY; const since = (days: number) => new Date(clock.now - days * DAY).toISOString(); const runs = await sealer.expire({ - object: 'policy_change_log', policy: 'retention.maxAge', policyValue: '90d', cutoff: since(90), - tenantColumn: 'organization_id', + object: 'policy_change_log', policy: 'retention.maxAge', policyValue: '20d', cutoff: since(20), + tenantColumn, tenants: [ { tenantId: 'org_short', policyValue: '10d', cutoff: since(10) }, - { tenantId: 'org_long', policyValue: '400d', cutoff: since(400) }, + { tenantId: 'org_long', policyValue: '100d', cutoff: since(100) }, ], }); const signed = store.hot.table('sys_audit_amendment').map((row) => amendmentBodyFromRow(row) as ExpiryAmendmentBody); @@ -128,15 +111,16 @@ describe('a ledger chained on `tenant_id` beside an injected `organization_id`: }; }; - it('a chain takes the longest window among the organizations that own its rows, whatever its chain key names', async () => { - const { runs, signed } = await expireShape(); - expect(runs).toEqual({ 'org:org_short': ['s0'], 'org:org_long': ['l0'] }); - expect(signed).toEqual({ org_short: [0, 0, '10d'], org_long: [0, 0, '10d'] }); + it('windows set on the chain column: each organization\'s chain expires under its own window, the deployment chain under the longest', async () => { + const { runs, signed } = await expireShape('tenant_id'); + expect(runs).toEqual({ 'org:org_short': ['s0', 's1'] }); + expect(signed).toEqual({ org_short: [0, 1, '10d'] }); }); - it('the owner of a row already archived is read from the archive', async () => { - const { runs, signed } = await expireShape(['l0']); - expect(runs).toEqual({ 'org:org_short': ['s0'], 'org:org_long': ['l0'] }); - expect(signed).toEqual({ org_short: [0, 0, '10d'], org_long: [0, 0, '10d'] }); + it('windows set on another column than the chain column: every chain keeps its rows to the longest window', async () => { + // organization_id is not what the chains are keyed by, so a shorter window set on it has no effect here. + const { runs, signed } = await expireShape('organization_id'); + expect(runs).toEqual({}); + expect(signed).toEqual({}); }); }); diff --git a/packages/plugins/plugin-audit/src/audit-seal/expiry.ts b/packages/plugins/plugin-audit/src/audit-seal/expiry.ts index d9174881ed2..aef19e9f236 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/expiry.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/expiry.ts @@ -4,7 +4,7 @@ import { randomUUID } from 'node:crypto'; import type { IAuditCheckpointSigner, IAuditCheckpointSink } from '@objectstack/spec/contracts'; import { isMissingTableError } from '@objectstack/types'; import { canonicalDatetime } from './canonical.js'; -import { AUDIT_AMENDMENT_OBJECT, AUDIT_CHECKPOINT_OBJECT } from './seed.js'; +import { AUDIT_AMENDMENT_OBJECT, AUDIT_CHECKPOINT_OBJECT, checkpointSeedContext } from './seed.js'; import { amendmentBodyFromRow, amendmentRow, @@ -65,8 +65,6 @@ const DAY_MS = 24 * 60 * 60 * 1000; const PAGE_SIZE = 20; /** Stored expiry amendments read per page while looking for a chain's newest admitted one. */ const AMENDMENT_PAGE_SIZE = 50; -/** Row ids per read of their owners (S4). */ -const OWNER_READ_BATCH = 500; const MAX_SIGN_ATTEMPTS = 3; const NO_KEY_YET = 'unknown'; @@ -83,7 +81,7 @@ export interface AuditExpiryRequest { readonly policy: string; readonly policyValue: string; readonly cutoff: string; - /** Tenant-scoped windows, each for the rows its organization owns by {@link tenantColumn} (see {@link windowOf}). */ + /** Tenant-scoped windows, set on {@link tenantColumn} (see {@link windowOf}). */ readonly tenants?: ReadonlyArray<{ readonly tenantId: string; readonly policyValue: string; readonly cutoff: string }>; /** The column {@link tenants} are configured on, which need not be the chain column. */ readonly tenantColumn?: string; @@ -103,45 +101,29 @@ const cutoffOf = (cutoff: string): number => { /** * The window chain `key` expires under, for an object chained on `chainField`, - * never shorter than the window configured for any row it holds (seat ruling - * on review 7202871622 S4). + * never shorter than a window configured for any row it holds (seat rulings on + * reviews 7198128323 S1 and 7202871622 S4). * * - No tenant window: the global one. - * - Not an organization's chain (the deployment chain): the longest of the - * global window and every tenant window. - * - The tenant windows are configured on the chain column itself: the chain - * holds its organization's rows alone, so it takes that organization's - * window, else the global one. - * - Otherwise a chain may hold rows several organizations own, by the column - * the windows are configured on. `owners` are those owners, one per row - * (`null` for a row about no organization, `undefined` for a row that could - * not be read): the chain takes the longest window among them, an owner - * with no window of its own taking the global one and an unread row the - * longest of all. Without `owners`, the longest of all. + * - The tenant windows are configured on the chain column itself: an + * organization's chain holds its organization's rows alone, so it takes + * that organization's window, else the global one. + * - Any other chain — the deployment chain, or every chain of an object whose + * windows are configured on another column than its chain column, which may + * hold rows of several organizations — takes the longest of the global + * window and every tenant window. No row is read to decide it. */ -export function windowOf( - request: AuditExpiryRequest, - key: string, - chainField: string, - owners?: ReadonlyArray, -): ChainWindow { +export function windowOf(request: AuditExpiryRequest, key: string, chainField: string): ChainWindow { const global: ChainWindow = { cutoffMs: cutoffOf(request.cutoff), policyValue: request.policyValue }; const tenants = request.tenants ?? []; if (tenants.length === 0) return global; const windowOfTenant = (t: (typeof tenants)[number]): ChainWindow => ({ cutoffMs: cutoffOf(t.cutoff), policyValue: t.policyValue }); - // The longest window is the earliest cutoff. - const longest = (windows: readonly ChainWindow[]): ChainWindow => - windows.length === 0 ? global : windows.reduce((a, b) => (b.cutoffMs < a.cutoffMs ? b : a)); - const longestOfAll = longest([global, ...tenants.map(windowOfTenant)]); - if (!key.startsWith('org:')) return longestOfAll; - const ownerWindow = (owner: string | null): ChainWindow => { - const own = owner === null ? undefined : tenants.find((t) => t.tenantId === owner); + if (key.startsWith('org:') && request.tenantColumn === chainField) { + const own = tenants.find((t) => t.tenantId === key.slice('org:'.length)); return own ? windowOfTenant(own) : global; - }; - if (request.tenantColumn === chainField) return ownerWindow(key.slice('org:'.length)); - if (!owners) return longestOfAll; - if (owners.some((o) => o === undefined)) return longestOfAll; - return longest([...new Set(owners as ReadonlyArray)].map(ownerWindow)); + } + // The longest window is the earliest cutoff. + return tenants.map(windowOfTenant).reduce((a, b) => (b.cutoffMs < a.cutoffMs ? b : a), global); } /** One chain's planned expiry (`LifecycleExpiryPrefixRun`, `@objectstack/objectql`). */ @@ -157,8 +139,6 @@ export interface ObjectExpiryOptions { readonly object: string; /** The object's chain column (`lifecycle.seal.chainField`, default `tenant_id`). */ readonly chainField: string; - /** The object's `archive.to` datasource, if it has one: owners of archived rows are read there (S4). */ - readonly archive?: SealStorageDriver; readonly signer: IAuditCheckpointSigner & { activeKeyId?(): Promise }; readonly sink?: IAuditCheckpointSink; readonly trust: SigningKeyTrust; @@ -210,8 +190,13 @@ export class ObjectExpiry { this.drained = false; break; } - const where: Row = { sealed_object: this.object, window_end: { $lte: iso(cutoffMs) } }; - if (after !== undefined) where.chain_key = { $gt: after }; + // A row with no `chain_key` is no chain's: it never answers, so where a driver orders NULL first it + // cannot become the walk's key and skip the chains that sort before its spelling. + const where: Row = { + sealed_object: this.object, + window_end: { $lte: iso(cutoffMs) }, + chain_key: after === undefined ? { $null: false } : { $gt: after }, + }; const [candidate] = await this.find(this.checkpoints, AUDIT_CHECKPOINT_OBJECT, { where, orderBy: [{ field: 'chain_key', order: 'asc' }], @@ -252,20 +237,22 @@ export class ObjectExpiry { } /** - * Whether a stored body belongs where it is stored: its signed object is this - * one and its signed organization is chain `key`. The row's `sealed_object` - * and `chain_key` columns are not signed; the body is. + * Whether a stored body belongs to chain `key`: its signed organization is + * that chain's. The row's `chain_key` column is not part of the signed body, + * so it is checked here. Its `sealed_object` column is: the body is read + * from it, every read here is narrowed to this object by it, and a + * signature that verifies covers it, so it needs no second compare. */ - private bound(key: string, body: { readonly sealed_object: string; readonly tenant_id: string | null }): boolean { - return body.sealed_object === this.object && chainKeyOf(body.tenant_id) === key; + private bound(key: string, body: { readonly tenant_id: string | null }): boolean { + return chainKeyOf(body.tenant_id) === key; } - /** A chain holding a row that is not bound to it is not expired at all, and that is said once. */ + /** A chain where an expiry reads, stored under it, a checkpoint or expiry signed for another chain is not expired at all, and that is said once. */ private refuseUnbound(key: string, what: string): null { this.options.say( `expiry:unbound:${this.object}:${key}`, `AuditSealer: '${this.object}' chain '${key}' is NOT expired: ${what} stored under it is signed for another ` + - 'object or organization. Nothing in the chain is deleted; os audit verify reports it.', + 'organization. Nothing in the chain is deleted; os audit verify reports it.', ); return null; } @@ -281,10 +268,12 @@ export class ObjectExpiry { } /** - * The chain's last expiry that is admitted — bound to the chain and signed - * under a trusted key — if any, walking every stored one newest first. A - * stored expiry under the chain that is bound elsewhere answers `null`: the - * chain is not expired at all. + * The chain's newest expiry amendment that is admitted — signed for this + * chain and under a trusted key — or `undefined` when none is. Stored ones + * are read newest first (by `last_sequence`), a page at a time, until one is + * admitted: a malformed or untrusted one is passed over, and the first one + * signed for another chain answers `null` instead, so the chain is not + * expired at all. */ private async latestExpiry(key: string): Promise { if (!this.amendments) return undefined; @@ -310,28 +299,6 @@ export class ObjectExpiry { } } - /** - * The owners of `ids` by `column`, one per id, read from the object's hot - * store and then its archive for the ids the hot store does not hold - * (`undefined` for a row neither holds). - */ - private async ownersOf(ids: readonly string[], column: string): Promise> { - const byId = new Map(); - const hot = this.options.engine.getDriverForObject(this.object); - for (const store of [hot, this.options.archive]) { - if (!store) continue; - const unread = ids.filter((id) => !byId.has(id)); - for (let at = 0; at < unread.length; at += OWNER_READ_BATCH) { - const batch = unread.slice(at, at + OWNER_READ_BATCH); - for (const row of await this.find(store, this.object, { where: { id: { $in: batch } }, limit: batch.length })) { - const owner = row[column]; - byId.set(String(row.id), owner === null || owner === undefined || owner === '' ? null : String(owner)); - } - } - } - return ids.map((id) => (byId.has(id) ? byId.get(id)! : undefined)); - } - private async chainRun( key: string, budget: number, @@ -357,22 +324,28 @@ export class ObjectExpiry { if (first.sequence < latest.first_sequence) return this.refuseResume(key, latest, first.sequence); const taken: Taken[] = []; let next = first.sequence; - for (const stored of await this.find(this.checkpoints, AUDIT_CHECKPOINT_OBJECT, { - where: { sealed_object: this.object, chain_key: key, sequence: { $lte: latest.last_sequence } }, - // Ascending, so complete() removes the newest checkpoint last (see runOf). - orderBy: [{ field: 'sequence', order: 'asc' }], - })) { - const body = this.parse(key, stored); - if (!body) return null; - if (!this.bound(key, body)) return this.refuseUnbound(key, `the checkpoint ${body.sequence}`); - if (body.sequence !== next) return this.refuseResume(key, latest, body.sequence); - const previous = taken[taken.length - 1]; - if (previous && body.previous_digest !== checkpointDigest(previous.body)) return this.refuseResume(key, latest, body.sequence); - if ((await this.options.trust.signature(body.signing_key_id, signedBodyBytes(body), stored.signature)) !== 'ok') { - return this.refuseResume(key, latest, body.sequence); + // A page at a time, from the next sequence: each page continues where the one before ended. + resume: for (;;) { + const page = await this.find(this.checkpoints, AUDIT_CHECKPOINT_OBJECT, { + where: { sealed_object: this.object, chain_key: key, sequence: { $gte: next, $lte: latest.last_sequence } }, + // Ascending, so complete() removes the newest checkpoint last (see runOf). + orderBy: [{ field: 'sequence', order: 'asc' }], + limit: PAGE_SIZE, + }); + for (const stored of page) { + const body = this.parse(key, stored); + if (!body) return null; + if (!this.bound(key, body)) return this.refuseUnbound(key, `the checkpoint ${body.sequence}`); + if (body.sequence !== next) return this.refuseResume(key, latest, body.sequence); + const previous = taken[taken.length - 1]; + if (previous && body.previous_digest !== checkpointDigest(previous.body)) return this.refuseResume(key, latest, body.sequence); + if ((await this.options.trust.signature(body.signing_key_id, signedBodyBytes(body), stored.signature)) !== 'ok') { + return this.refuseResume(key, latest, body.sequence); + } + taken.push({ stored, body }); + next += 1; } - taken.push({ stored, body }); - next += 1; + if (page.length < PAGE_SIZE) break resume; } if (taken.length === 0) return null; const last = taken[taken.length - 1].body; @@ -396,12 +369,7 @@ export class ObjectExpiry { // The first links to the last expiry's last removed checkpoint (sequence 0 links to nothing: `parse` holds it). if (latest && first.previous_digest !== latest.last_removed_digest) return this.refuseUnlinked(key, first.sequence); - // Where a chain may hold rows several organizations own, each checkpoint's owners decide its window (S4). - const byOwners = - key.startsWith('org:') && (request.tenants?.length ?? 0) > 0 && request.tenantColumn !== undefined && - request.tenantColumn !== this.options.chainField; - const owners: Array = []; - let window = windowOf(request, key, this.options.chainField, byOwners ? [] : undefined); + const window = windowOf(request, key, this.options.chainField); const taken: Taken[] = []; let rows = 0; @@ -419,12 +387,7 @@ export class ObjectExpiry { if (!this.bound(key, body)) return this.refuseUnbound(key, `the checkpoint ${body.sequence}`); const previous = taken[taken.length - 1]; if (previous && body.previous_digest !== checkpointDigest(previous.body)) return this.refuseUnlinked(key, body.sequence); - let candidate = window; - if (byOwners) { - owners.push(...(await this.ownersOf(body.row_ids, request.tenantColumn!))); - candidate = windowOf(request, key, this.options.chainField, owners); - } - if (Date.parse(canonicalDatetime(body.window_end, 'window_end')) > candidate.cutoffMs) break walk; + if (Date.parse(canonicalDatetime(body.window_end, 'window_end')) > window.cutoffMs) break walk; if (taken.length > 0 && rows + body.row_ids.length > budget) { cut = true; break walk; @@ -438,8 +401,6 @@ export class ObjectExpiry { ); break walk; } - // The window only lengthens as owners join, and windows end in order: every checkpoint taken ended by it. - window = candidate; taken.push({ stored, body }); rows += body.row_ids.length; next += 1; @@ -534,7 +495,9 @@ export class ObjectExpiry { // Oldest first, each seed before its checkpoint: a stop part way leaves no seed whose checkpoint is gone, // and the checkpoints left are this range's, which the next sweep resumes. for (const { stored, body } of taken) { - await dropAuditSealSecret(engine, body.seed_handle); + // Only the seed sealed under this checkpoint's own coordinate: a handle naming any other secret drops nothing. + const { namespace, key: coordinate } = checkpointSeedContext(body.sealed_object, body.tenant_id, body.sequence); + await dropAuditSealSecret(engine, body.seed_handle, { namespace, key: coordinate }); await checkpoints.delete!(AUDIT_CHECKPOINT_OBJECT, String(stored.id)); } }, diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index 2d93151da2c..41358239968 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -569,17 +569,10 @@ export class AuditSealer { const session = await trySealPassLocks(this.options.engine, [plan.name]); if (session.held) return []; try { - let archive: SealStorageDriver | undefined; - try { - archive = plan.archiveTo ? this.options.engine.datasource?.(plan.archiveTo) : undefined; - } catch { - archive = undefined; - } const expiry = new ObjectExpiry({ engine: this.options.engine, object: plan.name, chainField: plan.chainField, - ...(archive ? { archive } : {}), signer, ...(seams.sink ? { sink: seams.sink } : {}), trust: new SigningKeyTrust(anchoredPublicKeyOf(this.options.engine, crypto, signer)), @@ -953,9 +946,8 @@ class ObjectPass { /** * D8: the stored `expiry` amendment of this object (narrowed by `where`) that - * is highest by `field` among those admitted — bound where it is stored (its - * signed object is this one and its signed organization is the chain it is - * stored under) and signed under a trusted key (D6) — or `undefined`. Every + * is highest by `field` among those admitted — signed for the chain it is + * stored under and under a trusted key (D6) — or `undefined`. Every * stored one is walked, page by page, so no run of rows that are not admitted * hides an admitted one; a row that is not admitted is passed over, so a head * or a floor never follows one. A malformed one is a chain-local fault of its @@ -986,7 +978,8 @@ class ObjectPass { throw new ChainFault(String(row.chain_key), err); } if (body.kind !== 'expiry') continue; - if (body.sealed_object !== this.plan.name || chainKeyOf(body.tenant_id) !== String(row.chain_key)) continue; + // Signed for the chain it is stored under (its `sealed_object` is signed, and fixed by the read). + if (chainKeyOf(body.tenant_id) !== String(row.chain_key)) continue; if ((await this.trust().signature(body.signing_key_id, signedBodyBytes(body), row.signature)) === 'ok') return body; } if (rows.length < LAST_EXPIRY_PAGE) return undefined; diff --git a/packages/plugins/plugin-audit/src/audit-seal/signer.ts b/packages/plugins/plugin-audit/src/audit-seal/signer.ts index c0450775981..b1345d65ea1 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/signer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/signer.ts @@ -70,10 +70,25 @@ export async function writeAuditSealSecret(engine: SealStorageEngine, handle: Cr }); } -/** Remove a `sys_secret` row this producer wrote and no holder came to name. Best-effort; never throws. */ -export async function dropAuditSealSecret(engine: SealStorageEngine, id: string): Promise { +/** + * Remove a `sys_secret` row this producer wrote and no holder came to name, or + * whose holder is gone. Best-effort; never throws. With `expected`, the row is + * removed only when it is the secret sealed under that context (its + * `namespace` and `key`): a handle that names any other row removes nothing. + */ +export async function dropAuditSealSecret( + engine: SealStorageEngine, + id: string, + expected?: Pick, +): Promise { try { - await engine.getDriverForObject('sys_secret')?.delete?.('sys_secret', id); + const driver = engine.getDriverForObject('sys_secret'); + if (!driver?.delete) return; + if (expected) { + const [row] = await driver.find('sys_secret', { where: { id }, limit: 1 }); + if (!row || row.namespace !== expected.namespace || row.key !== expected.key) return; + } + await driver.delete('sys_secret', id); } catch { /* an unreferenced audit_seal row is what `os secret orphans` reports */ } diff --git a/packages/plugins/plugin-audit/src/audit-seal/verifier.ts b/packages/plugins/plugin-audit/src/audit-seal/verifier.ts index 5fd503d062f..76afa750f10 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/verifier.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/verifier.ts @@ -88,7 +88,11 @@ export type AuditChainFaultKind = | 'gap' /** A `previous_digest` that is not the digest of what precedes it. */ | 'link' - /** An expiry amendment that is not honoured (D8). */ + /** + * An expiry amendment that is not honoured (D8), or a checkpoint inside an + * honoured range whose own window ends after the range's `covered_to` + * (its rows are then judged, not read `expired`). + */ | 'expiry' /** Stored leaf hashes that do not rebuild the signed root. */ | 'leaf_hashes' diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index f7ee84025d6..d4fdc0ca6a9 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1177,9 +1177,9 @@ export const LifecycleSchema = lazySchema(() => strictObject({ "`onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their " + '`retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry ' + 'amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped ' + - 'retention window is matched to each row by the column it is set on: a chain expires under the longest ' + - 'window among the organizations whose rows it holds, and the chain of rows about no organization under ' + - 'the longest window set, so no row leaves before its own window. The window is counted to the start of a ' + + "retention window set on the chain column applies to that organization's chain; every other chain (the " + + 'chain of rows about no organization, and every chain of an object whose windows are set on another ' + + 'column) keeps its rows to the longest window set. The window is counted to the start of a ' + 'UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a ' + 'backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto ' + 'provider seals nothing and reports that at error.', From 71bb12a931f8e3eed30c04164076de98d4e3a9f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 02:15:33 +0000 Subject: [PATCH 13/16] feat(plugin-audit): on a sealed object, a retention override cannot shorten the declared window AuditPlugin registers a retention floor for every object that declares lifecycle.seal and no archive, at its declared retention.maxAge and ttl.expireAfter, beside the sealed expiry, and again before every sealer pass so the floors follow the registry. A lifecycle service without retention floors is given no expiry. Docs say which column a tenant window is set on. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt --- .changeset/31908-p4c-sealed-expiry.md | 6 +- content/docs/data-modeling/objects.mdx | 23 ++- content/docs/references/data/object.mdx | 4 +- .../plugin-audit/src/audit-plugin.test.ts | 1 + .../plugins/plugin-audit/src/audit-plugin.ts | 47 ++++- .../audit-seal-retention-floor.test.ts | 161 ++++++++++++++++++ .../src/audit-seal/retention-floor.ts | 97 +++++++++++ .../plugin-audit/src/audit-seal/sealer.ts | 13 ++ packages/spec/src/data/object.zod.ts | 9 +- scripts/engine-double-contract.pinned.json | 5 + 10 files changed, 345 insertions(+), 21 deletions(-) create mode 100644 packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts create mode 100644 packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts diff --git a/.changeset/31908-p4c-sealed-expiry.md b/.changeset/31908-p4c-sealed-expiry.md index 2665a9bfab5..3f0f7f80ba4 100644 --- a/.changeset/31908-p4c-sealed-expiry.md +++ b/.changeset/31908-p4c-sealed-expiry.md @@ -7,7 +7,7 @@ feat(plugin-audit): the audit log is sealed by default, and sealed rows expire by whole checkpoints under a signed expiry amendment -Clause-②: yes (narrowing) — narrowed: because `sys_audit_log` now declares `lifecycle.seal` on every deployment, `os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies` with `--apply` refuse on SQLite or Turso without `--sealer-stopped`, and on Postgres or MySQL take the audit seal lock and refuse when a sealer pass still holds it after ten minutes, where 18.6.0 ran them unlocked on a deployment that sealed nothing; `os audit verify` exits 1 on a row in a window at or before the newest window a trusted `window` checkpoint names that no checkpoint holds (`late`, unsealed), where it read the window unsealed and exited 0; `os audit verify` refuses with `archive_not_connected` and exits 2 wherever the `archive` datasource is declared and not connected on its own boot, where 18.6.0 printed that nothing is sealed and exited 0; and `verifyAuditLedger` throws for `sys_audit_log` when the `archive` datasource it archives to is not connected and no `archive` is passed. This breaks the bound changeset `35c9a30` (#33675) set, "No object declares `lifecycle.seal` by default, so a deployment that did not opt in sees no change": this release is the one that opts every deployment in. Widened: `@objectstack/objectql` `LifecycleService.registerExpiryPrefix` and the types `LifecycleExpiryPrefix`, `LifecycleExpiryPrefixRequest` (with its `tenants` windows and `tenantColumn`), `LifecycleExpiryPrefixRun`; a sweep entry's `policy` gains `'expiry'` and `skipped[].reason` gains `seal-expiry-pending` and `seal-delete-unsupported`. +Clause-②: yes (narrowing) — narrowed: because `sys_audit_log` now declares `lifecycle.seal` on every deployment, `os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies` with `--apply` refuse on SQLite or Turso without `--sealer-stopped`, and on Postgres or MySQL take the audit seal lock and refuse when a sealer pass still holds it after ten minutes, where 18.6.0 ran them unlocked on a deployment that sealed nothing; `os audit verify` exits 1 on a row in a window at or before the newest window a trusted `window` checkpoint names that no checkpoint holds (`late`, unsealed), where it read the window unsealed and exited 0; `os audit verify` refuses with `archive_not_connected` and exits 2 wherever the `archive` datasource is declared and not connected on its own boot, where 18.6.0 printed that nothing is sealed and exited 0; `verifyAuditLedger` throws for `sys_audit_log` when the `archive` datasource it archives to is not connected and no `archive` is passed; and on an object that declares `lifecycle.seal`, a `lifecycle` settings override of `retention.maxAge` or `ttl.expireAfter` below the declared window, global or for one organization, is rejected and reported at `error`, and the declared window applies, where 18.6.0 applied it. This breaks the bound changeset `35c9a30` (#33675) set, "No object declares `lifecycle.seal` by default, so a deployment that did not opt in sees no change": this release is the one that opts every deployment in. Widened: `@objectstack/objectql` `LifecycleService.registerExpiryPrefix` and the types `LifecycleExpiryPrefix`, `LifecycleExpiryPrefixRequest` (with its `tenants` windows and `tenantColumn`), `LifecycleExpiryPrefixRun`; a sweep entry's `policy` gains `'expiry'` and `skipped[].reason` gains `seal-expiry-pending` and `seal-delete-unsupported`. Metadata-protocol: semantic — on an object that declares `lifecycle.seal`, the authored `retention.maxAge`, `ttl.expireAfter` and `archive.keep` no longer delete a row at its row cutoff: rows leave by whole checkpoints under a signed expiry amendment, counted to the start of a UTC day, at most 10,000 a sweep, and not at all while no sealer runs Skills-docs: follow-up owed — this claim's second PR (amendment 7193137455) rewrites `skills/objectstack-data/rules/lifecycle.md`, which still says the sweeper deletes sealed rows @@ -20,6 +20,7 @@ Skills-docs: follow-up owed — this claim's second PR (amendment 7193137455) re - **`os audit verify` exits 1** on a row it reads `late` and unsealed in a window another chain of the object already sealed. Fix: none is owed by the command; read the rows the report names (a chain a fault left behind), and run it again after the sealer's next pass. - **`os audit verify` exits 2** (`archive_not_connected`) where the `archive` datasource is declared and the command's boot does not connect it. Fix: declare the datasource with `autoConnect: true`, or make it reachable from where the command runs. - **`verifyAuditLedger`** (`@objectstack/plugin-audit`) throws for `sys_audit_log` when its `archive` datasource is not connected. Fix: pass `archive`, for example `archive: () => 'none'` where the deployment has no archive datasource. +- **On a sealed object, a retention override cannot shorten the declared window.** An override below it is rejected at every sweep, reported at `error` (`floorViolations` on the sweep report), and the declared window applies. Fix: remove the override or raise it to at least the declared window; to keep rows for less time, shorten the window the object declares. Every dry run is unchanged. A deployment's own objects that do not declare `lifecycle.seal` keep the row-cutoff retention they had. @@ -29,7 +30,8 @@ ADR-0154 D8 and D10 (#31908, slice P4c, the last one). - **Sealed rows leave only by whole checkpoints.** The LifecycleService no longer deletes a row of an object that declares `lifecycle.seal` by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerExpiryPrefix`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). - **`os migrate audit-* --apply` on SQLite or Turso now needs `--sealer-stopped` for the audit log.** The rule 18.6.0 set for a sealed object now holds on every deployment, since `sys_audit_log` is one: stop every server that seals the database, then run with the flag. That includes the `os migrate audit-side-copies --apply` an upgrade from 18.4.0 or earlier runs. Postgres and MySQL take the audit seal lock, and a dry run is unchanged. - **No sealer, no deletion.** While no sealed expiry is registered (an `AuditPlugin` with no crypto provider, a one-shot boot), a sealed object's rows past their policy are kept, the archive copy still runs, the sweep reports `seal-expiry-pending`, and the lifecycle service says so once at `warn`; such a host keeps `sys_audit_log` past `archive.keep`, and its sealer reports the missing provider hourly at `error`. An archive store with no `bulkDelete` is never planned (`seal-delete-unsupported`), so no amendment is signed over rows it could not delete. A chain whose first remaining checkpoint does not follow its last expiry (a checkpoint removed outside the platform), or whose next checkpoint does not verify under a trusted key, is not expired past that point, and the sealer says so. An expiry acts only on the chain's own checkpoints and amendments, linked in order; a stopped expiry is resumed only over checkpoints that also each verify under a trusted key and run on to the amendment's last sequence and digest; otherwise nothing in its range is deleted, and the sealer says so. The verifier holds an expiry it honours to the same. An expiry deletes rows for good: a deleted row cannot be restored from the ledger. -- **A tenant-scoped retention override applies to its organization's chain where it is set on the chain column.** The lifecycle service hands each tenant's window, through the same floors, to the sealed expiry (`LifecycleExpiryPrefixRequest.tenants`), with the column the windows are set on (`LifecycleExpiryPrefixRequest.tenantColumn`). Where that is the object's chain column, an organization's chain expires under its own window and its amendment signs that value. Every other chain expires under the longest window configured: the chain of rows about no organization, and every chain of an object whose windows are set on another column than its chain column, which may hold rows of several organizations. On such an object a shorter tenant window has no effect on its sealed rows: they are kept to the longest. No row expires under a window shorter than one set for it. +- **On a sealed object, a retention override cannot shorten the declared window.** `AuditPlugin` registers a retention floor (the mechanism the job queue uses for its idempotency window) for every object that declares `lifecycle.seal` and no `archive`, at its declared `retention.maxAge` and `ttl.expireAfter`, refreshed before every sealer pass so it follows the declaration. An override, global or for one organization, may lengthen the window; one below it is rejected and the declared window applies. `archive.keep` takes no override. A lifecycle service that takes a sealed expiry but no retention floors is given no expiry, so its sealed rows are kept, and the plugin says so at `error`. +- **A tenant-scoped retention override applies to its organization's chain where it is set on the chain column.** Tenant windows are set on the object's `organization_id` column, so this holds on an object chained by it (`seal.chainField: 'organization_id'`). The lifecycle service hands each tenant's window, through the same floors, to the sealed expiry (`LifecycleExpiryPrefixRequest.tenants`), with the column the windows are set on (`LifecycleExpiryPrefixRequest.tenantColumn`). Where that is the object's chain column, an organization's chain expires under its own window and its amendment signs that value. Every other chain expires under the longest window configured: the chain of rows about no organization, and every chain of an object whose windows are set on another column than its chain column, which may hold rows of several organizations. On such an object a shorter tenant window has no effect on its sealed rows: they are kept to the longest. No row expires under a window shorter than one set for it. - **A fully expired chain continues.** Its next checkpoint chains onto the expiry: sequence after the expiry's last, linked to its `last_removed_digest`. - **`os audit verify` stays loud for a chain a fault left behind** (seat ruling 6885452378, ADR-0154 D3 as amended): a window that starts at or before the newest window a trusted `window` checkpoint names is sealed, so a row there that no checkpoint holds reads `late` and unsealed, and the check fails. - **The verify harness hands its crypto provider to `AuditPlugin`.** `bootStack` gives an `AuditPlugin` it mounts (an `extraPlugins` entry, a stack `plugins` entry, or the provider `requires: ['audit']` constructs) the same `harnessCryptoProvider()` instance that settings and the engine get, never a bare `LocalCryptoProvider`; an instance composed with its own provider keeps it. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 0fd584e69e3..dd6de6b01ef 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -283,15 +283,20 @@ it is sealed on every deployment whose `AuditPlugin` has a crypto provider. missing. The window is counted to the start of a UTC day, so a row can stay up to a day past it, and at most 10,000 such rows leave per object per sweep, so a backlog drains over several sweeps; once it has, a chain gains at most - one expiry amendment a day. A tenant-scoped retention window applies to - that organization's chain only where it is set on the chain column - (`tenant_id`, or `seal.chainField`). Every other chain keeps its rows to the - longest window configured: the chain of rows about no organization, and - every chain of an object whose windows are set on another column (an - `organization_id` beside a declared `tenant_id`), so on such an object a - shorter tenant window has no effect on its sealed rows. No row leaves before - the window set for it. While no sealer is running (no crypto provider), the - sweeper keeps them and says so once. + one expiry amendment a day. On a sealed object, a retention override cannot + shorten the declared window: an override of `retention.maxAge` or + `ttl.expireAfter` in the `lifecycle` settings, global or for one + organization, may lengthen it, and one below the declared window is + rejected, reported at `error`, and the declared window applies + (`archive.keep` takes no override). A tenant-scoped window is set on the + object's `organization_id` column, so it applies to that organization's + chain only on an object chained by that column + (`seal.chainField: 'organization_id'`). Every other chain keeps its rows to + the longest window configured: the chain of rows about no organization, and + every chain of an object chained by another column (the default + `tenant_id`), which may hold rows of several organizations. No row leaves + before the window set for it. While no sealer is running (no crypto + provider), the sweeper keeps them and says so once. - Sealing needs a crypto provider, which the host passes to `AuditPlugin` as `cryptoProvider`. `os serve` passes the one it seals every secret with; an app that puts its own `AuditPlugin` in `plugins` passes one itself. Without diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 8da24017ae2..953f857e8bb 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -82,7 +82,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped retention window set on the chain column applies to that organization's chain; every other chain (the chain of rows about no organization, and every chain of an object whose windows are set on another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A retention override cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of rows about no organization, and every chain of an object chained by another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Lifecycle.retention` @@ -384,7 +384,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped retention window set on the chain column applies to that organization's chain; every other chain (the chain of rows about no organization, and every chain of an object whose windows are set on another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A retention override cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of rows about no organization, and every chain of an object chained by another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Object.activityMilestones[number]` diff --git a/packages/plugins/plugin-audit/src/audit-plugin.test.ts b/packages/plugins/plugin-audit/src/audit-plugin.test.ts index 6afbb73ba25..079348da0ca 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.test.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.test.ts @@ -650,6 +650,7 @@ describe('AuditPlugin — hands its sealer\'s expiry to the lifecycle service (A registered.push(expiry); return () => void (unregistered += 1); }, + registerRetentionFloor() {}, }, }; }; diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 7634cc4c077..6245c0ef2a8 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -22,6 +22,7 @@ import type { } from '@objectstack/spec/contracts'; import { AUDIT_CHECKPOINT_SIGNER_SERVICE, AUDIT_CHECKPOINT_SINK_SERVICE } from '@objectstack/spec/contracts'; import type { AuditExpiryRequest, AuditExpiryRun } from './audit-seal/expiry.js'; +import { registerSealedWindowFloors, type SealedFloorRegistrar } from './audit-seal/retention-floor.js'; import { AuditSealer, type AuditSealerEngine } from './audit-seal/sealer.js'; import { LocalCheckpointSigner } from './audit-seal/signer.js'; import { @@ -352,6 +353,11 @@ export class AuditPlugin implements Plugin { private sealer: AuditSealer | null = null; /** [ADR-0154 D8] Takes the sealer's expiry back off the lifecycle service, on `destroy()`. */ private unregisterExpiryPrefix: (() => void) | null = null; + /** + * [ADR-0154 D8] Registers each sealed object's retention floors at its declared window + * (`audit-seal/retention-floor.ts`); set beside the expiry, run before every sealer pass. + */ + private refreshSealedFloors: (() => void) | null = null; /** * [#31796] The credential-use writer, built in `init()` (the `audit` slot @@ -921,11 +927,12 @@ export class AuditPlugin implements Plugin { sink: () => seam(AUDIT_CHECKPOINT_SINK_SERVICE), cluster: () => seam('cluster'), logger: ctx.logger, + beforePass: () => this.refreshSealedFloors?.(), }); - this.sealer.start(); // With no crypto provider nothing is sealed and no expiry can be signed: the // lifecycle service then keeps the sealed rows and says so (ADR-0154 D8). - if (crypto) this.registerExpiryPrefix(this.sealer, ctx); + if (crypto) this.registerExpiryPrefix(this.sealer, sealEngine, ctx); + this.sealer.start(); } /** @@ -935,9 +942,15 @@ export class AuditPlugin implements Plugin { * is (`ctx.getService('lifecycle')`). No lifecycle service ⇒ nothing sweeps, * so nothing expires. A lifecycle service with no sealed expiry keeps a * sealed object's rows past their policy and says so. + * + * Beside it, a retention floor for each sealed object at its declared window + * (`audit-seal/retention-floor.ts`): on a sealed object, a retention override + * cannot shorten the declared window. Registered now and again before every + * sealer pass, so the floors follow the registry as the pass does. A lifecycle + * service without floors gets no expiry either: its sealed rows are kept. */ - private registerExpiryPrefix(sealer: AuditSealer, ctx: PluginContext): void { - type LifecycleLike = { + private registerExpiryPrefix(sealer: AuditSealer, engine: AuditSealerEngine, ctx: PluginContext): void { + type LifecycleLike = SealedFloorRegistrar & { registerExpiryPrefix?: (expiry: { plan(request: AuditExpiryRequest): Promise }) => () => void; }; let lifecycle: LifecycleLike | undefined; @@ -947,6 +960,31 @@ export class AuditPlugin implements Plugin { return; } if (!lifecycle || typeof lifecycle.registerExpiryPrefix !== 'function') return; + if (typeof lifecycle.registerRetentionFloor !== 'function') { + ctx.logger.error( + 'AuditPlugin: the lifecycle service takes a sealed-object expiry but no retention floors, so the sealed ' + + "objects' expiry is NOT registered and their rows are kept past their window. Fix: run a lifecycle " + + 'service that supports retention floors (the one @objectstack/objectql ships).', + ); + return; + } + const floors = lifecycle as Required; + let failed: string | null = null; + this.refreshSealedFloors = () => { + try { + registerSealedWindowFloors(floors, engine.registry.getAllObjects()); + failed = null; + } catch (err) { + const fault = String((err as Error)?.message ?? err); + if (failed === fault) return; + failed = fault; + ctx.logger.error( + `AuditPlugin: registering the sealed objects' retention floors FAILED (${fault}); until it succeeds a ` + + 'retention override may shorten a sealed object\'s declared window. Retried before every sealer pass.', + ); + } + }; + this.refreshSealedFloors(); // Called as a method: the service's registration reads its own state. this.unregisterExpiryPrefix = lifecycle.registerExpiryPrefix({ plan: (request) => sealer.expire(request) }); } @@ -1174,6 +1212,7 @@ export class AuditPlugin implements Plugin { this.sealer = null; this.unregisterExpiryPrefix?.(); this.unregisterExpiryPrefix = null; + this.refreshSealedFloors = null; await sealer?.stop(); const writer = this.readAuditWriter; this.readAuditWriter = null; diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts new file mode 100644 index 00000000000..c143b946caf --- /dev/null +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts @@ -0,0 +1,161 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { assertEngineDeleteDispatch, LifecycleService, parseLifecycleDuration, type LifecycleObjectLike } from '@objectstack/objectql'; +import { describe, expect, it, vi } from 'vitest'; +import { AuditPlugin } from '../audit-plugin.js'; +import { AUDIT_SEAL_FLOOR_REGISTRAR, sealedWindowFloors } from './retention-floor.js'; +import type { AuditExpiryRequest } from './expiry.js'; +import type { AuditSealer } from './sealer.js'; + +/** + * [ADR-0154 D8] On a sealed object, a retention override cannot shorten the + * declared window: `AuditPlugin` registers a retention floor for every sealed + * object at its declared window, so the window the sealed expiry is asked for + * — the one its amendment signs — is never below the declaration, globally or + * for one organization. A longer override still applies. + */ + +const FIXED_NOW = 1_700_000_000_000; +const DAY = 24 * 60 * 60 * 1000; +const isoCutoff = (literal: string) => new Date(FIXED_NOW - parseLifecycleDuration(literal)).toISOString(); +const SEAL = { valueFields: ['new_value'] }; + +const retained = (maxAge = '30d'): LifecycleObjectLike => ({ + name: 'app_ledger', + lifecycle: { class: 'audit', retention: { maxAge }, seal: SEAL } as never, +}); + +/** A sweep over `objects` whose settings carry `global` and per-organization `tenants` retention overrides. */ +function sweepRig( + objects: LifecycleObjectLike[], + global: Record | undefined, + tenants: Record> = {}, +) { + const engine = { + registry: { getAllObjects: () => objects }, + getDriverForObject: () => undefined, + find: async (object: string) => (object === 'sys_organization' ? Object.keys(tenants).map((id) => ({ id })) : []), + delete: async (_object: string, options: unknown) => { + assertEngineDeleteDispatch(options as never); + return { deletedCount: 0 }; + }, + }; + const settings = { + async get(_ns: string, key: string, ctx?: Record) { + if (key !== 'retention_overrides') return { value: undefined, source: 'default' }; + const tenantId = ctx?.tenantId as string | undefined; + if (tenantId && tenants[tenantId]) return { value: tenants[tenantId], source: 'tenant' }; + return global ? { value: global, source: 'global' } : { value: undefined, source: 'default' }; + }, + }; + const errors: string[] = []; + const logger = { info() {}, debug() {}, warn() {}, error: (m: string) => void errors.push(m) }; + const lifecycle = new LifecycleService({ + getEngine: () => engine as never, logger, now: () => FIXED_NOW, initialDelayMs: 1, sweepIntervalMs: 10, + getSettings: () => settings as never, referenceAudit: { enabled: false }, + } as never); + const plugin = new AuditPlugin({ cryptoProvider: { label: 'host' } as never }); + const ctx = { + logger: { info() {}, warn() {}, error() {}, debug() {} }, + getService: (name: string) => { + if (name === 'lifecycle') return lifecycle; + throw new Error(`no '${name}' service`); + }, + }; + const start = async () => { + (plugin as unknown as { startSealer(e: unknown, c: unknown): void }).startSealer(engine, ctx); + const sealer = (plugin as unknown as { sealer: AuditSealer }).sealer; + await sealer.stop(); // drive the passes here + const requests: AuditExpiryRequest[] = []; + vi.spyOn(sealer, 'expire').mockImplementation(async (request) => { + requests.push(request); + return []; + }); + return { sealer, requests }; + }; + return { lifecycle, plugin, start, errors }; +} + +describe('AuditPlugin — on a sealed object, a retention override cannot shorten the declared window (ADR-0154 D8)', () => { + it('an override below the declared window, global or for one organization, is rejected: the expiry is asked for the declared window', async () => { + const rig = sweepRig([retained('30d')], { app_ledger: { maxAge: '1d' } }, { + org_short: { app_ledger: { maxAge: '10d' } }, + org_long: { app_ledger: { maxAge: '400d' } }, + }); + const { requests } = await rig.start(); + + const report = await rig.lifecycle.sweep(); + + expect(requests).toHaveLength(1); + expect(requests[0]).toMatchObject({ object: 'app_ledger', policy: 'retention.maxAge', policyValue: '30d', cutoff: isoCutoff('30d') }); + expect([...(requests[0].tenants ?? [])].sort((a, b) => a.tenantId.localeCompare(b.tenantId))).toEqual([ + { tenantId: 'org_long', policyValue: '400d', cutoff: isoCutoff('400d') }, + { tenantId: 'org_short', policyValue: '30d', cutoff: isoCutoff('30d') }, + ]); + expect(report.floorViolations.map((v) => [v.scope, v.override, v.appliedMs, v.declaredBy])).toEqual([ + ['global', '1d', 30 * DAY, AUDIT_SEAL_FLOOR_REGISTRAR], + ['tenant:org_short', '10d', 30 * DAY, AUDIT_SEAL_FLOOR_REGISTRAR], + ]); + expect(rig.errors.join('\n')).toMatch(/REJECTED the retention override '1d'.*app_ledger.*lifecycle\.seal/s); + }); + + it('an override above the declared window still applies, and is what the expiry signs', async () => { + const rig = sweepRig([retained('30d')], { app_ledger: { maxAge: '90d' } }); + const { requests } = await rig.start(); + + const report = await rig.lifecycle.sweep(); + + expect(requests[0]).toMatchObject({ policyValue: '90d', cutoff: isoCutoff('90d') }); + expect(report.floorViolations).toEqual([]); + }); + + it('the floor follows the declaration: a lengthened window is the floor from the next sealer pass on', async () => { + const objects = [retained('30d')]; + const rig = sweepRig(objects, { app_ledger: { maxAge: '45d' } }); + const { sealer, requests } = await rig.start(); + await rig.lifecycle.sweep(); + expect(requests[0]).toMatchObject({ policyValue: '45d' }); + + objects[0] = retained('60d'); + await sealer.runPass(); + await rig.lifecycle.sweep(); + + expect(requests[1]).toMatchObject({ policyValue: '60d', cutoff: isoCutoff('60d') }); + }); + + it('a lifecycle service without retention floors gets no expiry: the sealed rows are kept', async () => { + const registered: unknown[] = []; + const errors: string[] = []; + const plugin = new AuditPlugin({ cryptoProvider: { label: 'host' } as never }); + const engine = { getDriverForObject: () => undefined, registry: { getAllObjects: () => [retained()] } }; + const ctx = { + logger: { info() {}, warn() {}, debug() {}, error: (m: string) => void errors.push(m) }, + getService: () => ({ registerExpiryPrefix: (expiry: unknown) => (registered.push(expiry), () => {}) }), + }; + (plugin as unknown as { startSealer(e: unknown, c: unknown): void }).startSealer(engine, ctx); + await (plugin as unknown as { sealer: AuditSealer }).sealer.stop(); + expect(registered).toEqual([]); + expect(errors.join('\n')).toMatch(/no retention floors/); + }); +}); + +describe('sealedWindowFloors — the windows a sealed object is floored at', () => { + it('a retained or ttl sealed object: one floor per window, at the declared value, by the audit seal', () => { + expect(sealedWindowFloors(retained('30d'))).toEqual([ + expect.objectContaining({ policy: 'retention', minWindowMs: 30 * DAY, declaredBy: AUDIT_SEAL_FLOOR_REGISTRAR }), + ]); + expect(sealedWindowFloors({ + name: 'app_receipt', + lifecycle: { class: 'audit', ttl: { field: 'created_at', expireAfter: '7d' }, seal: SEAL }, + })).toEqual([expect.objectContaining({ policy: 'ttl', minWindowMs: 7 * DAY })]); + }); + + it('none for an unsealed object, an archiving one (it expires past `archive.keep`, which no override reaches), or an unparsable window', () => { + expect(sealedWindowFloors({ name: 'app_note', lifecycle: { class: 'audit', retention: { maxAge: '30d' } } })).toEqual([]); + expect(sealedWindowFloors({ + name: 'sys_audit_log', + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, archive: { after: '90d', to: 'archive', keep: '7y' }, seal: SEAL }, + })).toEqual([]); + expect(sealedWindowFloors({ name: 'app_ledger', lifecycle: { class: 'audit', retention: { maxAge: 'soon' }, seal: SEAL } })).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts b/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts new file mode 100644 index 00000000000..06bcaafe1e2 --- /dev/null +++ b/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts @@ -0,0 +1,97 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { parseLifecycleDuration, type LifecycleRetentionFloor } from '@objectstack/objectql'; + +/** + * [ADR-0154 D8] On a sealed object, a retention override cannot shorten the + * declared window. + * + * A sealed object's rows leave only by whole checkpoints, each run's `expiry` + * amendment signed first, and that amendment signs the window it expired + * under. The declared window is what the object's owner published; the + * `lifecycle` settings namespace may still lengthen it (globally, or for one + * organization), never shorten it. The mechanism is the one the job queue uses + * for its idempotency window (#5195): a retention floor per sealed object at + * its declared window, so the lifecycle service rejects an override below it, + * keeps the declared window, and reports the rejection at `error`. + * + * Which windows: the ones the sealed expiry runs under on an object that + * declares no `archive` — `retention.maxAge` and `ttl.expireAfter`. An + * archiving sealed object expires only past `archive.keep`, which no settings + * key reaches, and its other window decides when a row moves to the archive, + * not when it leaves. + */ + +/** Who the floors are registered by: named in every rejection the lifecycle service reports. */ +export const AUDIT_SEAL_FLOOR_REGISTRAR = 'com.objectstack.plugin.audit.seal'; + +/** The `lifecycle` slot's floor seam, as this package consumes it. */ +export interface SealedFloorRegistrar { + registerRetentionFloor?(object: string, floor: LifecycleRetentionFloor): void; +} + +interface SealedLifecycleLike { + seal?: unknown; + archive?: unknown; + retention?: { maxAge?: unknown }; + ttl?: { expireAfter?: unknown }; +} + +/** The window's literal in milliseconds, or `null` when it does not parse to a positive window. */ +function windowMs(literal: unknown): number | null { + if (typeof literal !== 'string') return null; + try { + const ms = parseLifecycleDuration(literal); + return Number.isFinite(ms) && ms > 0 ? ms : null; + } catch { + // The lifecycle service cannot apply a window it cannot parse either, and reports that object itself. + return null; + } +} + +function floorOf(object: string, policy: 'retention' | 'ttl', key: string, literal: string, ms: number): LifecycleRetentionFloor { + return { + policy, + minWindowMs: ms, + declaredBy: AUDIT_SEAL_FLOOR_REGISTRAR, + consequence: + `${object} is sealed (lifecycle.seal), so its expiry signs the window it expired under; a window shorter ` + + `than the declared ${policy === 'ttl' ? 'ttl.expireAfter' : 'retention.maxAge'} '${literal}' is not applied.`, + remedy: + `remove the ${key} override for ${object}, or raise it to at least '${literal}'; to keep its rows for less ` + + 'time, shorten the window the object declares.', + }; +} + +/** The floors one object definition takes: one per window its sealed expiry runs under, at the declared value. */ +export function sealedWindowFloors(object: { name: string; lifecycle?: unknown }): LifecycleRetentionFloor[] { + const lc = object.lifecycle as SealedLifecycleLike | undefined; + if (!lc?.seal || lc.archive) return []; + const floors: LifecycleRetentionFloor[] = []; + const maxAge = lc.retention?.maxAge; + const retentionMs = windowMs(maxAge); + if (retentionMs !== null) floors.push(floorOf(object.name, 'retention', 'maxAge', maxAge as string, retentionMs)); + const expireAfter = lc.ttl?.expireAfter; + const ttlMs = windowMs(expireAfter); + if (ttlMs !== null) floors.push(floorOf(object.name, 'ttl', 'expireAfter', expireAfter as string, ttlMs)); + return floors; +} + +/** + * Register {@link sealedWindowFloors} for every object `objects` holds. A floor + * is keyed by object, policy and registrar, so registering again replaces it: + * called again after a declaration changed, the floor follows the declaration. + */ +export function registerSealedWindowFloors( + lifecycle: Required, + objects: ReadonlyArray<{ name: string; lifecycle?: unknown }>, +): number { + let registered = 0; + for (const object of objects) { + for (const floor of sealedWindowFloors(object)) { + lifecycle.registerRetentionFloor(object.name, floor); + registered += 1; + } + } + return registered; +} diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index 41358239968..6ef3f7a1f42 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -186,6 +186,12 @@ export interface AuditSealerOptions { /** Resolved per pass: the `cluster` service, if any. */ cluster?: () => IClusterService | undefined | Promise; logger: AuditSealerLogger; + /** + * Run at the start of every pass, before the registry is read for the pass's plans. `AuditPlugin` refreshes + * the sealed objects' retention floors here (`retention-floor.ts`), so they follow the registry as the pass + * does. A throw is reported at `error` and the pass goes on. + */ + beforePass?: () => void; now?: () => number; /** * Test seam, like `now`: a smaller {@link AUDIT_SEAL_MAX_LEAVES}, so a test @@ -476,6 +482,13 @@ export class AuditSealer { /** One pass over every sealed object. Resolves to the number of checkpoints written. */ async runPass(): Promise { + try { + this.options.beforePass?.(); + } catch (err) { + this.report(`before-pass:${faultOf(err)}`, () => + `AuditSealer: the step run before each pass (beforePass) FAILED (${faultOf(err)}); the pass goes on, and the ` + + 'step is retried on the next one.'); + } const plans = this.plans(); if (plans.length === 0) return 0; const seams = await this.resolveSeams(); diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index d4fdc0ca6a9..21c257ce22b 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1176,10 +1176,11 @@ export const LifecycleSchema = lazySchema(() => strictObject({ "the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` " + "`onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their " + '`retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry ' + - 'amendment names them, so the verifier reads them as expired rather than missing. A tenant-scoped ' + - "retention window set on the chain column applies to that organization's chain; every other chain (the " + - 'chain of rows about no organization, and every chain of an object whose windows are set on another ' + - 'column) keeps its rows to the longest window set. The window is counted to the start of a ' + + 'amendment names them, so the verifier reads them as expired rather than missing. A retention override ' + + 'cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to ' + + "that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of " + + 'rows about no organization, and every chain of an object chained by another column) keeps its rows to ' + + 'the longest window set. The window is counted to the start of a ' + 'UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a ' + 'backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto ' + 'provider seals nothing and reports that at error.', diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 8995ed1146a..5ffa3642ad8 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -3826,6 +3826,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts", + "verb": "delete", + "pinned": 1 + }, { "file": "packages/plugins/plugin-audit/src/comment-routes.test.ts", "verb": "findOne", From 05e6a57937f630c437490c20d47f292cdae822a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 04:04:38 +0000 Subject: [PATCH 14/16] fix(lifecycle): signed expiry covers objects declared in packaged metadata An object created at runtime (a tenant-authored definition) keeps the row-cutoff retention sweep: the lifecycle service does not route it to the sealed expiry, AuditPlugin registers no retention floor for it, and the sealer's expiry answers no run for it. Docs and changeset say the override floor applies to sealed objects with no archive. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt --- .changeset/31908-p4c-sealed-expiry.md | 10 ++--- content/docs/data-modeling/objects.mdx | 18 +++++--- content/docs/references/data/object.mdx | 4 +- .../lifecycle-service.sealed-expiry.test.ts | 23 ++++++++++ .../src/lifecycle/lifecycle-service.ts | 24 ++++++++-- .../audit-seal-retention-floor.test.ts | 44 +++++++++++++++++++ .../src/audit-seal/retention-floor.ts | 7 ++- .../plugin-audit/src/audit-seal/sealer.ts | 13 +++++- packages/spec/src/data/object.zod.ts | 4 +- 9 files changed, 125 insertions(+), 22 deletions(-) diff --git a/.changeset/31908-p4c-sealed-expiry.md b/.changeset/31908-p4c-sealed-expiry.md index 3f0f7f80ba4..ed7c45dd005 100644 --- a/.changeset/31908-p4c-sealed-expiry.md +++ b/.changeset/31908-p4c-sealed-expiry.md @@ -7,8 +7,8 @@ feat(plugin-audit): the audit log is sealed by default, and sealed rows expire by whole checkpoints under a signed expiry amendment -Clause-②: yes (narrowing) — narrowed: because `sys_audit_log` now declares `lifecycle.seal` on every deployment, `os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies` with `--apply` refuse on SQLite or Turso without `--sealer-stopped`, and on Postgres or MySQL take the audit seal lock and refuse when a sealer pass still holds it after ten minutes, where 18.6.0 ran them unlocked on a deployment that sealed nothing; `os audit verify` exits 1 on a row in a window at or before the newest window a trusted `window` checkpoint names that no checkpoint holds (`late`, unsealed), where it read the window unsealed and exited 0; `os audit verify` refuses with `archive_not_connected` and exits 2 wherever the `archive` datasource is declared and not connected on its own boot, where 18.6.0 printed that nothing is sealed and exited 0; `verifyAuditLedger` throws for `sys_audit_log` when the `archive` datasource it archives to is not connected and no `archive` is passed; and on an object that declares `lifecycle.seal`, a `lifecycle` settings override of `retention.maxAge` or `ttl.expireAfter` below the declared window, global or for one organization, is rejected and reported at `error`, and the declared window applies, where 18.6.0 applied it. This breaks the bound changeset `35c9a30` (#33675) set, "No object declares `lifecycle.seal` by default, so a deployment that did not opt in sees no change": this release is the one that opts every deployment in. Widened: `@objectstack/objectql` `LifecycleService.registerExpiryPrefix` and the types `LifecycleExpiryPrefix`, `LifecycleExpiryPrefixRequest` (with its `tenants` windows and `tenantColumn`), `LifecycleExpiryPrefixRun`; a sweep entry's `policy` gains `'expiry'` and `skipped[].reason` gains `seal-expiry-pending` and `seal-delete-unsupported`. -Metadata-protocol: semantic — on an object that declares `lifecycle.seal`, the authored `retention.maxAge`, `ttl.expireAfter` and `archive.keep` no longer delete a row at its row cutoff: rows leave by whole checkpoints under a signed expiry amendment, counted to the start of a UTC day, at most 10,000 a sweep, and not at all while no sealer runs +Clause-②: yes (narrowing) — narrowed: because `sys_audit_log` now declares `lifecycle.seal` on every deployment, `os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies` with `--apply` refuse on SQLite or Turso without `--sealer-stopped`, and on Postgres or MySQL take the audit seal lock and refuse when a sealer pass still holds it after ten minutes, where 18.6.0 ran them unlocked on a deployment that sealed nothing; `os audit verify` exits 1 on a row in a window at or before the newest window a trusted `window` checkpoint names that no checkpoint holds (`late`, unsealed), where it read the window unsealed and exited 0; `os audit verify` refuses with `archive_not_connected` and exits 2 wherever the `archive` datasource is declared and not connected on its own boot, where 18.6.0 printed that nothing is sealed and exited 0; `verifyAuditLedger` throws for `sys_audit_log` when the `archive` datasource it archives to is not connected and no `archive` is passed; and on an object whose packaged metadata declares `lifecycle.seal` and no `archive`, a `lifecycle` settings override of `retention.maxAge` or `ttl.expireAfter` below the declared window, global or for one organization, is rejected and reported at `error`, and the declared window applies, where 18.6.0 applied it. An object created at runtime is outside every arm of this narrowing: it keeps the 18.6.0 retention sweep. This breaks the bound changeset `35c9a30` (#33675) set, "No object declares `lifecycle.seal` by default, so a deployment that did not opt in sees no change": this release is the one that opts every deployment in. Widened: `@objectstack/objectql` `LifecycleService.registerExpiryPrefix` and the types `LifecycleExpiryPrefix`, `LifecycleExpiryPrefixRequest` (with its `tenants` windows and `tenantColumn`), `LifecycleExpiryPrefixRun`; a sweep entry's `policy` gains `'expiry'` and `skipped[].reason` gains `seal-expiry-pending` and `seal-delete-unsupported`. +Metadata-protocol: semantic — on an object whose packaged metadata declares `lifecycle.seal`, the authored `retention.maxAge`, `ttl.expireAfter` and `archive.keep` no longer delete a row at its row cutoff: rows leave by whole checkpoints under a signed expiry amendment, counted to the start of a UTC day, at most 10,000 a sweep, and not at all while no sealer runs; an object created at runtime keeps the row cutoff Skills-docs: follow-up owed — this claim's second PR (amendment 7193137455) rewrites `skills/objectstack-data/rules/lifecycle.md`, which still says the sweeper deletes sealed rows @@ -20,17 +20,17 @@ Skills-docs: follow-up owed — this claim's second PR (amendment 7193137455) re - **`os audit verify` exits 1** on a row it reads `late` and unsealed in a window another chain of the object already sealed. Fix: none is owed by the command; read the rows the report names (a chain a fault left behind), and run it again after the sealer's next pass. - **`os audit verify` exits 2** (`archive_not_connected`) where the `archive` datasource is declared and the command's boot does not connect it. Fix: declare the datasource with `autoConnect: true`, or make it reachable from where the command runs. - **`verifyAuditLedger`** (`@objectstack/plugin-audit`) throws for `sys_audit_log` when its `archive` datasource is not connected. Fix: pass `archive`, for example `archive: () => 'none'` where the deployment has no archive datasource. -- **On a sealed object, a retention override cannot shorten the declared window.** An override below it is rejected at every sweep, reported at `error` (`floorViolations` on the sweep report), and the declared window applies. Fix: remove the override or raise it to at least the declared window; to keep rows for less time, shorten the window the object declares. +- **On a sealed object with no `archive`, a retention override cannot shorten the declared window.** An override below it is rejected at every sweep, reported at `error` (`floorViolations` on the sweep report), and the declared window applies. On an object that archives, an override still sets when rows move to the archive. Fix: remove the override or raise it to at least the declared window; to keep rows for less time, shorten the window the object declares. Every dry run is unchanged. A deployment's own objects that do not declare `lifecycle.seal` keep the row-cutoff retention they had. ADR-0154 D8 and D10 (#31908, slice P4c, the last one). - **`sys_audit_log` is sealed.** Its lifecycle declares `seal: { valueFields: ['old_value', 'new_value', 'metadata'] }`, so every deployment whose `AuditPlugin` has a crypto provider (`os serve` hands it one) signs each hour's audit rows into a per-organization checkpoint, and `os audit verify` checks them. The three value columns enter each checkpoint as salted commitments; every other column enters in clear. -- **Sealed rows leave only by whole checkpoints.** The LifecycleService no longer deletes a row of an object that declares `lifecycle.seal` by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerExpiryPrefix`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). +- **Sealed rows leave only by whole checkpoints.** Signed expiry covers objects whose lifecycle is declared in packaged metadata; an object created at runtime keeps today's retention sweep. Extending signed expiry to runtime-created objects is a separate card. The LifecycleService no longer deletes a row of such an object by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerExpiryPrefix`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). - **`os migrate audit-* --apply` on SQLite or Turso now needs `--sealer-stopped` for the audit log.** The rule 18.6.0 set for a sealed object now holds on every deployment, since `sys_audit_log` is one: stop every server that seals the database, then run with the flag. That includes the `os migrate audit-side-copies --apply` an upgrade from 18.4.0 or earlier runs. Postgres and MySQL take the audit seal lock, and a dry run is unchanged. - **No sealer, no deletion.** While no sealed expiry is registered (an `AuditPlugin` with no crypto provider, a one-shot boot), a sealed object's rows past their policy are kept, the archive copy still runs, the sweep reports `seal-expiry-pending`, and the lifecycle service says so once at `warn`; such a host keeps `sys_audit_log` past `archive.keep`, and its sealer reports the missing provider hourly at `error`. An archive store with no `bulkDelete` is never planned (`seal-delete-unsupported`), so no amendment is signed over rows it could not delete. A chain whose first remaining checkpoint does not follow its last expiry (a checkpoint removed outside the platform), or whose next checkpoint does not verify under a trusted key, is not expired past that point, and the sealer says so. An expiry acts only on the chain's own checkpoints and amendments, linked in order; a stopped expiry is resumed only over checkpoints that also each verify under a trusted key and run on to the amendment's last sequence and digest; otherwise nothing in its range is deleted, and the sealer says so. The verifier holds an expiry it honours to the same. An expiry deletes rows for good: a deleted row cannot be restored from the ledger. -- **On a sealed object, a retention override cannot shorten the declared window.** `AuditPlugin` registers a retention floor (the mechanism the job queue uses for its idempotency window) for every object that declares `lifecycle.seal` and no `archive`, at its declared `retention.maxAge` and `ttl.expireAfter`, refreshed before every sealer pass so it follows the declaration. An override, global or for one organization, may lengthen the window; one below it is rejected and the declared window applies. `archive.keep` takes no override. A lifecycle service that takes a sealed expiry but no retention floors is given no expiry, so its sealed rows are kept, and the plugin says so at `error`. +- **On a sealed object with no `archive`, a retention override cannot shorten the declared window.** `AuditPlugin` registers a retention floor (the mechanism the job queue uses for its idempotency window) for every object whose packaged metadata declares `lifecycle.seal` and no `archive`, at its declared `retention.maxAge` and `ttl.expireAfter`, refreshed before every sealer pass so it follows the declaration. An override, global or for one organization, may lengthen the window; one below it is rejected and the declared window applies. `archive.keep` takes no override. A lifecycle service that takes a sealed expiry but no retention floors is given no expiry, so its sealed rows are kept, and the plugin says so at `error`. - **A tenant-scoped retention override applies to its organization's chain where it is set on the chain column.** Tenant windows are set on the object's `organization_id` column, so this holds on an object chained by it (`seal.chainField: 'organization_id'`). The lifecycle service hands each tenant's window, through the same floors, to the sealed expiry (`LifecycleExpiryPrefixRequest.tenants`), with the column the windows are set on (`LifecycleExpiryPrefixRequest.tenantColumn`). Where that is the object's chain column, an organization's chain expires under its own window and its amendment signs that value. Every other chain expires under the longest window configured: the chain of rows about no organization, and every chain of an object whose windows are set on another column than its chain column, which may hold rows of several organizations. On such an object a shorter tenant window has no effect on its sealed rows: they are kept to the longest. No row expires under a window shorter than one set for it. - **A fully expired chain continues.** Its next checkpoint chains onto the expiry: sequence after the expiry's last, linked to its `last_removed_digest`. - **`os audit verify` stays loud for a chain a fault left behind** (seat ruling 6885452378, ADR-0154 D3 as amended): a window that starts at or before the newest window a trusted `window` checkpoint names is sealed, so a row there that no checkpoint holds reads `late` and unsealed, and the check fails. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index dd6de6b01ef..e0e9f22b43e 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -283,12 +283,13 @@ it is sealed on every deployment whose `AuditPlugin` has a crypto provider. missing. The window is counted to the start of a UTC day, so a row can stay up to a day past it, and at most 10,000 such rows leave per object per sweep, so a backlog drains over several sweeps; once it has, a chain gains at most - one expiry amendment a day. On a sealed object, a retention override cannot - shorten the declared window: an override of `retention.maxAge` or - `ttl.expireAfter` in the `lifecycle` settings, global or for one - organization, may lengthen it, and one below the declared window is - rejected, reported at `error`, and the declared window applies - (`archive.keep` takes no override). A tenant-scoped window is set on the + one expiry amendment a day. On a sealed object with no `archive`, a + retention override cannot shorten the declared window: an override of + `retention.maxAge` or `ttl.expireAfter` in the `lifecycle` settings, global + or for one organization, may lengthen it, and one below the declared window + is rejected, reported at `error`, and the declared window applies. On an + object that archives, an override still sets when rows move to the archive, + and `archive.keep` takes no override. A tenant-scoped window is set on the object's `organization_id` column, so it applies to that organization's chain only on an object chained by that column (`seal.chainField: 'organization_id'`). Every other chain keeps its rows to @@ -296,7 +297,10 @@ it is sealed on every deployment whose `AuditPlugin` has a crypto provider. every chain of an object chained by another column (the default `tenant_id`), which may hold rows of several organizations. No row leaves before the window set for it. While no sealer is running (no crypto - provider), the sweeper keeps them and says so once. + provider), the sweeper keeps them and says so once. Signed expiry covers + objects whose lifecycle is declared in packaged metadata; an object created + at runtime keeps today's retention sweep: its rows leave at their row + cutoff, and a retention override applies to it. - Sealing needs a crypto provider, which the host passes to `AuditPlugin` as `cryptoProvider`. `os serve` passes the one it seals every secret with; an app that puts its own `AuditPlugin` in `plugins` passes one itself. Without diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 953f857e8bb..a7faf17d531 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -82,7 +82,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A retention override cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of rows about no organization, and every chain of an object chained by another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. Signed expiry covers objects whose lifecycle is declared in packaged metadata; an object created at runtime keeps the retention sweep. A retention override cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of rows about no organization, and every chain of an object chained by another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Lifecycle.retention` @@ -384,7 +384,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. A retention override cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of rows about no organization, and every chain of an object chained by another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. Signed expiry covers objects whose lifecycle is declared in packaged metadata; an object created at runtime keeps the retention sweep. A retention override cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of rows about no organization, and every chain of an object chained by another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Object.activityMilestones[number]` diff --git a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts index 9e50e76e048..f6532cb18bc 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts @@ -290,6 +290,29 @@ describe('LifecycleService — a sealed object expires only through the sealed e expect(() => svc.registerExpiryPrefix({} as never)).toThrow(/requires an object with a plan\(request\) method/); }); + it('a sealed object created at runtime keeps the row-cutoff sweep, retained or archiving, and never asks the sealed expiry', async () => { + // Signed expiry covers objects whose lifecycle is declared in packaged metadata; a tenant-authored + // definition (ADR-0010 `_provenance: 'org'`) keeps today's retention sweep. + const runtimeRetained = { ...RETAINED, _provenance: 'org' } as LifecycleObjectLike; + const runtimeArchiving = { ...ARCHIVING, name: 'app_journal', _provenance: 'org' } as LifecycleObjectLike; + const hot = store('default'); + const cold = store('archive'); + const { engine, finds } = engineOver([runtimeRetained, runtimeArchiving], { hot, cold, rows: [] }); + const { warns, logger } = recordingLogger(); + const svc = service(engine, logger); + const { expiry, requests } = expiryOf([]); + svc.registerExpiryPrefix(expiry); + + const report = await svc.sweep(); + + expect(requests).toEqual([]); + expect(finds.map((f) => f.where)).toContainEqual({ created_at: { $lt: isoCutoff('30d') } }); + expect(cold.deleteMany).toHaveBeenCalledWith('app_journal', { where: { created_at: { $lt: isoCutoff('7y') } } }); + expect(report.swept.map((e) => [e.object, e.policy])).toEqual([['app_ledger', 'retention'], ['app_journal', 'archive']]); + expect(report.skipped).toEqual([]); + expect(warns.join('\n')).not.toMatch(/lifecycle\.seal/); + }); + it('an object without `seal` keeps the row-cutoff path, and never asks the sealed expiry', async () => { const plain: LifecycleObjectLike = { name: 'app_log', lifecycle: { class: 'telemetry', retention: { maxAge: '30d' } } as any }; const { engine, finds } = engineOver([plain], { rows: [] }); diff --git a/packages/objectql/src/lifecycle/lifecycle-service.ts b/packages/objectql/src/lifecycle/lifecycle-service.ts index 6772387098a..df2fc6392bb 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.ts @@ -3,6 +3,7 @@ import { resolveInjectedColumnProvenance, type Lifecycle } from '@objectstack/spec/data'; import type { DriverQuery } from '@objectstack/spec/contracts'; import { isMissingTableError } from '@objectstack/metadata/errors'; +import { isTenantAuthored } from '@objectstack/metadata-core'; import { redactPropagatedDriverFault } from '@objectstack/types'; import { parseLifecycleDuration } from './duration.js'; import { isFederatedUnprovisionedInjectedColumn } from '../federated-object.js'; @@ -925,7 +926,8 @@ export class LifecycleService { /** * [ADR-0154 D8] Register the expiry every object declaring `lifecycle.seal` - * expires through. One slot: the sealer's owner registers it, and a later + * in packaged metadata expires through (an object created at runtime keeps + * the row-cutoff sweep, {@link expiresSealed}). One slot: the sealer's owner registers it, and a later * registration replaces it (a re-initialised plugin). Answers the * unregistration, which clears the slot only while it still holds this one. * @@ -1575,8 +1577,8 @@ export class LifecycleService { if (lc.archive) { return this.archiveObject(engine, obj, lc, report); } - // [ADR-0154 D8] A sealed object expires by whole checkpoints, never by a row cutoff. - if (lc.seal) return this.reapSealed(engine, obj, lc, report); + // [ADR-0154 D8] A sealed object expires by whole checkpoints, never by a row cutoff ({@link expiresSealed}). + if (expiresSealed(obj, lc)) return this.reapSealed(engine, obj, lc, report); const outcomes: Array = []; // Governance overrides (P4): a configured window beats the declared one. @@ -2219,7 +2221,7 @@ export class LifecycleService { // not moved yet is listed by the same checkpoint as its archived siblings. if (!this.abort.aborted && archive.keep) { const keepCutoffMs = this.now() - parseLifecycleDuration(archive.keep); - if (lc.seal) { + if (expiresSealed(obj, lc)) { await this.sweepSealed( engine, obj, @@ -2485,6 +2487,20 @@ function idKey(id: unknown): string | undefined { * override when it is the one that stood, else the declaration. A sealed * object's expiry amendment signs it, and the verifier judges the expiry by it. */ +/** + * [ADR-0154 D8] Whether `obj` expires through the sealed-object expiry: it + * declares `lifecycle.seal`, and its definition is packaged or code metadata. + * + * Signed expiry covers objects whose lifecycle is declared in packaged + * metadata. An object created at runtime (a tenant-authored definition, + * ADR-0010 `_provenance: 'org'`) keeps today's retention sweep: its rows leave + * by their row cutoff and a settings override applies, as before this expiry + * existed. Extending signed expiry to runtime-created objects is separate work. + */ +function expiresSealed(obj: LifecycleObjectLike, lc: Lifecycle): boolean { + return Boolean(lc.seal) && !isTenantAuthored(obj); +} + function appliedLiteral(override: string | undefined, declared: string, appliedMs: number): string { if (typeof override !== 'string') return declared; try { diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts index c143b946caf..b1af3819460 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts @@ -139,6 +139,49 @@ describe('AuditPlugin — on a sealed object, a retention override cannot shorte }); }); +describe('AuditPlugin — signed expiry covers objects whose lifecycle is declared in packaged metadata (ADR-0154 D8)', () => { + const FIELDS = { id: { type: 'text' }, created_at: { type: 'datetime' }, tenant_id: { type: 'lookup' }, new_value: { type: 'textarea' } }; + const runtime = (): LifecycleObjectLike => ({ ...retained('30d'), fields: FIELDS, _provenance: 'org', _packageId: 'sys_metadata' } as never); + const packaged = (): LifecycleObjectLike => ({ ...retained('30d'), fields: FIELDS, _provenance: 'package', _packageId: 'app.ledger' } as never); + + it('an object created at runtime takes no floor: an override below its declared window applies, and no expiry is asked', async () => { + const rig = sweepRig([runtime()], { app_ledger: { maxAge: '1d' } }); + const { requests } = await rig.start(); + + const report = await rig.lifecycle.sweep(); + + expect(requests).toEqual([]); + expect(report.floorViolations).toEqual([]); + expect(report.swept).toEqual([expect.objectContaining({ object: 'app_ledger', policy: 'retention', cutoff: isoCutoff('1d') })]); + }); + + it('a packaged object still takes its floor and the signed expiry', async () => { + const rig = sweepRig([packaged()], { app_ledger: { maxAge: '1d' } }); + const { requests } = await rig.start(); + + const report = await rig.lifecycle.sweep(); + + expect(requests).toEqual([expect.objectContaining({ object: 'app_ledger', policyValue: '30d' })]); + expect(report.floorViolations.map((v) => v.declaredBy)).toEqual([AUDIT_SEAL_FLOOR_REGISTRAR]); + }); + + it("the sealer's expiry answers no run for an object created at runtime, before it resolves a seam; a packaged one goes on", async () => { + const objects = [runtime()]; + const rig = sweepRig(objects, undefined); + const { sealer } = await rig.start(); + vi.mocked(sealer.expire).mockRestore(); + const seams = vi.spyOn(sealer as unknown as { resolveSeams(): Promise }, 'resolveSeams').mockResolvedValue(null); + const request = { object: 'app_ledger', policy: 'retention.maxAge', policyValue: '30d', cutoff: isoCutoff('30d') } as const; + + await expect(sealer.expire(request)).resolves.toEqual([]); + expect(seams).not.toHaveBeenCalled(); + + objects[0] = packaged(); + await expect(sealer.expire(request)).rejects.toThrow(/could not be resolved/); + expect(seams).toHaveBeenCalledTimes(1); + }); +}); + describe('sealedWindowFloors — the windows a sealed object is floored at', () => { it('a retained or ttl sealed object: one floor per window, at the declared value, by the audit seal', () => { expect(sealedWindowFloors(retained('30d'))).toEqual([ @@ -157,5 +200,6 @@ describe('sealedWindowFloors — the windows a sealed object is floored at', () lifecycle: { class: 'audit', retention: { maxAge: '90d' }, archive: { after: '90d', to: 'archive', keep: '7y' }, seal: SEAL }, })).toEqual([]); expect(sealedWindowFloors({ name: 'app_ledger', lifecycle: { class: 'audit', retention: { maxAge: 'soon' }, seal: SEAL } })).toEqual([]); + expect(sealedWindowFloors({ ...retained('30d'), _provenance: 'org' } as never)).toEqual([]); }); }); diff --git a/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts b/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts index 06bcaafe1e2..2a7d2591f8c 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts @@ -1,5 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +import { isTenantAuthored } from '@objectstack/metadata-core'; import { parseLifecycleDuration, type LifecycleRetentionFloor } from '@objectstack/objectql'; /** @@ -20,6 +21,10 @@ import { parseLifecycleDuration, type LifecycleRetentionFloor } from '@objectsta * archiving sealed object expires only past `archive.keep`, which no settings * key reaches, and its other window decides when a row moves to the archive, * not when it leaves. + * + * Which objects: those whose lifecycle is declared in packaged metadata. An + * object created at runtime keeps today's retention sweep (no signed expiry), + * and an override applies to it as before, so it takes no floor. */ /** Who the floors are registered by: named in every rejection the lifecycle service reports. */ @@ -66,7 +71,7 @@ function floorOf(object: string, policy: 'retention' | 'ttl', key: string, liter /** The floors one object definition takes: one per window its sealed expiry runs under, at the declared value. */ export function sealedWindowFloors(object: { name: string; lifecycle?: unknown }): LifecycleRetentionFloor[] { const lc = object.lifecycle as SealedLifecycleLike | undefined; - if (!lc?.seal || lc.archive) return []; + if (!lc?.seal || lc.archive || isTenantAuthored(object)) return []; const floors: LifecycleRetentionFloor[] = []; const maxAge = lc.retention?.maxAge; const retentionMs = windowMs(maxAge); diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index 6ef3f7a1f42..df866918038 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -10,6 +10,7 @@ import type { ICryptoProvider, LockHandle, } from '@objectstack/spec/contracts'; +import { isTenantAuthored } from '@objectstack/metadata-core'; import { isMissingTableError } from '@objectstack/types'; import { AUDIT_SEAL_CANON_VERSION, @@ -209,6 +210,11 @@ interface SealPlan { /** The column each row's chain is read from ({@link chainValueOf}): `lifecycle.seal.chainField`, or `tenant_id`. */ readonly chainField: string; readonly archiveTo?: string; + /** + * ADR-0154 D8: whether the object's lifecycle is declared in packaged metadata, so it takes the signed + * expiry. An object created at runtime (a tenant-authored definition) is sealed but keeps the row-cutoff sweep. + */ + readonly signedExpiry: boolean; } interface ChainHead { @@ -424,7 +430,10 @@ export class AuditSealer { 'columns of a type with a canonical rule (ADR-0154 D1, D5, D10), or remove lifecycle.seal.'); continue; } - plans.push({ name: object.name, fields, columns, chainField, ...(lifecycle.archive?.to ? { archiveTo: lifecycle.archive.to } : {}) }); + plans.push({ + name: object.name, fields, columns, chainField, signedExpiry: !isTenantAuthored(object), + ...(lifecycle.archive?.to ? { archiveTo: lifecycle.archive.to } : {}), + }); } return plans; } @@ -562,7 +571,7 @@ export class AuditSealer { */ async expire(request: AuditExpiryRequest): Promise { const plan = this.plans().find((p) => p.name === request.object); - if (!plan) return []; + if (!plan || !plan.signedExpiry) return []; const memo = [ `${auditExpiryCutoff(Date.parse(request.cutoff))}|${request.policy}|${request.policyValue}`, `on:${request.tenantColumn ?? ''}`, diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 21c257ce22b..11f46cb558a 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1176,7 +1176,9 @@ export const LifecycleSchema = lazySchema(() => strictObject({ "the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` " + "`onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their " + '`retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry ' + - 'amendment names them, so the verifier reads them as expired rather than missing. A retention override ' + + 'amendment names them, so the verifier reads them as expired rather than missing. Signed expiry covers ' + + 'objects whose lifecycle is declared in packaged metadata; an object created at runtime keeps the ' + + 'retention sweep. A retention override ' + 'cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to ' + "that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of " + 'rows about no organization, and every chain of an object chained by another column) keeps its rows to ' + From ff14eb26ed32f4a34e684bfb3f810746d665940f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 06:39:19 +0000 Subject: [PATCH 15/16] fix(audit): signed expiry only on a positive packaged-metadata answer; round-6 wording One predicate, takesSignedExpiry, decides whether a sealed object takes the signed expiry and its retention floor: the lifecycle routing, the audit floors and the sealer's own expiry all ask it. It answers yes only when the registry places the object in packaged metadata; any other sealed object keeps the row-cutoff retention sweep. Docs, describe and changeset wording follow review 7210787318 (S8, S9, n17, n19, n20). Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt --- .changeset/31908-p4c-sealed-expiry.md | 8 +-- content/docs/data-modeling/objects.mdx | 14 ++--- content/docs/references/data/object.mdx | 4 +- packages/objectql/src/index.ts | 3 + .../lifecycle-service.sealed-expiry.test.ts | 32 ++++++++++- .../src/lifecycle/lifecycle-service.ts | 37 ++++++------ .../src/lifecycle/signed-expiry-scope.test.ts | 37 ++++++++++++ .../src/lifecycle/signed-expiry-scope.ts | 57 +++++++++++++++++++ .../plugins/plugin-audit/src/audit-plugin.ts | 2 +- .../audit-seal-retention-floor.test.ts | 43 +++++++++++--- .../src/audit-seal/retention-floor.ts | 28 +++++---- .../src/audit-seal/seal-store.testkit.ts | 3 +- .../plugin-audit/src/audit-seal/sealer.ts | 12 ++-- packages/spec/src/data/object.zod.ts | 12 ++-- 14 files changed, 228 insertions(+), 64 deletions(-) create mode 100644 packages/objectql/src/lifecycle/signed-expiry-scope.test.ts create mode 100644 packages/objectql/src/lifecycle/signed-expiry-scope.ts diff --git a/.changeset/31908-p4c-sealed-expiry.md b/.changeset/31908-p4c-sealed-expiry.md index ed7c45dd005..445c769b821 100644 --- a/.changeset/31908-p4c-sealed-expiry.md +++ b/.changeset/31908-p4c-sealed-expiry.md @@ -7,8 +7,8 @@ feat(plugin-audit): the audit log is sealed by default, and sealed rows expire by whole checkpoints under a signed expiry amendment -Clause-②: yes (narrowing) — narrowed: because `sys_audit_log` now declares `lifecycle.seal` on every deployment, `os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies` with `--apply` refuse on SQLite or Turso without `--sealer-stopped`, and on Postgres or MySQL take the audit seal lock and refuse when a sealer pass still holds it after ten minutes, where 18.6.0 ran them unlocked on a deployment that sealed nothing; `os audit verify` exits 1 on a row in a window at or before the newest window a trusted `window` checkpoint names that no checkpoint holds (`late`, unsealed), where it read the window unsealed and exited 0; `os audit verify` refuses with `archive_not_connected` and exits 2 wherever the `archive` datasource is declared and not connected on its own boot, where 18.6.0 printed that nothing is sealed and exited 0; `verifyAuditLedger` throws for `sys_audit_log` when the `archive` datasource it archives to is not connected and no `archive` is passed; and on an object whose packaged metadata declares `lifecycle.seal` and no `archive`, a `lifecycle` settings override of `retention.maxAge` or `ttl.expireAfter` below the declared window, global or for one organization, is rejected and reported at `error`, and the declared window applies, where 18.6.0 applied it. An object created at runtime is outside every arm of this narrowing: it keeps the 18.6.0 retention sweep. This breaks the bound changeset `35c9a30` (#33675) set, "No object declares `lifecycle.seal` by default, so a deployment that did not opt in sees no change": this release is the one that opts every deployment in. Widened: `@objectstack/objectql` `LifecycleService.registerExpiryPrefix` and the types `LifecycleExpiryPrefix`, `LifecycleExpiryPrefixRequest` (with its `tenants` windows and `tenantColumn`), `LifecycleExpiryPrefixRun`; a sweep entry's `policy` gains `'expiry'` and `skipped[].reason` gains `seal-expiry-pending` and `seal-delete-unsupported`. -Metadata-protocol: semantic — on an object whose packaged metadata declares `lifecycle.seal`, the authored `retention.maxAge`, `ttl.expireAfter` and `archive.keep` no longer delete a row at its row cutoff: rows leave by whole checkpoints under a signed expiry amendment, counted to the start of a UTC day, at most 10,000 a sweep, and not at all while no sealer runs; an object created at runtime keeps the row cutoff +Clause-②: yes (narrowing) — narrowed: because `sys_audit_log` now declares `lifecycle.seal` on every deployment, `os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies` with `--apply` refuse on SQLite or Turso without `--sealer-stopped`, and on Postgres or MySQL take the audit seal lock and refuse when a sealer pass still holds it after ten minutes, where 18.6.0 ran them unlocked on a deployment that sealed nothing; `os audit verify` exits 1 on a row in a window at or before the newest window a trusted `window` checkpoint names that no checkpoint holds (`late`, unsealed), where it read the window unsealed and exited 0; `os audit verify` refuses with `archive_not_connected` and exits 2 wherever the `archive` datasource is declared and not connected on its own boot, where 18.6.0 printed that nothing is sealed and exited 0; `verifyAuditLedger` throws for `sys_audit_log` when the `archive` datasource it archives to is not connected and no `archive` is passed; and on an object whose packaged metadata declares `lifecycle.seal` and no `archive`, a `lifecycle` settings override of `retention.maxAge` or `ttl.expireAfter` below the declared window, global or for one organization, is rejected and reported at `error`, and the declared window applies, where 18.6.0 applied it. An object created at runtime is outside the override arm and outside signed expiry: it keeps the 18.6.0 row-cutoff retention sweep, and a settings override applies to it; the `os audit verify` arms hold for it as for any sealed object. This breaks the bound changeset `35c9a30` (#33675) set, "No object declares `lifecycle.seal` by default, so a deployment that did not opt in sees no change": this release is the one that opts every deployment in. Widened: `@objectstack/objectql` `LifecycleService.registerExpiryPrefix` and the types `LifecycleExpiryPrefix`, `LifecycleExpiryPrefixRequest` (with its `tenants` windows and `tenantColumn`), `LifecycleExpiryPrefixRun`, the predicate `takesSignedExpiry` with its type `SignedExpiryRegistryLike`, and three optional owner reads on `LifecycleEngineLike.registry`; a sweep entry's `policy` gains `'expiry'` and `skipped[].reason` gains `seal-expiry-pending` and `seal-delete-unsupported`. +Metadata-protocol: semantic — on an object whose packaged metadata declares `lifecycle.seal`, the authored `retention.maxAge`, `ttl.expireAfter` and `archive.keep` no longer delete a row at its row cutoff: rows leave by whole checkpoints under a signed expiry amendment, counted to the start of a UTC day, at most 10,000 a sweep, and not at all while no sealer runs; an object created at runtime keeps its row cutoff Skills-docs: follow-up owed — this claim's second PR (amendment 7193137455) rewrites `skills/objectstack-data/rules/lifecycle.md`, which still says the sweeper deletes sealed rows @@ -20,14 +20,14 @@ Skills-docs: follow-up owed — this claim's second PR (amendment 7193137455) re - **`os audit verify` exits 1** on a row it reads `late` and unsealed in a window another chain of the object already sealed. Fix: none is owed by the command; read the rows the report names (a chain a fault left behind), and run it again after the sealer's next pass. - **`os audit verify` exits 2** (`archive_not_connected`) where the `archive` datasource is declared and the command's boot does not connect it. Fix: declare the datasource with `autoConnect: true`, or make it reachable from where the command runs. - **`verifyAuditLedger`** (`@objectstack/plugin-audit`) throws for `sys_audit_log` when its `archive` datasource is not connected. Fix: pass `archive`, for example `archive: () => 'none'` where the deployment has no archive datasource. -- **On a sealed object with no `archive`, a retention override cannot shorten the declared window.** An override below it is rejected at every sweep, reported at `error` (`floorViolations` on the sweep report), and the declared window applies. On an object that archives, an override still sets when rows move to the archive. Fix: remove the override or raise it to at least the declared window; to keep rows for less time, shorten the window the object declares. +- **On a sealed object with no `archive` whose lifecycle is declared in packaged metadata, a retention override cannot shorten the declared window.** An override below it is rejected at every sweep, reported at `error` (`floorViolations` on the sweep report), and the declared window applies. On an object that archives, an override still sets when rows move to the archive. Fix: remove the override or raise it to at least the declared window; to keep rows for less time, shorten the window the object declares. Every dry run is unchanged. A deployment's own objects that do not declare `lifecycle.seal` keep the row-cutoff retention they had. ADR-0154 D8 and D10 (#31908, slice P4c, the last one). - **`sys_audit_log` is sealed.** Its lifecycle declares `seal: { valueFields: ['old_value', 'new_value', 'metadata'] }`, so every deployment whose `AuditPlugin` has a crypto provider (`os serve` hands it one) signs each hour's audit rows into a per-organization checkpoint, and `os audit verify` checks them. The three value columns enter each checkpoint as salted commitments; every other column enters in clear. -- **Sealed rows leave only by whole checkpoints.** Signed expiry covers objects whose lifecycle is declared in packaged metadata; an object created at runtime keeps today's retention sweep. Extending signed expiry to runtime-created objects is a separate card. The LifecycleService no longer deletes a row of such an object by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerExpiryPrefix`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). +- **Sealed rows leave only by whole checkpoints.** Signed expiry covers objects whose lifecycle is declared in packaged metadata; an object created at runtime keeps the 18.6.0 row-cutoff retention sweep, its rows then reading as missing. Extending signed expiry to runtime-created objects is a separate card. The LifecycleService no longer deletes a row of a sealed object whose lifecycle is declared in packaged metadata by a row cutoff (`retention.maxAge`, `ttl.expireAfter`, or the archive's `keep` prune). It hands each policy to the sealed expiry the audit sealer registers (`LifecycleService.registerExpiryPrefix`, `@objectstack/objectql`). Per chain, the sealer takes the consecutive checkpoints from the chain's first remaining one whose windows ended before the cutoff (aligned down to a UTC day, so once its backlog is drained a chain gains at most one expiry amendment a day), each admitted under a trusted signing key, at most 10,000 rows a sweep. It signs and stores the chain's `expiry` amendment first. The sweep then deletes exactly those rows, by id, from the hot store and the archive, and only after them the checkpoints and their seeds. A sweep stopped part way resumes under the stored amendment and signs no second one. A run a reap guard vetoes in part is not completed and is retried. The verifier reads an expired row as `expired` while its checkpoint stands, and after it is gone honours the range as before (D8). - **`os migrate audit-* --apply` on SQLite or Turso now needs `--sealer-stopped` for the audit log.** The rule 18.6.0 set for a sealed object now holds on every deployment, since `sys_audit_log` is one: stop every server that seals the database, then run with the flag. That includes the `os migrate audit-side-copies --apply` an upgrade from 18.4.0 or earlier runs. Postgres and MySQL take the audit seal lock, and a dry run is unchanged. - **No sealer, no deletion.** While no sealed expiry is registered (an `AuditPlugin` with no crypto provider, a one-shot boot), a sealed object's rows past their policy are kept, the archive copy still runs, the sweep reports `seal-expiry-pending`, and the lifecycle service says so once at `warn`; such a host keeps `sys_audit_log` past `archive.keep`, and its sealer reports the missing provider hourly at `error`. An archive store with no `bulkDelete` is never planned (`seal-delete-unsupported`), so no amendment is signed over rows it could not delete. A chain whose first remaining checkpoint does not follow its last expiry (a checkpoint removed outside the platform), or whose next checkpoint does not verify under a trusted key, is not expired past that point, and the sealer says so. An expiry acts only on the chain's own checkpoints and amendments, linked in order; a stopped expiry is resumed only over checkpoints that also each verify under a trusted key and run on to the amendment's last sequence and digest; otherwise nothing in its range is deleted, and the sealer says so. The verifier holds an expiry it honours to the same. An expiry deletes rows for good: a deleted row cannot be restored from the ledger. - **On a sealed object with no `archive`, a retention override cannot shorten the declared window.** `AuditPlugin` registers a retention floor (the mechanism the job queue uses for its idempotency window) for every object whose packaged metadata declares `lifecycle.seal` and no `archive`, at its declared `retention.maxAge` and `ttl.expireAfter`, refreshed before every sealer pass so it follows the declaration. An override, global or for one organization, may lengthen the window; one below it is rejected and the declared window applies. `archive.keep` takes no override. A lifecycle service that takes a sealed expiry but no retention floors is given no expiry, so its sealed rows are kept, and the plugin says so at `error`. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index e0e9f22b43e..dcb7c5189cf 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -277,13 +277,14 @@ it is sealed on every deployment whose `AuditPlugin` has a crypto provider. - Refused at parse time beside `seal`: a `class` other than `audit`, `retention.onlyWhen`, `ttl.onlyWhen`, a `ttl` on a field other than `created_at`, and rotation `storage`. Each deletes part of a sealed hour. - Sealed rows past their `retention`, `ttl` or `archive.keep` window leave - only by whole checkpoints: the sealer first writes a signed expiry + Signed expiry covers objects whose lifecycle is declared in packaged + metadata. Their sealed rows past their `retention`, `ttl` or `archive.keep` + window leave only by whole checkpoints: the sealer first writes a signed expiry amendment naming them, so the verifier reads them as `expired` rather than missing. The window is counted to the start of a UTC day, so a row can stay up to a day past it, and at most 10,000 such rows leave per object per sweep, so a backlog drains over several sweeps; once it has, a chain gains at most - one expiry amendment a day. On a sealed object with no `archive`, a + one expiry amendment a day. On such a packaged object with no `archive`, a retention override cannot shorten the declared window: an override of `retention.maxAge` or `ttl.expireAfter` in the `lifecycle` settings, global or for one organization, may lengthen it, and one below the declared window @@ -297,10 +298,9 @@ it is sealed on every deployment whose `AuditPlugin` has a crypto provider. every chain of an object chained by another column (the default `tenant_id`), which may hold rows of several organizations. No row leaves before the window set for it. While no sealer is running (no crypto - provider), the sweeper keeps them and says so once. Signed expiry covers - objects whose lifecycle is declared in packaged metadata; an object created - at runtime keeps today's retention sweep: its rows leave at their row - cutoff, and a retention override applies to it. + provider), the sweeper keeps them and says so once. On an object created at + runtime the retention sweeper still deletes sealed rows at their row cutoff, + which then read as missing, and a retention override applies to it. - Sealing needs a crypto provider, which the host passes to `AuditPlugin` as `cryptoProvider`. `os serve` passes the one it seals every secret with; an app that puts its own `AuditPlugin` in `plugins` passes one itself. Without diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index a7faf17d531..c200a39b108 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -82,7 +82,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. Signed expiry covers objects whose lifecycle is declared in packaged metadata; an object created at runtime keeps the retention sweep. A retention override cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of rows about no organization, and every chain of an object chained by another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Signed expiry covers objects whose lifecycle is declared in packaged metadata: their sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing, and on such an object with no `archive` a retention override cannot shorten the declared window. On an object created at runtime the retention sweeper still deletes sealed rows at their row cutoff, which then read as missing. A tenant-scoped window is set on `organization_id`, so it applies to that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of rows about no organization, and every chain of an object chained by another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Lifecycle.retention` @@ -384,7 +384,7 @@ const result = ApiMethod.parse(data); | **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record }` | optional | Per-row TTL auto-expiry (transient/event classes). | | **storage** | `{ strategy: 'rotation'; shards: integer; unit: Enum<'day' \| 'week' \| 'month'> }` | optional | Physical storage strategy for high-frequency telemetry (LifecycleService Rotator). | | **archive** | `{ after: string; to: string; keep?: string }` | optional | Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off. | -| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing. Signed expiry covers objects whose lifecycle is declared in packaged metadata; an object created at runtime keeps the retention sweep. A retention override cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of rows about no organization, and every chain of an object chained by another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | +| **seal** | `{ valueFields: string[]; chainField?: string }` | optional | Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` `onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Signed expiry covers objects whose lifecycle is declared in packaged metadata: their sealed rows past their `retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so the verifier reads them as expired rather than missing, and on such an object with no `archive` a retention override cannot shorten the declared window. On an object created at runtime the retention sweeper still deletes sealed rows at their row cutoff, which then read as missing. A tenant-scoped window is set on `organization_id`, so it applies to that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of rows about no organization, and every chain of an object chained by another column) keeps its rows to the longest window set. The window is counted to the start of a UTC day and at most 10,000 rows leave per sweep, so a row can stay past it: a day, or longer while a backlog drains. While no sealer is running, the sweeper keeps them. A deployment with no crypto provider seals nothing and reports that at error. | | **reclaim** | `boolean` | optional | Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes. | ### Nested Shape: `Object.activityMilestones[number]` diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index dfbf0b7d7b3..4d6fed96b6b 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -810,6 +810,9 @@ export type { LifecycleFloorViolation, } from './lifecycle/lifecycle-service.js'; export { parseLifecycleDuration } from './lifecycle/duration.js'; +// [ADR-0154 D8] Which sealed objects take the signed expiry: the lifecycle service, the audit floors and the sealer ask one predicate. +export { takesSignedExpiry } from './lifecycle/signed-expiry-scope.js'; +export type { SignedExpiryRegistryLike } from './lifecycle/signed-expiry-scope.js'; // [#30237, ADR-0148 D3] What a host hands `ObjectQLPlugin`'s `recycleBinRetention`. export type { RecycleBinRetentionSettings } from './recycle-bin/retention.js'; export type { RecycleBinRemovalOptions } from './recycle-bin/purge.js'; diff --git a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts index f6532cb18bc..1f5a9fc1c32 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts @@ -10,6 +10,7 @@ import { } from './lifecycle-service.js'; import { assertEngineDeleteDispatch } from '@objectstack/metadata-core'; import { parseLifecycleDuration } from './duration.js'; +import { SchemaRegistry } from '../registry.js'; /** * [ADR-0154 D8] A sealed object (`lifecycle.seal`) never loses rows to a row @@ -70,7 +71,8 @@ function engineOver(objects: LifecycleObjectLike[], opts: { hot?: ReturnType objects }, + // Each object a plain registration from code, unless it is tenant-authored: the registry places it in packaged metadata. + registry: { getAllObjects: () => objects, getObjectOwner: (name: string) => (objects.some((o) => o.name === name) ? {} : undefined) }, getDriverForObject: () => opts.hot?.driver, datasource(name: string) { if (name === 'archive' && opts.cold) return opts.cold.driver; @@ -292,7 +294,7 @@ describe('LifecycleService — a sealed object expires only through the sealed e it('a sealed object created at runtime keeps the row-cutoff sweep, retained or archiving, and never asks the sealed expiry', async () => { // Signed expiry covers objects whose lifecycle is declared in packaged metadata; a tenant-authored - // definition (ADR-0010 `_provenance: 'org'`) keeps today's retention sweep. + // definition (ADR-0010 `_provenance: 'org'`) keeps the row-cutoff retention sweep. const runtimeRetained = { ...RETAINED, _provenance: 'org' } as LifecycleObjectLike; const runtimeArchiving = { ...ARCHIVING, name: 'app_journal', _provenance: 'org' } as LifecycleObjectLike; const hot = store('default'); @@ -313,6 +315,32 @@ describe('LifecycleService — a sealed object expires only through the sealed e expect(warns.join('\n')).not.toMatch(/lifecycle\.seal/); }); + it('a sealed object the registry cannot place in an installed code or marketplace package keeps the row-cutoff sweep', async () => { + // The reload door's shape (`ObjectQLPlugin`): a loader-chain body registered under its own `_packageId`, or + // `metadata-service`, with whatever provenance it carries. Only a positive answer takes the signed expiry. + const FIELDS = { created_at: { type: 'datetime' }, tenant_id: { type: 'lookup' }, new_value: { type: 'textarea' } }; + const sweepOver = async (install?: 'code' | 'marketplace' | 'authored', body: Record = { _packageId: 'app.ledger', _provenance: 'package' }) => { + const registry = new SchemaRegistry() as any; + if (install) registry.installPackage({ id: 'app.ledger', name: 'app.ledger', version: '1.0.0', type: 'app', namespace: 'ledger' }, install); + registry.registerObject({ ...RETAINED, fields: FIELDS, ...body }, (body._packageId as string | undefined) ?? 'metadata-service', undefined, 'own'); + const { engine } = engineOver([], { rows: [] }); + engine.registry = registry; + const svc = service(engine); + const { expiry, requests } = expiryOf([]); + svc.registerExpiryPrefix(expiry); + const report = await svc.sweep(); + return { requests, policies: report.swept.filter((e) => e.object === 'app_ledger').map((e) => e.policy) }; + }; + + for (const outcome of [await sweepOver(), await sweepOver(undefined, {}), await sweepOver('authored')]) { + expect(outcome).toEqual({ requests: [], policies: ['retention'] }); + } + for (const source of ['code', 'marketplace'] as const) { + const outcome = await sweepOver(source); + expect(outcome.requests.map((r) => r.policy)).toEqual(['retention.maxAge']); + } + }); + it('an object without `seal` keeps the row-cutoff path, and never asks the sealed expiry', async () => { const plain: LifecycleObjectLike = { name: 'app_log', lifecycle: { class: 'telemetry', retention: { maxAge: '30d' } } as any }; const { engine, finds } = engineOver([plain], { rows: [] }); diff --git a/packages/objectql/src/lifecycle/lifecycle-service.ts b/packages/objectql/src/lifecycle/lifecycle-service.ts index df2fc6392bb..41eb253955d 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.ts @@ -3,9 +3,9 @@ import { resolveInjectedColumnProvenance, type Lifecycle } from '@objectstack/spec/data'; import type { DriverQuery } from '@objectstack/spec/contracts'; import { isMissingTableError } from '@objectstack/metadata/errors'; -import { isTenantAuthored } from '@objectstack/metadata-core'; import { redactPropagatedDriverFault } from '@objectstack/types'; import { parseLifecycleDuration } from './duration.js'; +import { takesSignedExpiry, type SignedExpiryRegistryLike } from './signed-expiry-scope.js'; import { isFederatedUnprovisionedInjectedColumn } from '../federated-object.js'; import type { DanglingReferenceAuditOptions, @@ -103,7 +103,11 @@ export const LIFECYCLE_STATE_ROW_ID = 'lifecycle'; /** Minimal engine surface the service needs — duck-typed for tests. */ export interface LifecycleEngineLike { - registry: { + /** + * [ADR-0154 D8] The owner and installed-package reads ({@link SignedExpiryRegistryLike}) decide which sealed + * objects take the signed expiry ({@link takesSignedExpiry}); a registry without them takes none. + */ + registry: SignedExpiryRegistryLike & { getAllObjects(): LifecycleObjectLike[]; /** * [#21597] Registry presence by name: the question the engine's in-process @@ -1578,7 +1582,7 @@ export class LifecycleService { return this.archiveObject(engine, obj, lc, report); } // [ADR-0154 D8] A sealed object expires by whole checkpoints, never by a row cutoff ({@link expiresSealed}). - if (expiresSealed(obj, lc)) return this.reapSealed(engine, obj, lc, report); + if (expiresSealed(engine, obj, lc)) return this.reapSealed(engine, obj, lc, report); const outcomes: Array = []; // Governance overrides (P4): a configured window beats the declared one. @@ -2221,7 +2225,7 @@ export class LifecycleService { // not moved yet is listed by the same checkpoint as its archived siblings. if (!this.abort.aborted && archive.keep) { const keepCutoffMs = this.now() - parseLifecycleDuration(archive.keep); - if (expiresSealed(obj, lc)) { + if (expiresSealed(engine, obj, lc)) { await this.sweepSealed( engine, obj, @@ -2482,25 +2486,22 @@ function idKey(id: unknown): string | undefined { return id === null || id === undefined ? undefined : String(id); } -/** - * [ADR-0154 D8] The duration literal behind the window a sweep applied: the - * override when it is the one that stood, else the declaration. A sealed - * object's expiry amendment signs it, and the verifier judges the expiry by it. - */ /** * [ADR-0154 D8] Whether `obj` expires through the sealed-object expiry: it - * declares `lifecycle.seal`, and its definition is packaged or code metadata. - * - * Signed expiry covers objects whose lifecycle is declared in packaged - * metadata. An object created at runtime (a tenant-authored definition, - * ADR-0010 `_provenance: 'org'`) keeps today's retention sweep: its rows leave - * by their row cutoff and a settings override applies, as before this expiry - * existed. Extending signed expiry to runtime-created objects is separate work. + * declares `lifecycle.seal`, and the registry answers that its lifecycle is + * declared in packaged metadata ({@link takesSignedExpiry}). Anything else — + * an object created at runtime, or one the registry cannot place — keeps the + * row-cutoff retention sweep, as before this expiry existed. */ -function expiresSealed(obj: LifecycleObjectLike, lc: Lifecycle): boolean { - return Boolean(lc.seal) && !isTenantAuthored(obj); +function expiresSealed(engine: LifecycleEngineLike, obj: LifecycleObjectLike, lc: Lifecycle): boolean { + return Boolean(lc.seal) && takesSignedExpiry(engine.registry, obj); } +/** + * [ADR-0154 D8] The duration literal behind the window a sweep applied: the + * override when it is the one that stood, else the declaration. A sealed + * object's expiry amendment signs it, and the verifier judges the expiry by it. + */ function appliedLiteral(override: string | undefined, declared: string, appliedMs: number): string { if (typeof override !== 'string') return declared; try { diff --git a/packages/objectql/src/lifecycle/signed-expiry-scope.test.ts b/packages/objectql/src/lifecycle/signed-expiry-scope.test.ts new file mode 100644 index 00000000000..a737c4e68d8 --- /dev/null +++ b/packages/objectql/src/lifecycle/signed-expiry-scope.test.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { takesSignedExpiry } from './signed-expiry-scope.js'; + +/** + * [ADR-0154 D8] Signed expiry covers objects whose lifecycle is declared in + * packaged metadata, and only on the registry's positive answer: a registry + * that cannot place an object answers no. + */ +describe('takesSignedExpiry — only a positive answer from the registry', () => { + const object = { name: 'app_ledger' }; + + it('no for a registry that cannot be asked, or no registry at all', () => { + expect(takesSignedExpiry({}, object)).toBe(false); + expect(takesSignedExpiry(undefined, object)).toBe(false); + expect(takesSignedExpiry({ getPackagedObjectOwner: () => ({ packageId: 'app.ledger' }) }, object)).toBe(false); + }); + + it('yes for an owner of an installed code or marketplace package, no for an authored or unknown one', () => { + const over = (source: string | undefined) => ({ + getPackagedObjectOwner: () => ({ packageId: 'app.ledger' }), + getPackage: () => (source ? { source } : undefined), + }); + expect(takesSignedExpiry(over('code'), object)).toBe(true); + expect(takesSignedExpiry(over('marketplace'), object)).toBe(true); + expect(takesSignedExpiry(over('authored'), object)).toBe(false); + expect(takesSignedExpiry(over(undefined), object)).toBe(false); + }); + + it('yes for a plain registration from code; no for a tenant-authored definition or owner', () => { + expect(takesSignedExpiry({ getObjectOwner: () => ({}) }, object)).toBe(true); + expect(takesSignedExpiry({ getObjectOwner: () => ({ packageId: 'metadata-service' }) }, object)).toBe(false); + expect(takesSignedExpiry({ getObjectOwner: () => ({ definition: { _provenance: 'org' } }) }, object)).toBe(false); + expect(takesSignedExpiry({ getObjectOwner: () => ({}) }, { ...object, _provenance: 'org' } as never)).toBe(false); + }); +}); diff --git a/packages/objectql/src/lifecycle/signed-expiry-scope.ts b/packages/objectql/src/lifecycle/signed-expiry-scope.ts new file mode 100644 index 00000000000..35c41ad5800 --- /dev/null +++ b/packages/objectql/src/lifecycle/signed-expiry-scope.ts @@ -0,0 +1,57 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { isTenantAuthored } from '@objectstack/metadata-core'; + +/** + * [ADR-0154 D8] The registry surface {@link takesSignedExpiry} asks. Each + * member is optional so a double that models only `getAllObjects` stays a + * legal registry: such a registry cannot answer, and the answer is then "no". + */ +export interface SignedExpiryRegistryLike { + /** `SchemaRegistry.getPackagedObjectOwner`: the code-shipped `own` contributor of a name, if any. */ + getPackagedObjectOwner?(name: string): { packageId?: string } | undefined; + /** `SchemaRegistry.getObjectOwner`: the `own` contributor of a name. */ + getObjectOwner?(name: string): { packageId?: string; definition?: unknown } | undefined; + /** `SchemaRegistry.getPackage`: an installed package and the source it was installed from. */ + getPackage?(id: string): { source?: unknown } | undefined; +} + +/** + * [ADR-0154 D8] Whether `object`, a sealed object as the registry resolves it, + * takes the signed expiry and its retention floor. + * + * Signed expiry covers objects whose lifecycle is declared in packaged + * metadata. The answer is yes only when the registry says so positively: + * + * - the resolved definition is not tenant-authored (ADR-0010 + * `_provenance: 'org'`, which a tenant layer over a packaged owner also + * carries, ADR-0029 D9.2); and + * - its owner is a code-shipped contributor of an installed package whose + * source is `code` or `marketplace`, or a plain registration from code + * (an owner with no package at all). + * + * Everything else — an object created at runtime, an owner under a package + * id no installed package answers (the `metadata-service` and `sys_metadata` + * keys among them), a registry that cannot be asked — keeps the row-cutoff + * retention sweep, as before signed expiry existed. A miss therefore falls on + * that sweep, never on a signed expiry. + * + * Shared by the lifecycle service's routing, the audit plugin's floors and the + * sealer's own expiry, so the three cannot disagree on one object. + */ +export function takesSignedExpiry( + registry: SignedExpiryRegistryLike | undefined, + object: { name: string }, +): boolean { + if (!registry || isTenantAuthored(object)) return false; + const packaged = typeof registry.getPackagedObjectOwner === 'function' + ? registry.getPackagedObjectOwner(object.name) + : undefined; + if (packaged) { + if (typeof packaged.packageId !== 'string' || typeof registry.getPackage !== 'function') return false; + const source = registry.getPackage(packaged.packageId)?.source; + return source === 'code' || source === 'marketplace'; + } + const owner = typeof registry.getObjectOwner === 'function' ? registry.getObjectOwner(object.name) : undefined; + return owner !== undefined && owner.packageId === undefined && !isTenantAuthored(owner.definition); +} diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 6245c0ef2a8..bce2850adc2 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -972,7 +972,7 @@ export class AuditPlugin implements Plugin { let failed: string | null = null; this.refreshSealedFloors = () => { try { - registerSealedWindowFloors(floors, engine.registry.getAllObjects()); + registerSealedWindowFloors(floors, engine.registry); failed = null; } catch (err) { const fault = String((err as Error)?.message ?? err); diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts index b1af3819460..18529c8f221 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts @@ -31,8 +31,19 @@ function sweepRig( global: Record | undefined, tenants: Record> = {}, ) { + // The registry's owner reads, as `SchemaRegistry` answers them: an object with a `_packageId` is owned by that + // package (installed from code when it is `app.ledger`), one with none is a plain registration from code. + const ownerOf = (name: string) => objects.find((o) => o.name === name) as { _packageId?: string } | undefined; const engine = { - registry: { getAllObjects: () => objects }, + registry: { + getAllObjects: () => objects, + getPackagedObjectOwner: (name: string) => { + const o = ownerOf(name) as { _packageId?: string; _provenance?: string } | undefined; + return o?._packageId && o._packageId !== 'sys_metadata' && o._provenance !== 'org' ? { packageId: o._packageId } : undefined; + }, + getObjectOwner: (name: string) => (ownerOf(name) ? { packageId: ownerOf(name)!._packageId, definition: ownerOf(name) } : undefined), + getPackage: (id: string) => (id === 'app.ledger' ? { source: 'code' } : undefined), + }, getDriverForObject: () => undefined, find: async (object: string) => (object === 'sys_organization' ? Object.keys(tenants).map((id) => ({ id })) : []), delete: async (_object: string, options: unknown) => { @@ -155,6 +166,19 @@ describe('AuditPlugin — signed expiry covers objects whose lifecycle is declar expect(report.swept).toEqual([expect.objectContaining({ object: 'app_ledger', policy: 'retention', cutoff: isoCutoff('1d') })]); }); + it('an object owned under a package id no installed code or marketplace package answers takes no floor and no expiry', async () => { + // The reload door's shape: a loader-chain body stamped with a package and package provenance. + const unplaced = { ...retained('30d'), fields: FIELDS, _provenance: 'package', _packageId: 'app.unknown' } as never; + const rig = sweepRig([unplaced], { app_ledger: { maxAge: '1d' } }); + const { requests } = await rig.start(); + + const report = await rig.lifecycle.sweep(); + + expect(requests).toEqual([]); + expect(report.floorViolations).toEqual([]); + expect(report.swept).toEqual([expect.objectContaining({ object: 'app_ledger', policy: 'retention', cutoff: isoCutoff('1d') })]); + }); + it('a packaged object still takes its floor and the signed expiry', async () => { const rig = sweepRig([packaged()], { app_ledger: { maxAge: '1d' } }); const { requests } = await rig.start(); @@ -183,23 +207,26 @@ describe('AuditPlugin — signed expiry covers objects whose lifecycle is declar }); describe('sealedWindowFloors — the windows a sealed object is floored at', () => { + /** A registry that places every object as a plain registration from code. */ + const CODE = { getObjectOwner: () => ({}) }; it('a retained or ttl sealed object: one floor per window, at the declared value, by the audit seal', () => { - expect(sealedWindowFloors(retained('30d'))).toEqual([ + expect(sealedWindowFloors(retained('30d'), CODE)).toEqual([ expect.objectContaining({ policy: 'retention', minWindowMs: 30 * DAY, declaredBy: AUDIT_SEAL_FLOOR_REGISTRAR }), ]); expect(sealedWindowFloors({ name: 'app_receipt', lifecycle: { class: 'audit', ttl: { field: 'created_at', expireAfter: '7d' }, seal: SEAL }, - })).toEqual([expect.objectContaining({ policy: 'ttl', minWindowMs: 7 * DAY })]); + }, CODE)).toEqual([expect.objectContaining({ policy: 'ttl', minWindowMs: 7 * DAY })]); }); - it('none for an unsealed object, an archiving one (it expires past `archive.keep`, which no override reaches), or an unparsable window', () => { - expect(sealedWindowFloors({ name: 'app_note', lifecycle: { class: 'audit', retention: { maxAge: '30d' } } })).toEqual([]); + it('none for an unsealed object, an archiving one (it expires past `archive.keep`, which no override reaches), an unparsable window, or one the registry does not place in packaged metadata', () => { + expect(sealedWindowFloors({ name: 'app_note', lifecycle: { class: 'audit', retention: { maxAge: '30d' } } }, CODE)).toEqual([]); expect(sealedWindowFloors({ name: 'sys_audit_log', lifecycle: { class: 'audit', retention: { maxAge: '90d' }, archive: { after: '90d', to: 'archive', keep: '7y' }, seal: SEAL }, - })).toEqual([]); - expect(sealedWindowFloors({ name: 'app_ledger', lifecycle: { class: 'audit', retention: { maxAge: 'soon' }, seal: SEAL } })).toEqual([]); - expect(sealedWindowFloors({ ...retained('30d'), _provenance: 'org' } as never)).toEqual([]); + }, CODE)).toEqual([]); + expect(sealedWindowFloors({ name: 'app_ledger', lifecycle: { class: 'audit', retention: { maxAge: 'soon' }, seal: SEAL } }, CODE)).toEqual([]); + expect(sealedWindowFloors({ ...retained('30d'), _provenance: 'org' } as never, CODE)).toEqual([]); + expect(sealedWindowFloors(retained('30d'), {})).toEqual([]); }); }); diff --git a/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts b/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts index 2a7d2591f8c..2d7b0777749 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/retention-floor.ts @@ -1,7 +1,11 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -import { isTenantAuthored } from '@objectstack/metadata-core'; -import { parseLifecycleDuration, type LifecycleRetentionFloor } from '@objectstack/objectql'; +import { + parseLifecycleDuration, + takesSignedExpiry, + type LifecycleRetentionFloor, + type SignedExpiryRegistryLike, +} from '@objectstack/objectql'; /** * [ADR-0154 D8] On a sealed object, a retention override cannot shorten the @@ -22,8 +26,9 @@ import { parseLifecycleDuration, type LifecycleRetentionFloor } from '@objectsta * key reaches, and its other window decides when a row moves to the archive, * not when it leaves. * - * Which objects: those whose lifecycle is declared in packaged metadata. An - * object created at runtime keeps today's retention sweep (no signed expiry), + * Which objects: those the registry places in packaged metadata + * (`takesSignedExpiry`, the predicate the lifecycle service routes by). Any + * other sealed object keeps the row-cutoff retention sweep (no signed expiry), * and an override applies to it as before, so it takes no floor. */ @@ -69,9 +74,12 @@ function floorOf(object: string, policy: 'retention' | 'ttl', key: string, liter } /** The floors one object definition takes: one per window its sealed expiry runs under, at the declared value. */ -export function sealedWindowFloors(object: { name: string; lifecycle?: unknown }): LifecycleRetentionFloor[] { +export function sealedWindowFloors( + object: { name: string; lifecycle?: unknown }, + registry: SignedExpiryRegistryLike, +): LifecycleRetentionFloor[] { const lc = object.lifecycle as SealedLifecycleLike | undefined; - if (!lc?.seal || lc.archive || isTenantAuthored(object)) return []; + if (!lc?.seal || lc.archive || !takesSignedExpiry(registry, object)) return []; const floors: LifecycleRetentionFloor[] = []; const maxAge = lc.retention?.maxAge; const retentionMs = windowMs(maxAge); @@ -83,17 +91,17 @@ export function sealedWindowFloors(object: { name: string; lifecycle?: unknown } } /** - * Register {@link sealedWindowFloors} for every object `objects` holds. A floor + * Register {@link sealedWindowFloors} for every object `registry` holds. A floor * is keyed by object, policy and registrar, so registering again replaces it: * called again after a declaration changed, the floor follows the declaration. */ export function registerSealedWindowFloors( lifecycle: Required, - objects: ReadonlyArray<{ name: string; lifecycle?: unknown }>, + registry: SignedExpiryRegistryLike & { getAllObjects(): ReadonlyArray<{ name: string; lifecycle?: unknown }> }, ): number { let registered = 0; - for (const object of objects) { - for (const floor of sealedWindowFloors(object)) { + for (const object of registry.getAllObjects()) { + for (const floor of sealedWindowFloors(object, registry)) { lifecycle.registerRetentionFloor(object.name, floor); registered += 1; } diff --git a/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts b/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts index 9983d2f72d4..170a79010e1 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts @@ -91,7 +91,8 @@ export function memoryEngine(objects: ReadonlyArray<{ name: string; fields?: unk const archive = new MemoryStore(); const inserts: Array<{ object: string; row: Row }> = []; const engine: AuditSealerEngine = { - registry: { getAllObjects: () => objects }, + // Each object is a plain registration from code: the registry places it in packaged metadata (`takesSignedExpiry`). + registry: { getAllObjects: () => objects, getObjectOwner: (name: string) => (objects.some((o) => o.name === name) ? {} : undefined) }, getDriverForObject: () => hot, datasource: (name: string) => (name === 'archive' ? archive : undefined), async insert(object, row) { diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index df866918038..d54d7617ec1 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -10,7 +10,7 @@ import type { ICryptoProvider, LockHandle, } from '@objectstack/spec/contracts'; -import { isTenantAuthored } from '@objectstack/metadata-core'; +import { takesSignedExpiry, type SignedExpiryRegistryLike } from '@objectstack/objectql'; import { isMissingTableError } from '@objectstack/types'; import { AUDIT_SEAL_CANON_VERSION, @@ -158,7 +158,8 @@ export interface AuditSealerLogger { /** The engine surface the sealer uses: the signer's, plus the registry and the archive datasource. */ export interface AuditSealerEngine extends SealStorageEngine { - registry: { getAllObjects(): ReadonlyArray<{ name: string; fields?: unknown; lifecycle?: unknown }> }; + /** The object reads, and the owner reads that place an object in packaged metadata ({@link takesSignedExpiry}). */ + registry: SignedExpiryRegistryLike & { getAllObjects(): ReadonlyArray<{ name: string; fields?: unknown; lifecycle?: unknown }> }; datasource?(name: string): SealStorageDriver | undefined; } @@ -211,8 +212,9 @@ interface SealPlan { readonly chainField: string; readonly archiveTo?: string; /** - * ADR-0154 D8: whether the object's lifecycle is declared in packaged metadata, so it takes the signed - * expiry. An object created at runtime (a tenant-authored definition) is sealed but keeps the row-cutoff sweep. + * ADR-0154 D8: whether the registry places the object's lifecycle in packaged metadata, so it takes the signed + * expiry (`takesSignedExpiry`, the lifecycle service's own routing). Any other sealed object is sealed but keeps + * the row-cutoff sweep. */ readonly signedExpiry: boolean; } @@ -431,7 +433,7 @@ export class AuditSealer { continue; } plans.push({ - name: object.name, fields, columns, chainField, signedExpiry: !isTenantAuthored(object), + name: object.name, fields, columns, chainField, signedExpiry: takesSignedExpiry(this.options.engine.registry, object), ...(lifecycle.archive?.to ? { archiveTo: lifecycle.archive.to } : {}), }); } diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 11f46cb558a..c92d2d57002 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1174,12 +1174,12 @@ export const LifecycleSchema = lazySchema(() => strictObject({ }).optional().describe( 'Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside ' + "the platform shows. Only `class: 'audit'` may declare it, and not beside a `retention` or `ttl` " + - "`onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Sealed rows past their " + - '`retention`, `ttl` or `archive.keep` window leave only by whole checkpoints, after a signed expiry ' + - 'amendment names them, so the verifier reads them as expired rather than missing. Signed expiry covers ' + - 'objects whose lifecycle is declared in packaged metadata; an object created at runtime keeps the ' + - 'retention sweep. A retention override ' + - 'cannot shorten the declared window. A tenant-scoped window is set on `organization_id`, so it applies to ' + + "`onlyWhen`, a `ttl` on another field than `created_at`, or rotation `storage`. Signed expiry covers " + + 'objects whose lifecycle is declared in packaged metadata: their sealed rows past their `retention`, `ttl` ' + + 'or `archive.keep` window leave only by whole checkpoints, after a signed expiry amendment names them, so ' + + 'the verifier reads them as expired rather than missing, and on such an object with no `archive` a ' + + 'retention override cannot shorten the declared window. On an object created at runtime the retention ' + + 'sweeper still deletes sealed rows at their row cutoff, which then read as missing. A tenant-scoped window is set on `organization_id`, so it applies to ' + "that organization's chain only where `chainField` is `organization_id`; every other chain (the chain of " + 'rows about no organization, and every chain of an object chained by another column) keeps its rows to ' + 'the longest window set. The window is counted to the start of a ' + From 2a45517cfa6d738d31cd3b8278b43d3444be6f86 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 07:58:36 +0000 Subject: [PATCH 16/16] test(audit): state the signed-expiry scope rule in two test comments An owner under a package id that no installed code or marketplace package answers keeps the row-cutoff sweep, and takes no floor and no expiry. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUd6hon2o34LQSLbZt --- .../src/lifecycle/lifecycle-service.sealed-expiry.test.ts | 3 +-- .../src/audit-seal/audit-seal-retention-floor.test.ts | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts index 1f5a9fc1c32..93550efb1cc 100644 --- a/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts +++ b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts @@ -316,8 +316,7 @@ describe('LifecycleService — a sealed object expires only through the sealed e }); it('a sealed object the registry cannot place in an installed code or marketplace package keeps the row-cutoff sweep', async () => { - // The reload door's shape (`ObjectQLPlugin`): a loader-chain body registered under its own `_packageId`, or - // `metadata-service`, with whatever provenance it carries. Only a positive answer takes the signed expiry. + // An owner under a package id no installed code or marketplace package answers keeps the row-cutoff sweep. const FIELDS = { created_at: { type: 'datetime' }, tenant_id: { type: 'lookup' }, new_value: { type: 'textarea' } }; const sweepOver = async (install?: 'code' | 'marketplace' | 'authored', body: Record = { _packageId: 'app.ledger', _provenance: 'package' }) => { const registry = new SchemaRegistry() as any; diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts index 18529c8f221..f9642fb172b 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-retention-floor.test.ts @@ -167,7 +167,7 @@ describe('AuditPlugin — signed expiry covers objects whose lifecycle is declar }); it('an object owned under a package id no installed code or marketplace package answers takes no floor and no expiry', async () => { - // The reload door's shape: a loader-chain body stamped with a package and package provenance. + // An owner under a package id no installed code or marketplace package answers takes no floor and no expiry. const unplaced = { ...retained('30d'), fields: FIELDS, _provenance: 'package', _packageId: 'app.unknown' } as never; const rig = sweepRig([unplaced], { app_ledger: { maxAge: '1d' } }); const { requests } = await rig.start();