Skip to content
Draft
23 changes: 23 additions & 0 deletions .changeset/31908-p4c-sealed-expiry.md
Original file line number Diff line number Diff line change
@@ -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.
11 changes: 9 additions & 2 deletions content/docs/data-modeling/objects.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions content/docs/deployment/production-readiness.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.).
4 changes: 2 additions & 2 deletions content/docs/references/data/object.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ const result = ApiMethod.parse(data);
| **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record<string, string \| number \| boolean \| object \| object> }` | 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`
Expand Down Expand Up @@ -384,7 +384,7 @@ const result = ApiMethod.parse(data);
| **ttl** | `{ field: string; expireAfter: string; onlyWhen?: Record<string, string \| number \| boolean \| object \| object> }` | 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]`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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 |
Expand Down
14 changes: 8 additions & 6 deletions packages/cli/src/commands/audit/verify.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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' } } }]);
Expand Down Expand Up @@ -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}$/);
Expand Down Expand Up @@ -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', () => {
Expand All @@ -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: [] });
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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)")
Expand All @@ -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(() => {
Expand Down
Loading
Loading