From 1ab94153beea405f2de599076c1a0c33846b549c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:54:18 +0000 Subject: [PATCH 1/2] fix(lint): judge the one-hop leaf through a lookup an object extension adds The expression rule's hop checks (refuseUndeclaredHopField and the stored-metadata-body hop refusal) looked the reference up on the declared objects, so a misspelt leaf behind a lookup an objectExtensions entry adds passed os build and the object_extension publish door. They now read the object as served (typedObjects: extension fields folded in, a field two packages tie on left out), at both doors. The object walk's own field-reference verdict stays on the declared body. Adds the ADR-0087 semantic entry object-extension-added-lookup-hop-leaf-judged. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5ny58hH1bcw97uPpgu --- ...runtime-gate.object-formula-writes.test.ts | 129 ++++++++++++++++++ packages/lint/src/validate-expressions.ts | 51 +++++-- .../meta-object-extension-item.test.ts | 75 ++++++++++ ...-extension-added-lookup-hop-leaf-judged.ts | 41 ++++++ 4 files changed, 281 insertions(+), 15 deletions(-) create mode 100644 packages/spec/src/migrations/entries/semantic/18.object-extension-added-lookup-hop-leaf-judged.ts diff --git a/packages/lint/src/runtime-gate.object-formula-writes.test.ts b/packages/lint/src/runtime-gate.object-formula-writes.test.ts index f1187687dff..dc36fdcd651 100644 --- a/packages/lint/src/runtime-gate.object-formula-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-formula-writes.test.ts @@ -598,3 +598,132 @@ describe('#33154 — an extension\'s validation rules are judged at the build an expect(expressionFindings(result.errors).map((f) => f.where)).toEqual(["object 'fx_ticket' · validation 'own_typo'"]); }); }); + +describe('#33216 — the one-hop leaf through a lookup an extension adds is judged as one through a declared lookup', () => { + /** The extended object, as the door's live universe carries it: one declared lookup. */ + const target = { + name: 'fx_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: { + employee: { type: 'lookup', label: 'Employee', reference: 'fx_staff' }, + amount: { type: 'number', label: 'Amount' }, + }, + }; + const staff = { + name: 'fx_staff', label: 'Staff', sharingModel: 'private', + fields: { daily_hours: { type: 'number', label: 'Daily Hours' } }, + }; + /** The lookup the extension adds, to the same target as the declared one. */ + const MANAGER = { manager__c: { type: 'lookup', label: 'Manager', reference: 'fx_staff' } }; + /** A rule reading `record.REF.LEAF`, gated on the reference as the traversal check prescribes. */ + const hopRule = (ref: string, leaf: string) => ({ + name: 'long_day', type: 'conditional', message: 'Refused.', + when: `record.${ref} != null`, + then: { name: 'hours', type: 'script', condition: `record.${ref}.${leaf} > 12`, message: 'Refused.' }, + }); + const ruleExtension = (ref: string, leaf: string) => + ({ extend: 'fx_ticket', fields: { ...MANAGER }, validations: [hopRule(ref, leaf)] }); + const formulaExtension = (ref: string, leaf: string) => ({ + extend: 'fx_ticket', + fields: { ...MANAGER, hours__c: { type: 'formula', label: 'Hours', expression: `record.${ref}.${leaf}` } }, + }); + const RULE_WHERE = "object 'fx_ticket' · objectExtensions[0] · validation rule 'long_day' then → 'hours'"; + const FORMULA_WHERE = "object 'fx_ticket' · objectExtensions[0] · field 'hours__c' expression"; + const gateExtension = (item: unknown, objects: unknown[] = [target, staff]) => + runRuntimeAuthoringRules({ type: 'object_extension', item, context: { objects } }); + const buildFindings = (stack: Record) => + runAuthoringRules('build', { normalized: stack, parsed: stack }).filter((f) => f.where.includes('objectExtensions')); + /** The verdict with the reference's name taken out, so a declared and an added lookup compare. */ + const anonymous = (message: string, ref: string) => message.split(ref).join('REF'); + + it('⭐ LIT — a RULE reading a misspelt leaf through the added lookup is REFUSED at the door and the build, with the declared-lookup verdict', () => { + const item = ruleExtension('manager__c', 'daly_hours'); + const atDoor = gateExtension(item); + const errs = expressionFindings(atDoor.errors); + expect(errs, dump(atDoor)).toHaveLength(1); + expect(errs[0]).toMatchObject({ + severity: 'error', + where: RULE_WHERE, + path: 'objectExtensions[0].validations[0].then.condition', + }); + expect(errs[0]!.message).toContain('daly_hours'); + expect(errs[0]!.message).toContain('fx_staff'); + + // The build gives the same finding, byte for byte. + expect(buildFindings({ objects: [target, staff], objectExtensions: [item] })).toEqual([...atDoor.errors, ...atDoor.advisories]); + + // The same misspelling through the lookup the target DECLARES gets the same verdict. + const declared = expressionFindings(gateExtension(ruleExtension('employee', 'daly_hours')).errors); + expect(declared, dump(declared)).toHaveLength(1); + expect(anonymous(errs[0]!.message, 'manager__c')).toBe(anonymous(declared[0]!.message, 'employee')); + }); + + it('⭐ LIT — a FORMULA an extension adds reading a misspelt leaf through the added lookup is REFUSED at the door and the build', () => { + const item = formulaExtension('manager__c', 'daly_hours'); + const atDoor = gateExtension(item); + const errs = expressionFindings(atDoor.errors); + expect(errs, dump(atDoor)).toHaveLength(1); + expect(errs[0]).toMatchObject({ severity: 'error', where: FORMULA_WHERE }); + expect(errs[0]!.message).toContain('daly_hours'); + expect(buildFindings({ objects: [target, staff], objectExtensions: [item] })).toEqual([...atDoor.errors, ...atDoor.advisories]); + + const declared = expressionFindings(gateExtension(formulaExtension('employee', 'daly_hours')).errors); + expect(declared, dump(declared)).toHaveLength(1); + expect(anonymous(errs[0]!.message, 'manager__c')).toBe(anonymous(declared[0]!.message, 'employee')); + }); + + it('⭐ LIT — the object\'s OWN formula reading through a lookup a package\'s extension adds is refused at the build, at the object', () => { + const own = { ...target, fields: { ...target.fields, hours: { type: 'formula', label: 'Hours', expression: 'record.manager__c.daly_hours' } } }; + const stack = { objects: [own, staff], objectExtensions: [{ extend: 'fx_ticket', fields: { ...MANAGER } }] }; + const found = validateStackExpressions(stack).filter((i) => i.severity === 'error'); + expect(found.map((i) => i.where), dump(found)).toEqual(["object 'fx_ticket' · field 'hours' expression"]); + expect(found[0]!.message).toContain('daly_hours'); + + // CONTROL — the leaf the target declares. + const ok = { ...own, fields: { ...own.fields, hours: { type: 'formula', label: 'Hours', expression: 'record.manager__c.daily_hours' } } }; + expect(validateStackExpressions({ ...stack, objects: [ok, staff] }).filter((i) => i.severity === 'error')).toEqual([]); + }); + + it('⭐ LIT — a hop through an added lookup into a stored-metadata-body table is refused as through a declared one', () => { + const item = { + extend: 'fx_ticket', + fields: { + meta__c: { type: 'lookup', label: 'Meta', reference: 'sys_metadata' }, + body__c: { type: 'formula', label: 'Body', expression: 'record.meta__c.metadata' }, + }, + }; + const found = buildFindings({ objects: [target, staff], objectExtensions: [item] }); + expect(found.map((f) => f.where), dump(found)).toEqual(["object 'fx_ticket' · objectExtensions[0] · field 'body__c' expression"]); + expect(found[0]!.message).toContain('sys_metadata'); + }); + + it('⭐ CONTROL — the correct leaf through the added lookup is accepted at the door and the build, rule and formula alike', () => { + for (const item of [ruleExtension('manager__c', 'daily_hours'), formulaExtension('manager__c', 'daily_hours')]) { + const result = gateExtension(item); + expect(expressionFindings(result.errors), dump(result)).toEqual([]); + expect(buildFindings({ objects: [target, staff], objectExtensions: [item] }).filter((f) => f.severity === 'error'), dump(item)).toEqual([]); + } + }); + + it('a lookup two packages add at the same priority is left unjudged: which definition is served is registration order', () => { + const twin = { extend: 'fx_ticket', fields: { ...MANAGER } }; + const stack = { + objects: [target, staff], + packages: [ + { manifest: { objects: [target, staff] } }, + { manifest: { objectExtensions: [twin] } }, + { manifest: { objectExtensions: [ruleExtension('manager__c', 'daly_hours')] } }, + ], + }; + expect(buildFindings(stack).filter((f) => f.message.includes('daly_hours')), dump(buildFindings(stack))).toEqual([]); + }); + + it('CONTROL — the object\'s own hop through a declared lookup is unchanged, at the object save door and the build', () => { + const own = { ...target, validations: [hopRule('employee', 'daly_hours')] }; + const atDoor = expressionFindings(runRuntimeAuthoringRules({ type: 'object', item: own, context: { objects: [staff] } }).errors); + expect(atDoor.map((f) => f.where), dump(atDoor)).toEqual(["object 'fx_ticket' · validation rule 'long_day' then → 'hours'"]); + expect(validateStackExpressions({ objects: [own, staff] }).filter((i) => i.severity === 'error').map((i) => i.where)) + .toEqual(["object 'fx_ticket' · validation rule 'long_day' then → 'hours'"]); + }); +}); diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 72951696caa..613f249dcbe 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -2272,8 +2272,9 @@ export interface StackExpressionOptions { * build locates it. [#33154] The same walk judges each validation rule the * written entry adds, by the object walk's own rule pass * (`judgeValidationRule`), its `record.FIELD` reads resolved against the - * same served fields (the leaf of a hop through a reference an extension - * adds is not judged; see the walk), and located at the entry + * same served fields (#33216: and a one-hop leaf through a reference an + * extension adds judged as one through a declared reference), and located + * at the entry * (`object 'T' · objectExtensions[0] · validation 'N'`). On this write the * live objects are read without the system columns the registry injects * (`stripInjectedSystemColumns`), as the build reads them. The @@ -2398,13 +2399,26 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // the walk reaches the object's fields, whichever comes first — never before // the walk reaches the object, so a carrier the spec cannot read is refused // by the pass that owned that verdict before this one existed. + // + // [#33216] Two readings, one per question. A HOP (`served`) is planned by + // the engine over the registered schema, so a site that serves one reads the + // object as served (`typedObjects`: every `objectExtensions` field folded in, + // a field two packages tie on left out): a reference an extension adds is + // refused like a declared one. The object walk's #24677 field verdict judges + // the object's OWN fields and stays on the declared body, so a field an + // extension adds is never charged to the object's location. + // One map holds both readings; a served reading is keyed `served:NAME` (an + // object name carries no `:`). const storedMetadataBodyReferenceIndex = new Map>(); - const storedMetadataBodyReferencesFor = (objectName: string): Map => { - let familyRefs = storedMetadataBodyReferenceIndex.get(objectName); + const storedMetadataBodyReferencesFor = (objectName: string, served = false): Map => { + const key = served ? `served:${objectName}` : objectName; + let familyRefs = storedMetadataBodyReferenceIndex.get(key); if (!familyRefs) { familyRefs = new Map(); - for (const obj of objects) if (obj.name === objectName) familyRefs = storedMetadataBodyReferencesOf(obj); - storedMetadataBodyReferenceIndex.set(objectName, familyRefs); + for (const obj of served ? typedObjects : objects) { + if (obj.name === objectName) familyRefs = storedMetadataBodyReferencesOf(obj); + } + storedMetadataBodyReferenceIndex.set(key, familyRefs); } return familyRefs; }; @@ -2427,7 +2441,8 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression if (!source) return; const traversals = analyzeRelationshipTraversals(source, 'record')?.traversals; if (!traversals || traversals.size === 0) return; - const familyRefs = storedMetadataBodyReferencesFor(objectName); + // [#33216] The hop's reference as served: one an extension adds counts. + const familyRefs = storedMetadataBodyReferencesFor(objectName, true); for (const [field, columns] of traversals) { const target = familyRefs.get(field); if (!target) continue; @@ -2454,7 +2469,14 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression * * Judged against the target's field index — its declared fields and the * system columns the platform injects on it, the set the registry carries — - * and the primary key, which no field map carries and the loader reads. A + * and the primary key, which no field map carries and the loader reads. + * + * [#33216] The reference itself is read off the hopping object AS SERVED + * (`typedObjects`), as the engine plans the hop over the registered schema: + * a lookup an `objectExtensions` entry adds is judged like a declared one, + * and so is a leaf an extension adds to the target (`fieldIndex` is built + * over the served objects too). A reference two packages tie on is left + * out, since which definition the registry serves is registration order. A * target outside the stack (or the door's snapshot, which carries the live * registry's objects, another package's included) has no index here and is * not judged; a hop into the stored-metadata-body family is refused by @@ -2471,7 +2493,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression const analysis = analyzeRelationshipTraversals(source, 'record'); const traversals = analysis?.traversals; if (!traversals || traversals.size === 0) return; - for (const obj of objects) { + for (const obj of typedObjects) { if (obj.name !== objectName) continue; for (const [field, def] of fieldEntries(obj)) { // [#24468] A reference read more than one hop deep is refused whole by @@ -4129,12 +4151,11 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // over `objectsAsServed`), so a field this or a sibling extension adds // resolves and a field nothing serves is unknown; an undeclared target // is judged on what does not depend on its fields, as its fields' - // formulas are. Not every check reads the fold: the hop checks - // (`refuseUndeclaredHopField`, `storedMetadataBodyReferencesFor`) read - // the declared objects, so the leaf of a one-hop read through a - // reference an extension ADDS is not judged here (`record.manager__c. - // nmae` passes), while a hop through a reference the target declares - // is. Located at the entry (`object 'T' · objectExtensions[0] · + // formulas are. [#33216] The hop checks (`refuseUndeclaredHopField`, + // `storedMetadataBodyReferencesFor`) read the fold too, so the leaf of + // a one-hop read through a reference an extension ADDS + // (`record.manager__c.nmae`) is refused as one through a reference the + // target declares is. Located at the entry (`object 'T' · objectExtensions[0] · // validation 'N'`), the key path at the rule's slot under the entry // (`objectExtensions[0].validations[0].condition`): the door's 422 // carries that path as is, and only a draft read's `_diagnostics` diff --git a/packages/runtime/src/domains/meta-object-extension-item.test.ts b/packages/runtime/src/domains/meta-object-extension-item.test.ts index 3e30f989edb..a169379923f 100644 --- a/packages/runtime/src/domains/meta-object-extension-item.test.ts +++ b/packages/runtime/src/domains/meta-object-extension-item.test.ts @@ -548,6 +548,81 @@ describe('[#33154] the publish door judges an extension\'s validation rule as `o }, 60_000); }); +describe('[#33216] the publish door judges the one-hop leaf through a lookup the extension adds, as `os build` does', () => { + /** The lookup's target, a second object of the base. */ + const contact = { + name: 'crm_contact', + label: 'Contact', + fields: { daily_hours: { name: 'daily_hours', label: 'Daily Hours', type: 'number' } }, + }; + const MANAGER = { manager__c: { type: 'lookup', label: 'Manager', reference: 'crm_contact' } }; + /** A rule reading `record.manager__c.LEAF`, gated on the reference as the traversal check prescribes. */ + const ruleBody = (leaf: string) => ({ + extend: TARGET, + fields: { ...MANAGER }, + validations: [{ + name: 'long_day', type: 'conditional', message: 'Refused.', + when: 'record.manager__c != null', + then: { name: 'hours', type: 'script', condition: `record.manager__c.${leaf} > 12`, message: 'Refused.' }, + }], + }); + const formulaBody = (leaf: string) => ({ + extend: TARGET, + fields: { ...MANAGER, hours__c: { type: 'formula', label: 'Hours', expression: `record.manager__c.${leaf}` } }, + }); + /** `os build`'s expression findings at the extension, over the base as authored. */ + const atBuild = (item: unknown) => { + const stack = { objects: baseManifest([contact]).objects, objectExtensions: [item] }; + return runAuthoringRules('build', { normalized: stack, parsed: stack } as any) + .filter((f) => f.where.includes('objectExtensions') && f.rule === 'expression-invalid') + .map((f) => ({ rule: f.rule, where: f.where, path: f.path })); + }; + const refusedAtDoor = async (rig: Awaited>, item: unknown) => { + await rig.protocol.saveMetaItem({ type: TYPE, name: TARGET, item, mode: 'draft', packageId: PAIR }); + return rig.protocol.publishMetaItem({ type: TYPE, name: TARGET, packageId: PAIR }).catch((e: any) => e); + }; + + for (const [label, body, where, path] of [ + [ + 'a rule', + ruleBody, + "object 'crm_account' · objectExtensions[0] · validation rule 'long_day' then → 'hours'", + 'objectExtensions[0].validations[0].then.condition', + ], + [ + 'a formula', + formulaBody, + "object 'crm_account' · objectExtensions[0] · field 'hours__c' expression", + "object 'crm_account' · objectExtensions[0] · field 'hours__c' expression", + ], + ] as const) { + it(`⭐ LIT — ${label} reading a misspelt leaf through the added lookup is refused with the build's rule id, location and path`, async () => { + const expected = [{ rule: 'expression-invalid', where, path }]; + expect(atBuild(body('daly_hours'))).toEqual(expected); + + const rig = await boot([contact]); + const err: any = await refusedAtDoor(rig, body('daly_hours')); + expect(err, 'the publish was admitted').toBeInstanceOf(Error); + expect({ code: err.code, status: err.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + const issues = (err.issues ?? []).filter((i: any) => i.rule === 'expression-invalid'); + expect(issues.map((i: any) => ({ rule: i.rule, where: i.where, path: i.path })), JSON.stringify(err.issues)).toEqual(expected); + expect(issues[0].message).toContain('daly_hours'); + expect(issues[0].message).toContain('crm_contact'); + expect((await rig.fieldsOn()).registry).not.toContain('manager__c'); + expect(await rig.rows()).toEqual([{ name: TARGET, package_id: PAIR, state: 'draft' }]); + }, 60_000); + + it(`⭐ CONTROL — ${label} reading the leaf the target declares, through the added lookup, publishes`, async () => { + expect(atBuild(body('daily_hours'))).toEqual([]); + + const rig = await boot([contact]); + await rig.saveAndPublish(PAIR, body('daily_hours')); + expect((await rig.fieldsOn()).registry).toContain('manager__c'); + expect(await rig.rows()).toEqual([{ name: TARGET, package_id: PAIR, state: 'active' }]); + }, 60_000); + } +}); + describe('[ADR-0146 D10] a module\'s extension that re-declares the base\'s field beyond its display properties', () => { /** A writable module package that depends on the base: the account is inside its closure. */ const MODULE = 'com.acme.module'; diff --git a/packages/spec/src/migrations/entries/semantic/18.object-extension-added-lookup-hop-leaf-judged.ts b/packages/spec/src/migrations/entries/semantic/18.object-extension-added-lookup-hop-leaf-judged.ts new file mode 100644 index 00000000000..b78c445c878 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.object-extension-added-lookup-hop-leaf-judged.ts @@ -0,0 +1,41 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #33216: an accept-set narrowing of `os build`, `os validate` and the runtime +// `object_extension` publish door. The expression rule of `@objectstack/lint` +// (`validateStackExpressions`) judged the leaf of a one-hop read +// (`record.REF.LEAF`) only when the reference was declared on the object: it +// read the declared objects for the reference, so a lookup an +// `objectExtensions` entry adds let a misspelt leaf through. The hop is now +// judged on the object as served, the reference an extension adds included, +// at the build and the door. No D2 conversion: which field the author meant +// is a fact only the author holds, and a stored row is not re-judged until it +// is published again. +export const entry: SemanticMigration = { + id: 'object-extension-added-lookup-hop-leaf-judged', + surface: + 'a validation rule or a formula that reads one hop (`record.REF.LEAF`) through a lookup an `objectExtensions` ' + + 'entry adds (`defineObjectExtension({ extend, fields })`, or an `object_extension` item published at runtime ' + + 'through Studio, `PUT /api/v1/meta/object_extension/TARGET` or the MCP and AI authoring doors), where LEAF is ' + + 'a field the lookup\'s target does not serve, e.g. `{ extend: \'crm_account\', fields: { manager__c: { type: ' + + '\'lookup\', reference: \'crm_contact\' }, hours__c: { type: \'formula\', expression: ' + + '\'record.manager__c.daly_hours\' } } }`.', + replacement: + 'A one-hop read whose LEAF is a field the lookup\'s target serves (its own fields, the columns the platform ' + + 'injects on it, every field an extension adds to it, or `id`), as a hop through a lookup the object declares ' + + 'must already read.', + reason: + 'The engine plans a one-hop read over the registered schema, where a lookup an extension adds is a field like ' + + 'any other, but the build and the door looked the reference up on the declared object only. So a misspelt ' + + 'leaf behind an extension-added lookup was accepted: a formula read null on every row, and a validation rule ' + + 'had no verdict and refused every save of the object. The hop is now judged on the object as served and ' + + 'refused with the verdict a hop through a declared lookup gets (`expression-invalid`; at the door `422 ' + + 'INVALID_METADATA`), located where the rule or formula is written. A hop through an added lookup into a ' + + 'stored-metadata-body table is refused as through a declared one. A lookup two packages add at the same ' + + 'priority is not judged, since which definition is served is registration order.', + acceptanceCriteria: + '`os build` reports no `expression-invalid` finding naming an unknown field read through a reference an ' + + 'extension adds, and publishing each such extension again answers 200 with no such issue. The formula reads ' + + 'the target\'s value, and a record the rule should refuse is refused on save with the rule\'s message.', +}; From d190a7f0437f6d0d40f1a2357023b12ce5b04993 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:54:19 +0000 Subject: [PATCH 2/2] fix(lint): give an object extension's validation rules the regex and JSON-schema checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit validateRuleCompilability and validateRuleSchemaFormats share one rule walk, which read objects[].validations only. It now also walks each rule an objectExtensions entry adds, through the shared extension fold, located at the entry (object 'T' · objectExtensions[i] · validation 'N', path objectExtensions[i].validations.N.regex|schema), with the rule ids the object's own rules get. Both rules now run on the object_extension publish door; the gate's differential keeps the target's own stored rules off the extension write. Adds the ADR-0087 semantic entry object-extension-validation-rule-artifacts-judged, the one changeset for both fixes, and the validating-metadata docs row and paragraph this makes stale. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5ny58hH1bcw97uPpgu --- ...extension-lookup-hop-and-rule-artifacts.md | 22 ++++ .../docs/deployment/validating-metadata.mdx | 9 +- packages/lint/src/authoring-rules.ts | 14 +- ...runtime-gate.object-formula-writes.test.ts | 5 +- .../src/validate-rule-compilability.test.ts | 120 ++++++++++++++++++ .../lint/src/validate-rule-compilability.ts | 55 +++++++- .../lint/src/validate-rule-schema-formats.ts | 6 +- ...e-security-posture.runtime-surface.test.ts | 8 +- .../meta-object-extension-item.test.ts | 56 ++++++++ ...ension-validation-rule-artifacts-judged.ts | 41 ++++++ 10 files changed, 321 insertions(+), 15 deletions(-) create mode 100644 .changeset/33216-extension-lookup-hop-and-rule-artifacts.md create mode 100644 packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-artifacts-judged.ts diff --git a/.changeset/33216-extension-lookup-hop-and-rule-artifacts.md b/.changeset/33216-extension-lookup-hop-and-rule-artifacts.md new file mode 100644 index 00000000000..4963eb95322 --- /dev/null +++ b/.changeset/33216-extension-lookup-hop-and-rule-artifacts.md @@ -0,0 +1,22 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': minor +--- + +fix(lint): `os build` and the runtime `object_extension` publish door judge the one-hop leaf through a lookup an object extension adds, and the regex and JSON-schema checks of each validation rule an extension adds, as they judge an object's own + +Clause-②: no (narrowing) — `os build`, `os validate`, `os lint` and the `object_extension` publish door (Studio, `PUT /api/v1/meta/object_extension/TARGET`, the MCP and AI authoring doors) now refuse two shapes an extension could carry before: a validation rule or formula reading `record.REF.LEAF` through a lookup an extension adds where the lookup's target serves no `LEAF`, and a `format` / `json_schema` validation rule an extension adds whose regex or schema does not compile or names an unregistered format. No exported type or signature changes. Measured first-party: 0 `objectExtensions` entries add a lookup or a validation rule (`examples/app-showcase` one entry, three plain fields; `packages/plugins/plugin-auth` one, a `secret` field; HotCRM none), so nothing first-party is newly refused. +Metadata-protocol: narrowed +Skills-docs: none owed — this PR edits `content/docs/deployment/validating-metadata.mdx` (the rule-table row now marks the extension door, and the object extension paragraph names both checks); `skills/objectstack-data` teaches one-hop reads, `format` / `json_schema` rules and `defineObjectExtension({ extend, fields })` without saying an extension is exempt from either check, so the build and the door now give the verdict the object's own declarations already get. + + + +**BREAKING** accept-set narrowing of `os build`, `os validate`, `os lint` and the runtime `object_extension` publish door. + +**Before:** two checks the object's own declarations get skipped what an extension adds. The expression rule judged the leaf of a one-hop read (`record.REF.LEAF`) only when `REF` was declared on the object, so through a lookup an extension adds (`manager__c`) a misspelt leaf (`record.manager__c.daly_hours`) was accepted: a formula read null on every row, and a validation rule had no verdict and refused every save. And the regex and JSON-schema checks walked an object's own `validations` only, so an extension's `format` rule with a regex `new RegExp` throws on, or a `json_schema` rule whose schema ajv cannot compile or that names an unregistered format, was accepted and then skipped (or the format dropped) on every write: the rule protected nothing. + +**Now:** the hop is judged on the object as served, a lookup an extension adds included, with the verdict a hop through a declared lookup gets (`expression-invalid`), located where the rule or formula is written (`object 'TARGET' · objectExtensions[0] · validation rule 'R' then → 'S'`, or `· field 'F' expression`); a hop through an added lookup into a stored-metadata-body table is refused as through a declared one. Each rule an extension adds, a nested `then` / `otherwise` branch included, gets the regex and JSON-schema checks with the same rule ids (`validation-rule-regex-uncompilable`, `validation-rule-json-schema-uncompilable`, `validation-rule-json-schema-unknown-format`), located at the entry: `object 'TARGET' · objectExtensions[0] · validation 'RULE'`, key path `objectExtensions[0].validations.RULE.regex` (or `.schema`). Both run at the `object_extension` door (`422 INVALID_METADATA`) as in `os build`. + +**Unchanged:** the object save door and an object's own rules, formulas and hops, at the same locations; a draft save (never gated); a stored row (judged only when it is published again). A lookup two packages add at the same priority is not judged, since which definition the registry serves is registration order. At the extension door the target's own rules the door's live objects carry are judged in the gate's baseline too, so a broken rule of the target is not charged to the extension write. + +**Fix:** before building or publishing again, read a field the lookup's target serves through the added lookup, and give each extension rule a regex that compiles (or a named `format`) and a schema ajv compiles, naming only registered formats, as you would on a rule declared on the same object. diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 0bdf227e8de..87e5fadd7ba 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -523,7 +523,7 @@ orthogonal to both, and no cell here can carry it; it is written out in | Security posture (ADR-0090 — e.g. every custom object declares `sharingModel`) | ✓ | ✓ | ✓ | ✓ˢᵖᵉᵇᵒ | | Security vocabulary freeze (ADR-0090 D3 — the reserved word, replaced by `permission_set` / `position` / `business_unit`) | ✓ | ✓ | ✓ | ✓ᵒᵖᵉᵇᵖᵒᵃᵒˣ | | Organization-axis red lines (ADR-0105 D6) | ✓ | ✓ | ✓ | — | -| Declared enforcement that cannot run, **declared on the object being written** — a validation rule's regex / JSON Schema (#4762) and its `format` names (#5178) | ✓ | ✓ | ✓ | ✓ᵒ | +| Declared enforcement that cannot run, **declared on the object being written** — a validation rule's regex / JSON Schema (#4762) and its `format` names (#5178), and (#33217) those of a rule an object extension adds | ✓ | ✓ | ✓ | ✓ᵒᵒˣ | | Declared enforcement that cannot run, **declared on another collection** — sharing-rule conditions (#4698) | ✓ | ✓ | ✓ | — | | Row-level-security predicates (#4983) — a permission set's policies, an object's `defaultRowScope`, a membership key's `filter` and a field permission entry's `when` (#25866); at the save door also a membership key nothing owns (#25234) | ✓ | ✓ | ✓ | ✓ᵖᵉᵒ | | Membership key declarations — `userField` / `valueField` columns, one key on one object, a key the registered resolver also owns (save door only) (#25234) | ✓ | ✓ | ✓ | ✓ᵒ | @@ -613,7 +613,12 @@ the write replaces, and refuses with the build's rule id (`expression-invalid`). Each validation rule the entry adds is judged the same way (#33154), by the object's own rule pass, at the door and in `os build` alike: the registry merges an extension's `validations` onto the target, so every save of the target runs -them (`object 'TARGET' · objectExtensions[0] · validation 'RULE'`). +them (`object 'TARGET' · objectExtensions[0] · validation 'RULE'`). A one-hop +read through a lookup the entry adds (`record.manager__c.LEAF`) is judged as +one through a lookup the target declares (#33216), and a `format` rule's regex +and a `json_schema` rule's schema and format names are checked as on the +object's own rules (#33217), with the same rule ids, at the door and in +`os build` alike. **Declared enforcement that cannot run** is two rows for the mirror-image reason, and #4716 is where it split. That heading covers four rule ids, and diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 77c094aad8c..2bc723f736c 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -2732,8 +2732,16 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // The load it does take (~64 ms cold once, ~15 ms warm per publish // carrying such a rule) is the measured, adjudicated price of refusing a // validation rule that would otherwise ship compiled-by-nothing. + // + // [#33217] `object_extension` joins: the walk reads the `validations[]` + // an extension adds (the registry merges them onto the target, and every + // save runs them), so a regex or schema the build refuses on an extension + // is refused at that publish door too, same rule id, located at the entry + // (`object 'TARGET' · objectExtensions[0] · validation 'N'`). The target's + // own rules the door's live objects carry are judged in the baseline as + // well, so the differential charges the write with its entry's alone. surfaces: CLI_AND_RUNTIME, - runtimeTypes: ['object'], + runtimeTypes: ['object', 'object_extension'], run: (stack) => validateRuleCompilability(stack), }, // #5178 — the residual half of #5029, which registering `ajv-formats` does @@ -2758,8 +2766,10 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // the two judgements over one artifact stay on one side of the wall // (#7220's family discipline). Same lazy-ajv contract: the registered // format set is only enumerated once a schema actually names a format. + // [#33217] And it crosses on `object_extension` with its sibling, for the + // same reason: the shared walk reads the rules an extension adds. surfaces: CLI_AND_RUNTIME, - runtimeTypes: ['object'], + runtimeTypes: ['object', 'object_extension'], run: (stack) => validateRuleSchemaFormats(stack), }, // [#25189] The email half of #25082 (ruling `6335348115`, F1 A2): a hole an diff --git a/packages/lint/src/runtime-gate.object-formula-writes.test.ts b/packages/lint/src/runtime-gate.object-formula-writes.test.ts index dc36fdcd651..e8fdacd5640 100644 --- a/packages/lint/src/runtime-gate.object-formula-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-formula-writes.test.ts @@ -362,8 +362,9 @@ describe('#33072 — the object_extension door judges an extension field\'s form const ofRule = (rule: string, fs: readonly T[]): T[] => fs.filter((f) => f.rule === rule); it('`validateStackExpressions` is on the object_extension door, beside the vocabulary freeze', () => { + // [#33217] And the two validation-rule artifact checks (regex, JSON schema). expect(runtimeAuthoringRulesFor('object_extension').map((r) => r.name)) - .toEqual(['validateStackExpressions', 'validateSecurityRoleWord']); + .toEqual(['validateStackExpressions', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); }); it('⭐ LIT — an extension formula calling an unregistered function (`sqrt`) is REFUSED, at the entry the build names', () => { @@ -421,7 +422,7 @@ describe('#33072 — the object_extension door judges an extension field\'s form const result = gateExtension(item); expect(result.errors, dump(result)).toEqual([]); expect(result.advisories, dump(result)).toEqual([]); - expect(result.rulesRun).toEqual(['validateStackExpressions', 'validateSecurityRoleWord']); + expect(result.rulesRun).toEqual(['validateStackExpressions', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); } }); diff --git a/packages/lint/src/validate-rule-compilability.test.ts b/packages/lint/src/validate-rule-compilability.test.ts index 35eac92da25..90ac37ea3bf 100644 --- a/packages/lint/src/validate-rule-compilability.test.ts +++ b/packages/lint/src/validate-rule-compilability.test.ts @@ -31,6 +31,8 @@ import { } from './validate-rule-compilability.js'; import { AUTHORING_COMMANDS, AUTHORING_RULES, authoringRulesFor, runAuthoringRules } from './authoring-rules.js'; import { explainRule } from './rule-explanations.js'; +import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js'; +import { VALIDATION_RULE_SCHEMA_UNKNOWN_FORMAT } from './validate-rule-schema-formats.js'; // [#22161] Each finding of the two ids is one verdict sentence; the reasoning // it used to carry is the id's `os explain` entry. Every call below records @@ -1058,3 +1060,121 @@ describe('[#22161] one-line fixes — the two compile ids', () => { } }); }); + +describe('#33217 — the regex and JSON-schema checks reach the validation rules an object extension adds', () => { + /** The extended object, as the door's live universe carries it. */ + const target = { + name: 'fx_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: { + code: { type: 'text', label: 'Code' }, + config: { type: 'json', label: 'Config' }, + }, + }; + const BAD_REGEX = { name: 'code_shape', type: 'format', field: 'code', regex: '([', message: 'Refused.' }; + const BAD_SCHEMA = { name: 'config_shape', type: 'json_schema', field: 'config', schema: { type: 'not-a-type' }, message: 'Refused.' }; + const BAD_FORMAT_NAME = { + name: 'config_email', type: 'json_schema', field: 'config', message: 'Refused.', + schema: { type: 'object', properties: { e: { type: 'string', format: 'emial' } } }, + }; + const GOOD = [ + { name: 'code_ok', type: 'format', field: 'code', regex: '^[A-Z]{3}$', message: 'Refused.' }, + { name: 'config_ok', type: 'json_schema', field: 'config', message: 'Refused.', schema: { type: 'object', properties: { e: { type: 'string', format: 'email' } } } }, + ]; + const ARTIFACT_IDS = [VALIDATION_RULE_REGEX_UNCOMPILABLE, VALIDATION_RULE_SCHEMA_UNCOMPILABLE, VALIDATION_RULE_SCHEMA_UNKNOWN_FORMAT]; + const extension = (validations: unknown[]) => ({ extend: 'fx_ticket', fields: { note__c: { type: 'text', label: 'Note' } }, validations }); + const located = (fs: readonly { rule: string; where: string; path: string }[]) => + fs.filter((f) => ARTIFACT_IDS.includes(f.rule)).map((f) => ({ rule: f.rule, where: f.where, path: f.path })); + const atBuild = (stack: Record) => located(runAuthoringRules('build', { normalized: stack, parsed: stack })); + const atDoor = (item: unknown, objects: unknown[] = [target]) => { + const result = runRuntimeAuthoringRules({ type: 'object_extension', item, context: { objects } }); + return { result, errors: located(result.errors), advisories: located(result.advisories) }; + }; + const ENTRY = "object 'fx_ticket' · objectExtensions[0]"; + + it('both rules are on the object_extension door, and still on the object door', () => { + for (const type of ['object', 'object_extension']) { + expect(runtimeAuthoringRulesFor(type).map((r) => r.name)).toEqual(expect.arrayContaining(['validateRuleCompilability', 'validateRuleSchemaFormats'])); + } + }); + + it('⭐ LIT — an invalid `regex`, an uncompilable `schema` and a misspelt format name an extension adds are each REFUSED at the build, at the entry', () => { + expect(atBuild({ objects: [target], objectExtensions: [extension([BAD_REGEX, BAD_SCHEMA, BAD_FORMAT_NAME])] })).toEqual([ + { rule: VALIDATION_RULE_REGEX_UNCOMPILABLE, where: `${ENTRY} · validation 'code_shape'`, path: 'objectExtensions[0].validations.code_shape.regex' }, + { rule: VALIDATION_RULE_SCHEMA_UNCOMPILABLE, where: `${ENTRY} · validation 'config_shape'`, path: 'objectExtensions[0].validations.config_shape.schema' }, + { rule: VALIDATION_RULE_SCHEMA_UNKNOWN_FORMAT, where: `${ENTRY} · validation 'config_email'`, path: 'objectExtensions[0].validations.config_email.schema#/properties/e/format' }, + ]); + }); + + it('⭐ LIT — each is REFUSED at the object_extension publish door with the build\'s finding, byte for byte', () => { + for (const rule of [BAD_REGEX, BAD_SCHEMA, BAD_FORMAT_NAME]) { + const item = extension([rule]); + const door = atDoor(item); + const build = runAuthoringRules('build', { normalized: { objects: [target], objectExtensions: [item] }, parsed: { objects: [target], objectExtensions: [item] } }) + .filter((f) => ARTIFACT_IDS.includes(f.rule)); + expect(build, rule.name).toHaveLength(1); + expect(door.result.errors.filter((f) => ARTIFACT_IDS.includes(f.rule)), JSON.stringify(door.result)).toEqual(build); + expect(door.advisories).toEqual([]); + } + }); + + it('⭐ LIT — a `conditional` branch an extension adds is judged too, located at the branch', () => { + const item = extension([{ name: 'outer', type: 'conditional', when: 'record.code != null', message: 'Refused.', then: BAD_REGEX }]); + const expected = [{ + rule: VALIDATION_RULE_REGEX_UNCOMPILABLE, + where: `${ENTRY} · validation 'outer' → 'code_shape'`, + path: 'objectExtensions[0].validations.outer.then.code_shape.regex', + }]; + expect(atBuild({ objects: [target], objectExtensions: [item] })).toEqual(expected); + expect(atDoor(item).errors).toEqual(expected); + }); + + it('⭐ PARITY — the same rule ids the object\'s own rules get, the object\'s own location unchanged', () => { + const own = { ...target, validations: [BAD_REGEX, BAD_SCHEMA, BAD_FORMAT_NAME] }; + const ownFindings = atBuild({ objects: [own] }); + expect(ownFindings.map((f) => [f.where, f.path])).toEqual([ + ["object 'fx_ticket' · validation 'code_shape'", 'objects.fx_ticket.validations.code_shape.regex'], + ["object 'fx_ticket' · validation 'config_shape'", 'objects.fx_ticket.validations.config_shape.schema'], + ["object 'fx_ticket' · validation 'config_email'", 'objects.fx_ticket.validations.config_email.schema#/properties/e/format'], + ]); + const extFindings = atBuild({ objects: [target], objectExtensions: [extension([BAD_REGEX, BAD_SCHEMA, BAD_FORMAT_NAME])] }); + expect(extFindings.map((f) => f.rule)).toEqual(ownFindings.map((f) => f.rule)); + }); + + it('⭐ CONTROL — a valid regex and a valid schema an extension adds pass at the build and the door', () => { + const item = extension(GOOD); + expect(atBuild({ objects: [target], objectExtensions: [item] })).toEqual([]); + const door = atDoor(item); + expect(door.errors, JSON.stringify(door.result)).toEqual([]); + expect(door.result.rulesRun).toEqual(expect.arrayContaining(['validateRuleCompilability', 'validateRuleSchemaFormats'])); + }); + + it('a rule a SIBLING package\'s extension adds is located at its body; an extension of an undeclared object is judged all the same', () => { + const stack = { + objects: [target], + packages: [{ manifest: { objects: [target] } }, { manifest: { objectExtensions: [extension([BAD_REGEX])] } }], + }; + expect(atBuild(stack)).toEqual([{ + rule: VALIDATION_RULE_REGEX_UNCOMPILABLE, + where: "object 'fx_ticket' · packages[1].manifest.objectExtensions[0] · validation 'code_shape'", + path: 'packages[1].manifest.objectExtensions[0].validations.code_shape.regex', + }]); + expect(atDoor(extension([BAD_REGEX]), []).errors.map((f) => f.rule)).toEqual([VALIDATION_RULE_REGEX_UNCOMPILABLE]); + }); + + it('the target\'s own broken rule, carried by the door\'s live objects, is not the extension write\'s to answer for', () => { + const broken = { ...target, validations: [BAD_REGEX] }; + const door = atDoor(extension(GOOD), [broken]); + expect(door.errors, JSON.stringify(door.result)).toEqual([]); + }); + + it('CONTROL — the object save door still refuses the object\'s own invalid regex, at the object', () => { + const result = runRuntimeAuthoringRules({ type: 'object', item: { ...target, validations: [BAD_REGEX] }, context: { objects: [] } }); + expect(located(result.errors)).toEqual([{ + rule: VALIDATION_RULE_REGEX_UNCOMPILABLE, + where: "object 'fx_ticket' · validation 'code_shape'", + path: 'objects.fx_ticket.validations.code_shape.regex', + }]); + }); +}); diff --git a/packages/lint/src/validate-rule-compilability.ts b/packages/lint/src/validate-rule-compilability.ts index eddb8285afd..575a616118d 100644 --- a/packages/lint/src/validate-rule-compilability.ts +++ b/packages/lint/src/validate-rule-compilability.ts @@ -98,6 +98,19 @@ * recurses into those and reaches the very same `checkFormat` / * `checkJsonSchema`. Nothing else in the stack is judged here. * + * [#33217] "Object validation rules" includes the `validations[]` an + * `objectExtensions` entry adds: the registry merges them onto the target by + * name, so every save of the target runs them through the same + * `checkFormat` / `checkJsonSchema`. They are read through the shared + * extension fold (`objectExtensionsByTarget`, the one the expression pass's + * extension walk reads), so the entries judged are the ones the registry + * keeps, and located at the entry (`object 'T' · objectExtensions[i] · + * validation 'N'`, path `objectExtensions[i].validations.N`), with the rule + * ids the object's own rules get. On the `object_extension` publish door the + * written entry is the snapshot's sole extension; the target's own rules the + * door's live objects carry are judged in the gate's baseline too, so they + * cancel and only the written entry's verdicts reach the write. + * * ### The keys read, and the one deliberately NOT read (#5096) * * This rule is registered `input: 'parsed'` (`authoring-rules.ts`), so on the @@ -109,6 +122,7 @@ * | Read | Declared by | * |---------------------------------------------|--------------------------------------| * | `objects[].validations[]` | `ObjectSchema` | + * | `objectExtensions[].validations[]` (#33217) | `ObjectExtensionSchema`, through `objectExtensionsByTarget` | * | `validations[].type` / `.name` | every `*ValidationSchema` variant | * | `validations[].regex` | `FormatValidationSchema` | * | `validations[].schema` | `JSONValidationSchema` | @@ -144,7 +158,7 @@ import { createRequire } from 'node:module'; // a sharper reason: it `require`s `ajv/dist/compile/codegen`, so importing it // eagerly would drag ajv onto the boot path through the back door. import type { Options as AjvOptions } from 'ajv'; -import { recordsOf } from './object-graph.js'; +import { objectExtensionsByTarget, recordsOf } from './object-graph.js'; export type RuleCompilabilitySeverity = 'error'; @@ -396,19 +410,28 @@ function flattenRules( export interface WalkedValidationRule { /** The rule record itself — a top-level entry, or a `conditional` branch. */ rule: AnyRec; - /** The declaring object's `name`, or `(unnamed object)`. */ + /** The declaring object's `name` (an extension's target), or `(unnamed object)`. */ objectName: string; /** The nesting-aware rule name as prose: `'outer' → 'inner'`. */ label: string; - /** Human-readable location: `object 'account' · validation 'outer' → 'inner'`. */ + /** + * Human-readable location: `object 'account' · validation 'outer' → 'inner'`; + * for a rule an extension adds, `object 'account' · objectExtensions[0] · + * validation 'outer'` (#33217). + */ where: string; - /** Config path of the rule: `objects.account.validations.outer.then.inner`. */ + /** + * Config path of the rule: `objects.account.validations.outer.then.inner`; + * for a rule an extension adds, the entry's path in place of the object's + * (`objectExtensions[0].validations.outer`, #33217). + */ basePath: string; } /** * Every object validation rule an author declared, `conditional` branches - * flattened in, each carrying the location strings a finding needs. + * flattened in, each carrying the location strings a finding needs: the + * objects' own, then (#33217) those each `objectExtensions` entry adds. * * Exported because #5178's format-NAME gate judges exactly this set. A second * walker there would be a second opinion about which rules EXIST — the same @@ -441,6 +464,28 @@ export function walkObjectValidationRules(stack: unknown): WalkedValidationRule[ } } + // [#33217] Each rule an `objectExtensions` entry adds, through the shared + // fold (one entry per package per target, as the registry keeps them), + // whether or not the stack declares the target: a regex or a schema needs + // no field of the target to judge. Destructured, so the #5096 receiver scan + // sees no new receiver: the fold hands back `ObjectExtensionSchema`'s + // `validations` as records, read through `recordsOf` there. + for (const [target, entries] of objectExtensionsByTarget(stack)) { + for (const { path: entryPath, validations: rules } of entries) { + for (const authored of rules) { + for (const { rule, label, path } of flattenRules(authored, '', '')) { + walked.push({ + rule, + objectName: target, + label, + where: `object '${target}' · ${entryPath} · validation ${label}`, + basePath: `${entryPath}.validations.${path}`, + }); + } + } + } + } + return walked; } diff --git a/packages/lint/src/validate-rule-schema-formats.ts b/packages/lint/src/validate-rule-schema-formats.ts index d7d4741f3c2..28c5b5e30c4 100644 --- a/packages/lint/src/validate-rule-schema-formats.ts +++ b/packages/lint/src/validate-rule-schema-formats.ts @@ -80,11 +80,15 @@ * re-implemented so the two rules can never disagree about which rules exist. * That covers `object.validations[]` including the rules nested in a * `conditional`'s `then` / `otherwise`, since `evaluateRule` recurses into those - * and reaches the very same `checkJsonSchema`. + * and reaches the very same `checkJsonSchema`. [#33217] Through that walk, the + * `validations[]` an `objectExtensions` entry adds are judged too, located at + * the entry (`object 'T' · objectExtensions[i] · validation 'N'`), since the + * registry merges them onto the target and every save runs them. * * | Read | Declared by | * |----------------------------------|------------------------| * | `objects[].validations[]` | `ObjectSchema` | + * | `objectExtensions[].validations[]` | `ObjectExtensionSchema` (#33217, via the walk) | * | `validations[].type` / `.name` | every `*ValidationSchema` variant | * | `validations[].schema` | `JSONValidationSchema` | * | `validations[].then`/`.otherwise`| `ConditionalValidationSchema` | diff --git a/packages/lint/src/validate-security-posture.runtime-surface.test.ts b/packages/lint/src/validate-security-posture.runtime-surface.test.ts index 48d0dfbe6cd..b65a553f4ce 100644 --- a/packages/lint/src/validate-security-posture.runtime-surface.test.ts +++ b/packages/lint/src/validate-security-posture.runtime-surface.test.ts @@ -566,7 +566,9 @@ describe('validateSecurityPosture at the runtime publish surface (#7576 → #830 const entry = DEFAULT_METADATA_TYPE_REGISTRY.find((e) => e.type === 'object_extension'); expect(entry?.allowRuntimeCreate, "'object_extension' is runtime-creatable").toBe(true); expect(stackKeyForType('object_extension')).toBe('objectExtensions'); - expect(runtimeAuthoringRulesFor('object_extension').map((r) => r.name)).toEqual(['validateStackExpressions', 'validateSecurityRoleWord']); + // [#33217] The validation-rule artifact checks (regex, JSON schema) cross on it too. + expect(runtimeAuthoringRulesFor('object_extension').map((r) => r.name)) + .toEqual(['validateStackExpressions', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); const roleSelect = { type: 'select', label: 'Group Function', options: [{ value: 'l1', label: 'Tier 1' }] }; const refused = runRuntimeAuthoringRules({ @@ -581,7 +583,7 @@ describe('validateSecurityPosture at the runtime publish surface (#7576 → #830 // positional and names it. expect(refused.errors[0].path).toBe('objectExtensions[0].fields.role.name'); expect(refused.errors[0].where).toBe('field "sd_agent.role"'); - expect(refused.rulesRun).toEqual(['validateStackExpressions', 'validateSecurityRoleWord']); + expect(refused.rulesRun).toEqual(['validateStackExpressions', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); // The two labels the entry serves, at the same door. const labelled = runRuntimeAuthoringRules({ @@ -601,7 +603,7 @@ describe('validateSecurityPosture at the runtime publish surface (#7576 → #830 }); expect(clean.errors).toEqual([]); expect(clean.advisories).toEqual([]); - expect(clean.rulesRun).toEqual(['validateStackExpressions', 'validateSecurityRoleWord']); + expect(clean.rulesRun).toEqual(['validateStackExpressions', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); // Not a context row: the baseline carries no `objectExtensions`, and the // candidate holds exactly the written item. diff --git a/packages/runtime/src/domains/meta-object-extension-item.test.ts b/packages/runtime/src/domains/meta-object-extension-item.test.ts index a169379923f..9783f1bba98 100644 --- a/packages/runtime/src/domains/meta-object-extension-item.test.ts +++ b/packages/runtime/src/domains/meta-object-extension-item.test.ts @@ -623,6 +623,62 @@ describe('[#33216] the publish door judges the one-hop leaf through a lookup the } }); +describe('[#33217] the publish door judges an extension\'s `format` regex and `json_schema` schema as `os build` does', () => { + const ruleBody = (rule: Record) => ({ + extend: TARGET, + fields: { code__c: { type: 'text', label: 'Code' }, config__c: { type: 'json', label: 'Config' } }, + validations: [rule], + }); + const BAD_REGEX = { name: 'code_shape', type: 'format', field: 'code__c', regex: '([', message: 'Refused.' }; + const BAD_SCHEMA = { name: 'config_shape', type: 'json_schema', field: 'config__c', schema: { type: 'not-a-type' }, message: 'Refused.' }; + const ARTIFACT_IDS = ['validation-rule-regex-uncompilable', 'validation-rule-json-schema-uncompilable']; + const atBuild = (item: unknown) => { + const stack = { objects: baseManifest().objects, objectExtensions: [item] }; + return runAuthoringRules('build', { normalized: stack, parsed: stack } as any) + .filter((f) => ARTIFACT_IDS.includes(f.rule)) + .map((f) => ({ rule: f.rule, where: f.where, path: f.path })); + }; + const servedRules = (rig: Awaited>) => + ((rig.engine.registry.getObject(TARGET) as any)?.validations ?? []).map((r: any) => r?.name); + + for (const [label, rule, rid, slot] of [ + ['an invalid `regex`', BAD_REGEX, 'validation-rule-regex-uncompilable', 'regex'], + ['an uncompilable `schema`', BAD_SCHEMA, 'validation-rule-json-schema-uncompilable', 'schema'], + ] as const) { + it(`⭐ LIT — ${label} is refused with the build's rule id and a locator at the extension's rule; the rule is not served`, async () => { + const expected = [{ + rule: rid, + where: `object 'crm_account' · objectExtensions[0] · validation '${rule.name}'`, + path: `objectExtensions[0].validations.${rule.name}.${slot}`, + }]; + expect(atBuild(ruleBody(rule))).toEqual(expected); + + const rig = await boot(); + await rig.protocol.saveMetaItem({ type: TYPE, name: TARGET, item: ruleBody(rule), mode: 'draft', packageId: PAIR }); + const err: any = await rig.protocol.publishMetaItem({ type: TYPE, name: TARGET, packageId: PAIR }).catch((e: any) => e); + expect(err, 'the publish was admitted').toBeInstanceOf(Error); + expect({ code: err.code, status: err.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + expect((err.issues ?? []).filter((i: any) => ARTIFACT_IDS.includes(i.rule)) + .map((i: any) => ({ rule: i.rule, where: i.where, path: i.path })), JSON.stringify(err.issues)).toEqual(expected); + expect(servedRules(rig)).not.toContain(rule.name); + expect(await rig.rows()).toEqual([{ name: TARGET, package_id: PAIR, state: 'draft' }]); + }, 60_000); + } + + it('⭐ CONTROL — a valid regex and a valid schema publish and are served on the account', async () => { + const body = { + ...ruleBody({ name: 'code_ok', type: 'format', field: 'code__c', regex: '^[A-Z]{3}$', message: 'Refused.' }), + }; + body.validations.push({ name: 'config_ok', type: 'json_schema', field: 'config__c', schema: { type: 'object' }, message: 'Refused.' } as any); + expect(atBuild(body)).toEqual([]); + + const rig = await boot(); + await rig.saveAndPublish(PAIR, body); + expect(servedRules(rig)).toEqual(expect.arrayContaining(['code_ok', 'config_ok'])); + expect(await rig.rows()).toEqual([{ name: TARGET, package_id: PAIR, state: 'active' }]); + }, 60_000); +}); + describe('[ADR-0146 D10] a module\'s extension that re-declares the base\'s field beyond its display properties', () => { /** A writable module package that depends on the base: the account is inside its closure. */ const MODULE = 'com.acme.module'; diff --git a/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-artifacts-judged.ts b/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-artifacts-judged.ts new file mode 100644 index 00000000000..a82a65f3ef5 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-artifacts-judged.ts @@ -0,0 +1,41 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #33217: an accept-set narrowing of `os build`, `os validate` and the runtime +// `object_extension` publish door. The two `@objectstack/lint` rules that judge +// a validation rule's static artifact (`validateRuleCompilability`: a `format` +// rule's `regex`, a `json_schema` rule's `schema`; `validateRuleSchemaFormats`: +// a format NAME inside that schema) walked only the rules an object declares, +// and ran on the object door only. They now walk each rule an +// `objectExtensions` entry adds too, and run on the `object_extension` door. No +// D2 conversion: the pattern or schema the author meant is a fact only the +// author holds, and a stored row is not re-judged until it is published again. +export const entry: SemanticMigration = { + id: 'object-extension-validation-rule-artifacts-judged', + surface: + 'a `format` validation rule whose `regex` does not compile, or a `json_schema` validation rule whose `schema` ' + + 'ajv cannot compile or that names an unregistered `format`, added by an `objectExtensions` entry ' + + '(`defineObjectExtension({ extend, validations })`, or an `object_extension` item published at runtime ' + + 'through Studio, `PUT /api/v1/meta/object_extension/TARGET` or the MCP and AI authoring doors), a nested ' + + '`then` / `otherwise` branch included, e.g. `{ extend: \'crm_account\', validations: [{ name: \'code_shape\', ' + + 'type: \'format\', field: \'code__c\', regex: \'([\', message: \'Bad code.\' }] }`.', + replacement: + 'A rule the two checks accept on a declared rule of the same object: a `regex` that `new RegExp(...)` ' + + 'compiles (or a named `format` instead), and a `schema` that ajv compiles in the runtime\'s environment, ' + + 'naming only registered formats.', + reason: + 'The registry merges an extension\'s rules onto the target, so every save of the target runs them, but a ' + + 'regex or schema the runtime cannot compile is logged and skipped on every write, and a misspelt format ' + + 'name is dropped: the rule protects nothing. The build and the door judged that on an object\'s own rules ' + + 'only. Each rule an extension adds is now judged by the same two checks, with the same rule ids ' + + '(`validation-rule-regex-uncompilable`, `validation-rule-json-schema-uncompilable`, ' + + '`validation-rule-json-schema-unknown-format`; at the door `422 INVALID_METADATA`), located at the entry: ' + + '`object \'TARGET\' · objectExtensions[N] · validation \'RULE\'`, key path ' + + '`objectExtensions[N].validations.RULE.regex` (or `.schema`), prefixed `packages[J].manifest.` in a built ' + + 'artifact, and `objectExtensions[0]` at the door, which judges the one entry it writes.', + acceptanceCriteria: + '`os build` reports none of the three rule ids located at an `objectExtensions[N] · validation` site, and ' + + 'publishing each extension that adds such a rule again answers 200 with no such issue. A value the rule ' + + 'should refuse is refused on save with the rule\'s message.', +};