diff --git a/.changeset/31908-p4c-sealed-expiry.md b/.changeset/31908-p4c-sealed-expiry.md new file mode 100644 index 00000000000..8ed154695bf --- /dev/null +++ b/.changeset/31908-p4c-sealed-expiry.md @@ -0,0 +1,23 @@ +--- +'@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). +- **`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`. +- **`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 4243eccfdb7..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 @@ -274,8 +277,12 @@ 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. 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/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.). 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/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/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..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)); @@ -457,7 +469,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/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.sealed-expiry.test.ts b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts new file mode 100644 index 00000000000..89c909b780f --- /dev/null +++ b/packages/objectql/src/lifecycle/lifecycle-service.sealed-expiry.test.ts @@ -0,0 +1,249 @@ +// 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 { assertEngineDeleteDispatch } from '@objectstack/metadata-core'; +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[] | 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 }; + }, + }; + 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 as string).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/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; 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 85f025b9c3d..411619cad35 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,32 @@ export class AuditPlugin implements Plugin { logger: ctx.logger, }); 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); + } + + /** + * [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 +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; await sealer?.stop(); const writer = this.readAuditWriter; this.readAuditWriter = null; 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)', () => { 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) { 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",