diff --git a/.changeset/34352-seal-default-chain-column.md b/.changeset/34352-seal-default-chain-column.md new file mode 100644 index 00000000000..db26e4ff593 --- /dev/null +++ b/.changeset/34352-seal-default-chain-column.md @@ -0,0 +1,27 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec)!: a sealed object that names no `lifecycle.seal.chainField` is refused at parse when its default chain column `tenant_id` cannot chain its rows + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** accept-set narrowing, shipped as `minor`. A `lifecycle.seal` that names no `chainField` chains each row by the default column `tenant_id` (ADR-0154 D10, note on `chainField`). That default was never judged at authoring. It is now judged by the same rules as a named `chainField`, and the object is refused with one located issue at `lifecycle.seal` in three cases. What run time did with each before: + +- (a) `tenant_id` is not a field of the object. The platform injects `organization_id`, never `tenant_id`, so it must be declared. Before: the object parsed, and the sealer reported it at `error` and sealed none of its rows. +- (b) `tenant_id` has a value that is not one text on every store (a number, boolean, date, datetime, JSON-shaped or multi-value column). Before: the object parsed, and the sealer sealed some or all of its rows (every row whose value the driver returns as a non-string) into the deployment chain with no report. +- (c) `tenant_id` is listed in `lifecycle.seal.valueFields`. Before: the object parsed and was sealed per organization, with the committed column's value carried in clear as the chain in every checkpoint. + +The judgement reads the object's own declared fields plus the columns the platform injects. A `tenant_id` that reaches the object only through an `objectExtensions` entry does not count: such an object is refused at parse, although the sealer, which reads the folded field map, would have sealed it. Declare the column on the object itself. + +The refusal fires wherever `ObjectSchema` parses: `ObjectSchema.create()` and `defineStack()` (strict by default) throw when a code-authored stack's config module is evaluated, and `os validate`, `os build` and the metadata save door refuse it. A definition that reaches the registry without the parse, including a stored `sys_metadata` row loaded at boot, still registers, and the sealer still treats it as before. + +- FROM: `{ name: 'ai_audit_log', fields: { id, created_at, payload }, lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal: { valueFields: ['payload'] } } }` parsed, and its rows were not sealed. +- TO: the same object is refused at `lifecycle.seal`: "`lifecycle.seal` names no `chainField`, so the sealer chains each row by the default chain column `tenant_id`, which is not a field of this object." + +Not moved: an object that declares a text or lookup `tenant_id`, and an object whose `chainField` names a column it has, parse as before. + +The fix: declare a text or lookup `tenant_id` field that holds each row's organization id, or name the chain column, such as the injected tenant column: `seal: { valueFields: ['payload'], chainField: 'organization_id' }`. Removing `tenant_id` from `valueFields` (case (c)) keeps every chain: nothing is re-sealed and `os audit verify` stays ok, since each earlier checkpoint is checked against the columns it was signed with. A fix that changes a row's chain value on an object that already has checkpoints (case (b), or naming a different `chainField`) re-seals the last sealed window, `os audit verify` reports it `listed_twice`, and verifying one organization with `--org` reads the rows sealed before the change as late and unsealed. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 16322cf57f7..4c0e4058173 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -250,10 +250,16 @@ lifecycle: { datetime, JSON-shaped or multi-value column, the injected `updated_at` included), `id` or `created_at` (they order the rows), and a column `valueFields` also lists (the chain value travels in clear in every - checkpoint). Name a text or lookup column holding the organization id. An object that names no chain column and has - no `tenant_id` field still parses, but it is not sealed: the sealer reports - it at `error`. So is an object chained by `organization_id` that its - deployment declares platform-global, which withholds that column. A row whose chain column is empty is + checkpoint). Name a text or lookup column holding the organization id. An object that names no chain column is + chained by `tenant_id`, and that column is held to the same rules: an object + with no `tenant_id` field (the platform never injects one), with a + `tenant_id` whose value is not text, or with `tenant_id` in `valueFields` is + refused at parse time, at `lifecycle.seal`. Declare a text or lookup + `tenant_id`, or name a chain column such as `organization_id`. An object + chained by `organization_id` that its deployment declares platform-global, + which withholds that column, still parses but is not sealed: the sealer + reports it at `error`, as it does any definition that reaches the registry + without the parse. A row whose chain column is empty is sealed with the rows about no organization. `os audit verify --org ` reads the same column, so it reports that organization's rows whichever column holds it. The chain column is fixed once the object has diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 337d3691307..bbd7c4944e8 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -121,7 +121,7 @@ const result = ApiMethod.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **valueFields** | `string[]` | ✅ | Columns that enter each sealed row as salted commitments instead of in clear, so a checkpoint never carries their values; every other declared column enters in clear. Each must name a declared field other than `id` and `created_at`, which order the leaves. | -| **chainField** | `string` | optional | The column whose value names the organization chain each sealed row joins (default `tenant_id`); a row whose value is empty seals into the deployment chain. It must name a declared field or a column the platform injects, such as the tenant column `organization_id`, whose value is one text on every store (not a number, boolean, date, datetime, JSON or multi-value column); not `id` or `created_at`, which order the leaves; and not a `valueFields` member. Fixed once the object has checkpoints. | +| **chainField** | `string` | optional | The column whose value names the organization chain each sealed row joins (default `tenant_id`); a row whose value is empty seals into the deployment chain. It must name a declared field or a column the platform injects, such as the tenant column `organization_id`, whose value is one text on every store (not a number, boolean, date, datetime, JSON or multi-value column); not `id` or `created_at`, which order the leaves; and not a `valueFields` member. Absent, the default `tenant_id` is held to the same rules, and the registry does not inject it: a seal that names no chain column needs a declared text or lookup `tenant_id` field. Fixed once the object has checkpoints. | --- 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 173e2a44995..b3ccdaa82cd 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 @@ -350,4 +350,44 @@ describe('changing chainField on an object that already has checkpoints (ADR-015 expect(scoped.rows.map((r) => [r.chain, r.row, r.verdict, r.sealed])).toEqual([['org:org_b', 'r1', 'late', false]]); expect(scoped.ok).toBe(false); }); + + it('removing the chain column from valueFields changes no chain: nothing is re-sealed and the check stays ok', async () => { + // The fix the spec's default-chain-column refusal gives for `tenant_id` listed in `valueFields`. The chain key + // reads the row's chain value only, never the column set, and each checkpoint is checked against its own + // signed columns, so the earlier checkpoints stay valid under the set they were signed with. + const object = { + name: 'ledger_probe', + fields: { id: { type: 'text' }, created_at: { type: 'datetime' }, action: { type: 'text' }, tenant_id: { type: 'text' }, payload: { type: 'textarea' } }, + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal: { valueFields: ['payload', 'tenant_id'] } as Record }, + }; + const store = memoryEngine([object, { name: 'sys_audit_amendment', fields: {} }] as never); + const crypto = bindingCrypto(); + const signer = new LocalCheckpointSigner({ engine: store.engine, crypto }); + const clock = { now: DAY0 + 12 * H + 30 * 60_000 }; + const run = () => new AuditSealer({ engine: store.engine, crypto, signer: () => signer, logger: recordingLogger(), now: () => clock.now }).runPass(); + const ledger = store.hot.table('ledger_probe'); + ledger.push( + { id: 'r1', created_at: at(8, 10), action: 'update', tenant_id: 'org_a', payload: 'one' }, + { id: 'r2', created_at: at(10, 5), action: 'update', tenant_id: 'org_a', payload: 'two' }, + ); + await run(); + const sealed = () => store.hot.table('sys_audit_checkpoint').map((r) => { + const body = checkpointBodyFromRow(r); + return [r.chain_key, body.kind, body.row_ids.join(',')].join(' '); + }); + const before = sealed(); + + object.lifecycle.seal = { valueFields: ['payload'] }; + ledger.push({ id: 'r3', created_at: at(13, 10), action: 'update', tenant_id: 'org_a', payload: 'three' }); + clock.now = DAY0 + 14 * H + 30 * 60_000; + await run(); + + expect(before).toEqual(['org:org_a window r1', 'org:org_a window r2']); + expect(sealed()).toEqual([...before, 'org:org_a window r3']); + const report = await verifyAuditLedger({ engine: store.engine, crypto, now: () => clock.now }); + expect(report.faults).toEqual([]); + expect(report.ok).toBe(true); + const scoped = await verifyAuditLedger({ engine: store.engine, crypto, now: () => clock.now, orgs: ['org_a'] }); + expect(scoped.ok).toBe(true); + }); }); diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index 23c808908d8..65069d82ee5 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -392,8 +392,8 @@ export class AuditSealer { 'have no canonical rule'; } else if (!Object.prototype.hasOwnProperty.call(fields, chainField)) { // S3: a chain is the row's own chain column (D10 note: `seal.chainField`, default `tenant_id`); without - // it every organization would share one. A NAMED column the object lacks is refused at authoring; this - // stays for the default, and for a definition that reached the registry without the parse. + // it every organization would share one. A chain column the object lacks, named or the default, is + // refused at authoring; this stays for a definition that reached the registry without the parse. reason = `it has no '${chainField}' field, the column its rows are chained by per organization`; } } catch (err) { diff --git a/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts b/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts index dc17ac4b26d..5f0541c9b73 100644 --- a/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts +++ b/packages/spec/src/data/object-lifecycle-seal-chain-field-34164.test.ts @@ -56,8 +56,11 @@ describe('lifecycle.seal.chainField — a column the object has parses, as autho expect(sealOf(input)).toEqual({ valueFields: [], chainField: 'tenant_id' }); }); - it('leaves a seal that names no chain column exactly as before: no key added, no new refusal', () => { - expect(sealOf(ledger({ valueFields: ['payload'] }))).toEqual({ valueFields: ['payload'] }); + it('leaves a seal that names no chain column, on an object that declares tenant_id, as authored: no key added', () => { + // The default chain column is judged too (object-lifecycle-seal-default-chain-column-34352.test.ts). + const input = ledger({ valueFields: ['payload'] }); + (input.fields as Record).tenant_id = { type: 'text', label: 'Organization' }; + expect(sealOf(input)).toEqual({ valueFields: ['payload'] }); }); }); diff --git a/packages/spec/src/data/object-lifecycle-seal-default-chain-column-34352.test.ts b/packages/spec/src/data/object-lifecycle-seal-default-chain-column-34352.test.ts new file mode 100644 index 00000000000..b3bfb8a4a6b --- /dev/null +++ b/packages/spec/src/data/object-lifecycle-seal-default-chain-column-34352.test.ts @@ -0,0 +1,172 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { ObjectSchema } from './object.zod'; +import { ObjectStackDefinitionSchema, defineStack } from '../stack.zod'; +import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; + +// --------------------------------------------------------------------------- +// [ADR-0154 D10, note on `chainField`] A `lifecycle.seal` that names no +// `chainField` chains by the default column `tenant_id`, and that column is +// held to the rules a NAMED `chainField` is: it is a field of the object +// (declared, or injected — the registry injects `organization_id`, never +// `tenant_id`), its value is one text on every store, and `valueFields` does +// not list it. Each refusal is one located issue at `lifecycle.seal`, asserted +// by code, path and the first sentence of its message. The sealer still +// reports such an object at run time for a definition that skips the parse +// (plugin-audit `audit-seal-sealer.test.ts`, "with no tenant_id field"). +// --------------------------------------------------------------------------- + +const AUDIT = { class: 'audit', retention: { maxAge: '90d' } } as const; + +const ledger = (seal: Record, fields: Record = {}, extra: Record = {}) => ({ + name: 'ai_audit_probe', + fields: { + id: { type: 'text', label: 'ID' }, + created_at: { type: 'datetime', label: 'Created At' }, + action: { type: 'text', label: 'Action' }, + payload: { type: 'textarea', label: 'Payload' }, + ...fields, + }, + lifecycle: { ...AUDIT, seal }, + ...extra, +}); + +function issues(input: unknown): Array<{ code: string; path: PropertyKey[]; message: string }> { + const parsed = ObjectSchema.safeParse(input); + expect(parsed.success, 'the declaration must NOT parse clean').toBe(false); + if (parsed.success) return []; + return parsed.error.issues.map((i) => ({ code: i.code, path: i.path, message: i.message })); +} + +function sealOf(input: unknown) { + const parsed = ObjectSchema.safeParse(input); + expect(parsed.success, parsed.success ? '' : JSON.stringify(parsed.error.issues)).toBe(true); + return parsed.success ? parsed.data.lifecycle?.seal : undefined; +} + +const LEAD = /^`lifecycle\.seal` names no `chainField`, so the sealer chains each row by the default chain column `tenant_id`/; + +describe('lifecycle.seal with no chainField — a default tenant_id the object does not have is refused', () => { + it('refuses an object with no tenant_id field, at lifecycle.seal, naming organization_id as the fix', () => { + const [issue, ...rest] = issues(ledger({ valueFields: ['payload'] })); + expect(rest).toEqual([]); + expect(issue.code).toBe('custom'); + expect(issue.path).toEqual(['lifecycle', 'seal']); + expect(issue.message).toMatch(LEAD); + expect(issue.message.split('. ')[0]).toMatch(/`tenant_id`, which is not a field of this object$/); + expect(issue.message).toContain('`organization_id`, the tenant column the platform injects'); + }); + + it.each([ + ['systemFields.tenant: false', { systemFields: { tenant: false } }], + ['tenancy.enabled: false', { tenancy: { enabled: false } }], + ])('names a declared column, not organization_id, where the registry injects no tenant column (%s)', (_label, extra) => { + const [issue, ...rest] = issues(ledger({ valueFields: [] }, {}, extra)); + expect(rest).toEqual([]); + expect(issue.path).toEqual(['lifecycle', 'seal']); + expect(issue.message).toMatch(LEAD); + expect(issue.message).not.toContain('organization_id'); + }); +}); + +describe('lifecycle.seal with no chainField — a default tenant_id whose value is not one text on every store is refused', () => { + it.each([ + ['number', { type: 'number' }], + ['boolean', { type: 'boolean' }], + ['datetime', { type: 'datetime' }], + ['json', { type: 'json' }], + ['multiselect', { type: 'multiselect', options: [{ label: 'A', value: 'org_a' }] }], + ['lookup (multi-value)', { type: 'lookup', reference: 'sys_organization', multiple: true }], + ])('refuses a declared %s tenant_id, at lifecycle.seal', (type, def) => { + const [issue, ...rest] = issues(ledger({ valueFields: [] }, { tenant_id: { label: 'Organization', ...def } })); + expect(rest).toEqual([]); + expect(issue.code).toBe('custom'); + expect(issue.path).toEqual(['lifecycle', 'seal']); + expect(issue.message).toMatch(LEAD); + expect(issue.message.split('. ')[0]).toContain(`\`tenant_id\`, a \`${type}\` column, whose value is not one text on every store`); + }); +}); + +describe('lifecycle.seal with no chainField — a default tenant_id that valueFields lists is refused', () => { + it('refuses tenant_id listed in valueFields, at lifecycle.seal', () => { + const [issue, ...rest] = issues(ledger({ valueFields: ['payload', 'tenant_id'] }, { tenant_id: { type: 'text', label: 'Organization' } })); + expect(rest).toEqual([]); + expect(issue.code).toBe('custom'); + expect(issue.path).toEqual(['lifecycle', 'seal']); + expect(issue.message).toMatch(LEAD); + expect(issue.message.split('. ')[0]).toMatch(/`tenant_id`, which `lifecycle\.seal\.valueFields` also lists$/); + }); +}); + +describe('lifecycle.seal — CONTROLS that still parse', () => { + it.each([ + ['text', { type: 'text' }], + ['lookup', { type: 'lookup', reference: 'sys_organization' }], + ])('a seal naming no chainField on an object that declares a %s tenant_id', (_label, def) => { + expect(sealOf(ledger({ valueFields: ['payload'] }, { tenant_id: { label: 'Organization', ...def } }))).toEqual({ valueFields: ['payload'] }); + }); + + it('a chainField naming a declared field, on an object with no tenant_id', () => { + expect(sealOf(ledger({ valueFields: ['payload'], chainField: 'org_ref' }, { org_ref: { type: 'text', label: 'Org' } }))) + .toEqual({ valueFields: ['payload'], chainField: 'org_ref' }); + }); + + it('a chainField naming the injected organization_id, on an object with no tenant_id', () => { + expect(sealOf(ledger({ valueFields: ['payload'], chainField: 'organization_id' }))) + .toEqual({ valueFields: ['payload'], chainField: 'organization_id' }); + }); + + it('a named chainField leaves tenant_id unjudged: a number tenant_id parses beside chainField organization_id', () => { + expect(sealOf(ledger({ valueFields: [], chainField: 'organization_id' }, { tenant_id: { type: 'number', label: 'Legacy' } }))) + .toEqual({ valueFields: [], chainField: 'organization_id' }); + }); +}); + +describe('lifecycle.seal with no chainField — the doors that parse ObjectSchema refuse it too', () => { + const unchainable = () => ledger({ valueFields: ['payload'] }); + + it('the stack definition `os validate` and `os build` parse', () => { + const parsed = ObjectStackDefinitionSchema.safeParse({ objects: [unchainable()] }); + expect(parsed.success).toBe(false); + if (parsed.success) return; + expect(parsed.error.issues.filter((i) => LEAD.test(i.message)).map((i) => i.path)).toEqual([['objects', 0, 'lifecycle', 'seal']]); + }); + + const thrown = (fn: () => unknown): { code?: unknown; issues?: Array<{ path: PropertyKey[]; message: string }> } => { + try { + fn(); + } catch (e) { + return e as never; + } + throw new Error('expected a throw'); + }; + + it('ObjectSchema.create(), the authoring factory a config module calls, throws the located issue', () => { + const e = thrown(() => ObjectSchema.create(unchainable() as never)); + expect((e.issues ?? []).filter((i) => LEAD.test(i.message)).map((i) => i.path)).toEqual([['lifecycle', 'seal']]); + }); + + it('defineStack(), strict by default, throws STACK_SCHEMA_INVALID when a config module carrying the object is evaluated', () => { + const e = thrown(() => defineStack({ objects: [unchainable()] } as never)); + expect(e.code).toBe('STACK_SCHEMA_INVALID'); + expect((e.issues ?? []).filter((i) => LEAD.test(i.message)).map((i) => i.path)).toEqual([['objects', 0, 'lifecycle', 'seal']]); + }); + + it('counts only the object\'s own fields: a tenant_id contributed by objectExtensions alone is still refused', () => { + const extension = { extend: 'ai_audit_probe', fields: { tenant_id: { type: 'text', label: 'Organization' } } }; + const parsed = ObjectStackDefinitionSchema.safeParse({ objects: [unchainable()], objectExtensions: [extension] }); + expect(parsed.success).toBe(false); + if (parsed.success) return; + expect(parsed.error.issues.filter((i) => LEAD.test(i.message)).map((i) => i.path)).toEqual([['objects', 0, 'lifecycle', 'seal']]); + }); + + it("the metadata type schema the save door judges an object against (getMetadataTypeSchema('object'))", () => { + const schema = getMetadataTypeSchema('object'); + expect(schema).toBeDefined(); + const parsed = schema!.safeParse(unchainable()); + expect(parsed.success).toBe(false); + if (parsed.success) return; + expect(parsed.error.issues.filter((i) => LEAD.test(i.message)).map((i) => i.path)).toEqual([['lifecycle', 'seal']]); + }); +}); diff --git a/packages/spec/src/data/object-lifecycle-seal.test.ts b/packages/spec/src/data/object-lifecycle-seal.test.ts index 43bb28686bc..0b5dc2ca69c 100644 --- a/packages/spec/src/data/object-lifecycle-seal.test.ts +++ b/packages/spec/src/data/object-lifecycle-seal.test.ts @@ -21,6 +21,8 @@ const ledger = (lifecycle: Record, fields: Record { it('is a known key at the authoring factory, so `ObjectSchema.create()` takes it', () => { const created = ObjectSchema.create({ name: 'compliance_ledger_probe', - fields: { id: { type: 'text', label: 'ID' }, old_value: { type: 'textarea', label: 'Old Value' } }, + fields: { + id: { type: 'text', label: 'ID' }, + old_value: { type: 'textarea', label: 'Old Value' }, + tenant_id: { type: 'lookup', reference: 'sys_organization', label: 'Organization' }, + }, lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal: { valueFields: ['old_value'] } }, }); expect(created.lifecycle?.seal).toEqual({ valueFields: ['old_value'] }); diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index ae4e92315ba..2c21ba80c31 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1141,7 +1141,9 @@ export const LifecycleSchema = lazySchema(() => strictObject({ 'whose value is empty seals into the deployment chain. It must name a declared field or a column the ' + 'platform injects, such as the tenant column `organization_id`, whose value is one text on every store ' + '(not a number, boolean, date, datetime, JSON or multi-value column); not `id` or `created_at`, which ' + - 'order the leaves; and not a `valueFields` member. Fixed once the object has checkpoints.', + 'order the leaves; and not a `valueFields` member. Absent, the default `tenant_id` is held to the same ' + + 'rules, and the registry does not inject it: a seal that names no chain column needs a declared text or ' + + 'lookup `tenant_id` field. Fixed once the object has checkpoints.', ), }).optional().describe( 'Seals the rows into signed, chained checkpoints (ADR-0154), so a change, insert or delete made outside ' + @@ -3206,6 +3208,108 @@ function refuseUndeclaredSealValueFields(lifecycle: unknown, fields: unknown, ct }); } +/** + * [ADR-0154 D10, note on `chainField`] The chain column a seal that names no + * `chainField` reads: the sealer's default (`AUDIT_SEAL_DEFAULT_CHAIN_FIELD` + * in `@objectstack/plugin-audit`). + */ +const SEAL_DEFAULT_CHAIN_FIELD = 'tenant_id'; + +/** Why a column cannot be a sealed object's chain column ({@link sealChainColumnFaults}). */ +type SealChainColumnFault = + | { kind: 'not-a-field' } + | { kind: 'leaf-order' } + | { kind: 'value-field' } + | { kind: 'non-text'; type: string }; + +/** + * The faults that keep `name` from being this sealed object's chain column, in + * the order they are judged; empty when it can be. One judgement for a named + * `chainField` and for the default `tenant_id` + * ({@link refuseUnknownSealChainField}): a column the object does not have + * stops the judgement, and so does a leaf-order column; a `valueFields` member + * and a column whose value is not one text on every store are each a fault. + * + * "Has" means the AUTHORED field map plus the injected plan, as the + * `valueFields` check reads it. A column contributed only by an + * `objectExtensions` entry is not counted, so a sealed object whose chain + * column (named, or the default `tenant_id`) reaches it only that way is + * refused here, although the sealer, which reads the registry's folded field + * map, would seal it. That false refusal is accepted: the fix is to declare + * the column on the object itself. + */ +function sealChainColumnFaults( + object: { fields?: unknown }, + seal: { valueFields?: unknown }, + name: string, +): SealChainColumnFault[] { + const declared = (object.fields !== null && typeof object.fields === 'object' ? object.fields : {}) as Record; + const isDeclared = Object.prototype.hasOwnProperty.call(declared, name); + if (!isDeclared && !resolveInjectedSystemColumns(object).names.has(name)) return [{ kind: 'not-a-field' }]; + if (isSealLeafOrderColumn(name)) return [{ kind: 'leaf-order' }]; + const faults: SealChainColumnFault[] = []; + if (Array.isArray(seal.valueFields) && seal.valueFields.includes(name)) faults.push({ kind: 'value-field' }); + const nonText = nonTextChainColumnType(isDeclared ? declared[name] : injectedSystemColumnDefs(object)[name]); + if (nonText !== null) faults.push({ kind: 'non-text', type: nonText }); + return faults; +} + +/** The message of a refused NAMED `chainField`. */ +function namedSealChainFieldMessage(name: string, fault: SealChainColumnFault): string { + switch (fault.kind) { + case 'not-a-field': + return `\`lifecycle.seal.chainField\` names \`${name}\`, which is not a field of this object. ` + + 'The sealer chains each row by that column\'s value, one chain per organization, so it must name a ' + + 'declared field or a column the platform injects (the tenant column is `organization_id`); declare ' + + 'the field, name another, or remove the key to chain by `tenant_id` (ADR-0154 D10).'; + case 'leaf-order': + return `\`lifecycle.seal.chainField\` cannot name \`${name}\`: it orders each sealed leaf, and it names no ` + + 'organization. Name the column that holds the organization id of each row, such as `organization_id` ' + + '(ADR-0154 D10).'; + case 'value-field': + return `\`lifecycle.seal.chainField\` names \`${name}\`, which \`lifecycle.seal.valueFields\` also lists. ` + + 'A value field enters each sealed leaf as a salted commitment so a checkpoint never carries it, but ' + + 'the chain value travels in clear in every checkpoint and proof bundle of its chain; remove it from ' + + '`valueFields`, or name another chain column (ADR-0154 D1, D9, D10).'; + case 'non-text': + return `\`lifecycle.seal.chainField\` names \`${name}\`, a \`${fault.type}\` column, whose value is not one text on ` + + 'every store. The sealer reads a row\'s chain as a non-empty text only, so the rows would seal into ' + + 'the deployment chain with no report; name a text or lookup column that holds the organization id, ' + + 'such as `organization_id` (ADR-0154 D10).'; + } +} + +/** + * The message of a refused DEFAULT chain column. `fix` names the chain column + * to name instead: the injected tenant column where the registry injects it, + * otherwise a declared column — on an object that opts out of the tenant + * column, `organization_id` would itself be refused. + */ +function defaultSealChainColumnMessage(fault: SealChainColumnFault, injectsTenantColumn: boolean): string { + const name = SEAL_DEFAULT_CHAIN_FIELD; + const lead = `\`lifecycle.seal\` names no \`chainField\`, so the sealer chains each row by the default chain column \`${name}\``; + const other = injectsTenantColumn + ? 'name the chain column with `chainField`, such as `organization_id`, the tenant column the platform injects' + : 'name a declared text or lookup column that holds it with `chainField`'; + switch (fault.kind) { + case 'not-a-field': + case 'leaf-order': // never for `tenant_id`; judged alike so the switch stays total + return `${lead}, which is not a field of this object. The sealer cannot chain the rows per organization ` + + 'without that column, so it would seal none of them and only report the object at run time; ' + + `declare a \`${name}\` text or lookup field that holds each row's organization id, or ${other} ` + + '(ADR-0154 D10).'; + case 'value-field': + return `${lead}, which \`lifecycle.seal.valueFields\` also lists. A value field enters each sealed leaf as a ` + + 'salted commitment so a checkpoint never carries it, but the chain value travels in clear in every ' + + `checkpoint and proof bundle of its chain; remove \`${name}\` from \`valueFields\`, or ${other} ` + + '(ADR-0154 D1, D9, D10).'; + case 'non-text': + return `${lead}, a \`${fault.type}\` column, whose value is not one text on every store. The sealer reads a ` + + 'row\'s chain as a non-empty text only, so the rows would seal into the deployment chain with no report; ' + + `declare \`${name}\` as a text or lookup field that holds the organization id, or ${other} (ADR-0154 D10).`; + } +} + /** * [ADR-0154 D10, note on `chainField`] A `lifecycle.seal.chainField` the * author names is a field the object has: one it declares, or a column the @@ -3221,15 +3325,21 @@ function refuseUndeclaredSealValueFields(lifecycle: unknown, fields: unknown, ct * one text on every store ({@link nonTextChainColumnType}), judged by the * declared field or, for an injected column, by the definition the registry * injects ({@link injectedSystemColumnDefs}). Each is one located issue at - * `['lifecycle', 'seal', 'chainField']`. Every refusal here needs the key, which - * did not exist before it, so none refuses a declaration that parsed before. - * - * Only a NAMED chain column is judged here. An object that names none chains - * by `tenant_id`, as before the key existed, and one without that column is - * reported by the sealer at `error`, as before. The injected plan is read with - * no deployment, as every author-time caller reads it; a deployment that - * declares the object platform-global withholds the tenant column, and the - * sealer reports that object the same way. + * `['lifecycle', 'seal', 'chainField']`. + * + * An object that names NO chain column chains by its default, `tenant_id`, and + * that column is held to the same rules ({@link sealChainColumnFaults}, one + * judgement for both): it must be a field of the object, its value one text on + * every store, and not a `valueFields` member. The registry injects no + * `tenant_id` (its tenant column is `organization_id`), so in practice the + * default must be declared. Each refusal of the default is one located issue at + * `['lifecycle', 'seal']`, the block the author wrote: there is no + * `chainField` to point at, and naming one is half of every fix. Before this + * rule such an object parsed and the sealer reported it at `error` and sealed + * none of its rows, which it still does for a definition that skips the parse. + * The injected plan is read with no deployment, as every author-time caller + * reads it; a deployment that declares the object platform-global withholds + * the tenant column, and the sealer reports that object the same way. * * `injected-system-columns` imports this module (for `isTenancyDisabled`), so * the two form an import cycle. Each side calls the other only from inside a @@ -3239,59 +3349,22 @@ function refuseUndeclaredSealValueFields(lifecycle: unknown, fields: unknown, ct function refuseUnknownSealChainField(object: { lifecycle?: unknown; fields?: unknown }, ctx: z.RefinementCtx): void { const lifecycle = object.lifecycle; if (lifecycle === null || typeof lifecycle !== 'object') return; - const seal = (lifecycle as { seal?: { chainField?: unknown } }).seal; - if (!seal || typeof seal.chainField !== 'string') return; - const name = seal.chainField; - const path = ['lifecycle', 'seal', 'chainField']; - const declared = (object.fields !== null && typeof object.fields === 'object' ? object.fields : {}) as Record; - const isDeclared = Object.prototype.hasOwnProperty.call(declared, name); - if (!isDeclared && !resolveInjectedSystemColumns(object).names.has(name)) { - ctx.addIssue({ - code: 'custom', - path, - message: - `\`lifecycle.seal.chainField\` names \`${name}\`, which is not a field of this object. ` - + 'The sealer chains each row by that column\'s value, one chain per organization, so it must name a ' - + 'declared field or a column the platform injects (the tenant column is `organization_id`); declare ' - + 'the field, name another, or remove the key to chain by `tenant_id` (ADR-0154 D10).', - }); - return; - } - if (isSealLeafOrderColumn(name)) { - ctx.addIssue({ - code: 'custom', - path, - message: - `\`lifecycle.seal.chainField\` cannot name \`${name}\`: it orders each sealed leaf, and it names no ` - + 'organization. Name the column that holds the organization id of each row, such as `organization_id` ' - + '(ADR-0154 D10).', - }); + const seal = (lifecycle as { seal?: { chainField?: unknown; valueFields?: unknown } }).seal; + if (!seal || typeof seal !== 'object') return; + if (typeof seal.chainField === 'string') { + const name = seal.chainField; + for (const fault of sealChainColumnFaults(object, seal, name)) { + ctx.addIssue({ code: 'custom', path: ['lifecycle', 'seal', 'chainField'], message: namedSealChainFieldMessage(name, fault) }); + } return; } - const valueFields = (seal as { valueFields?: unknown }).valueFields; - if (Array.isArray(valueFields) && valueFields.includes(name)) { - ctx.addIssue({ - code: 'custom', - path, - message: - `\`lifecycle.seal.chainField\` names \`${name}\`, which \`lifecycle.seal.valueFields\` also lists. ` - + 'A value field enters each sealed leaf as a salted commitment so a checkpoint never carries it, but ' - + 'the chain value travels in clear in every checkpoint and proof bundle of its chain; remove it from ' - + '`valueFields`, or name another chain column (ADR-0154 D1, D9, D10).', - }); - } - const def = isDeclared ? declared[name] : injectedSystemColumnDefs(object)[name]; - const nonText = nonTextChainColumnType(def); - if (nonText !== null) { - ctx.addIssue({ - code: 'custom', - path, - message: - `\`lifecycle.seal.chainField\` names \`${name}\`, a \`${nonText}\` column, whose value is not one text on ` - + 'every store. The sealer reads a row\'s chain as a non-empty text only, so the rows would seal into ' - + 'the deployment chain with no report; name a text or lookup column that holds the organization id, ' - + 'such as `organization_id` (ADR-0154 D10).', - }); + // A `chainField` of another type is the key's own type refusal; only an absent one reads the default. + if (seal.chainField !== undefined) return; + const faults = sealChainColumnFaults(object, seal, SEAL_DEFAULT_CHAIN_FIELD); + if (faults.length === 0) return; + const injectsTenantColumn = resolveInjectedSystemColumns(object).tenant; + for (const fault of faults) { + ctx.addIssue({ code: 'custom', path: ['lifecycle', 'seal'], message: defaultSealChainColumnMessage(fault, injectsTenantColumn) }); } } diff --git a/packages/spec/src/migrations/entries/semantic/18.seal-default-chain-column-refused.ts b/packages/spec/src/migrations/entries/semantic/18.seal-default-chain-column-refused.ts new file mode 100644 index 00000000000..0fb3855297e --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.seal-default-chain-column-refused.ts @@ -0,0 +1,39 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +export const entry: SemanticMigration = { + id: 'seal-default-chain-column-refused', + surface: + 'data.Object.lifecycle.seal with no chainField (ObjectSchema: ObjectSchema.create() and defineStack() throw when a ' + + 'config module is evaluated; os validate, os build and the metadata save door refuse): ' + + 'an audit-class object whose default chain column tenant_id is not a field of the object, has a value that is ' + + 'not one text on every store, or is listed in lifecycle.seal.valueFields', + replacement: + 'Declare a text or lookup tenant_id field that holds each row\'s organization id, or name the chain column with ' + + 'lifecycle.seal.chainField, such as the tenant column the platform injects: ' + + 'seal: { valueFields: [...], chainField: \'organization_id\' }', + reason: + 'A seal that names no chainField chains each row by tenant_id (ADR-0154 D10, note on chainField). That default ' + + 'was never judged at authoring, and such an object parsed. At run time the sealer reported an object with no ' + + 'tenant_id field at error and sealed none of its rows; sealed some or all rows of one with a non-text tenant_id ' + + '(every row whose value the driver returns as a non-string) into the deployment chain with no report; and ' + + 'sealed one that lists tenant_id in valueFields per organization, ' + + 'carrying the committed value in clear as the chain. The ' + + 'parse now holds the default to the rules a named chainField meets and refuses the object at lifecycle.seal. ' + + 'The registry injects organization_id, never tenant_id. A definition that skips the parse (a stored row loaded ' + + 'at boot, a raw registration) still registers, and the sealer treats it as before. The judgement reads the ' + + 'object\'s own fields and the injected columns, so a tenant_id contributed only by an objectExtensions entry ' + + 'does not count. There is no mechanical rewrite: ' + + 'which column holds each row\'s organization is the author\'s choice, and a fix that changes the chain value of ' + + 'rows on an object that already has checkpoints re-seals its last sealed window.', + acceptanceCriteria: + 'os validate passes for every sealed object; each one names a chainField it has, or declares a text or lookup ' + + 'tenant_id outside valueFields. Removing tenant_id from valueFields keeps every chain: nothing is re-sealed and ' + + 'os audit verify stays ok, since each earlier checkpoint is checked against the columns it was signed with. A ' + + 'fix that changes a row\'s chain value on an object that already has checkpoints (a non-text tenant_id fixed, or ' + + 'a different chainField named) re-seals the last sealed window: os audit verify reports it listed_twice, and ' + + 'verifying one organization with --org reads the rows sealed before the change as late and unsealed ' + + '(ADR-0154 D10 note); expect those findings for that object only. An object that had no tenant_id field had no ' + + 'checkpoints, and verifies ok once it seals.', +}; diff --git a/skills/objectstack-data/evals/objects-fields-relationships.json b/skills/objectstack-data/evals/objects-fields-relationships.json index 94b034a8b17..28fccae48ce 100644 --- a/skills/objectstack-data/evals/objects-fields-relationships.json +++ b/skills/objectstack-data/evals/objects-fields-relationships.json @@ -275,7 +275,7 @@ { "id": 16, "prompt": "Our `consent_change` audit log must show it if anyone edits, inserts or deletes rows directly in the database, but whatever proof is stored must not carry the consent text itself. How do I declare that?", - "expected_output": "Keep `lifecycle.class: 'audit'` with its bounding `retention` (or a `ttl` on `created_at`) and add `seal: { valueFields: ['consent_text'] }`: the audit plugin signs each `created_at` hour into one checkpoint per organization, chained to the one before, where `valueFields` columns enter as salted commitments and every other column in clear. The object declares its own `id` and `tenant_id` fields; without them it parses but is not sealed, and the sealer reports it at `error` each hour. Refused at parse: `seal` on a class other than `audit`, `valueFields` naming `id`, `created_at` or an undeclared field, and beside `seal` a `retention` or `ttl` `onlyWhen`, a `ttl` on another field, or rotation `storage`. Two limits today: no verifier reads the checkpoints back yet, so a break is recorded but not reported; and until expiry ships, the sweeper still deletes sealed rows, which then read as missing. Field history is not tamper evidence.", + "expected_output": "Keep `lifecycle.class: 'audit'` with its bounding `retention` (or a `ttl` on `created_at`) and add `seal: { valueFields: ['consent_text'] }`: the audit plugin signs each `created_at` hour into one checkpoint per organization, chained to the one before, where `valueFields` columns enter as salted commitments and every other column in clear. The object declares its own `id` and a text or lookup `tenant_id` field; without that `tenant_id` (and with no `chainField` naming another chain column, such as the injected `organization_id`) it is refused at parse, and without `id` it parses but is not sealed, and the sealer reports it at `error` each hour. Refused at parse: `seal` on a class other than `audit`, `valueFields` naming `id`, `created_at` or an undeclared field, and beside `seal` a `retention` or `ttl` `onlyWhen`, a `ttl` on another field, or rotation `storage`. Two limits today: no verifier reads the checkpoints back yet, so a break is recorded but not reported; and until expiry ships, the sweeper still deletes sealed rows, which then read as missing. Field history is not tamper evidence.", "files": [], "assertions": { "must_contain": [ diff --git a/skills/objectstack-data/rules/lifecycle.md b/skills/objectstack-data/rules/lifecycle.md index 07720a5f9b2..d5834bd8ee8 100644 --- a/skills/objectstack-data/rules/lifecycle.md +++ b/skills/objectstack-data/rules/lifecycle.md @@ -156,10 +156,10 @@ export const PolicyChangeLog = ObjectSchema.create({ seal: { valueFields: ['created_at'] } ``` -Also refused: `seal` off class `audit`, an undeclared `valueFields` name, and -beside `seal` any `onlyWhen`, a `ttl` not on `created_at`, or rotation -`storage`. Not sealed, reported at `error` hourly: no declared `id` or -`tenant_id` (the injected tenant column is `organization_id`); a `password`, +Also refused: `seal` off class `audit`, an undeclared `valueFields` name, no +text `tenant_id` outside `valueFields` (or `chainField: 'organization_id'`), +and beside `seal` any `onlyWhen`, a `ttl` not on `created_at`, or rotation +`storage`. Unsealed, `error` hourly: no declared `id`; a `password`, `secret`, `formula`, `summary`, `image`, `file`, `avatar`, `video` or `audio` column; no `cryptoProvider` on `AuditPlugin`. Not built yet (ADR-0154): a verifier, so a break is recorded but not reported; expiry (P4), so the sweeper