From 6bf223ae89d2b9038d13fc3a2f90e6c4affdc6f1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:40:15 +0000 Subject: [PATCH 1/8] fix(lint)!: the extension walk judges each validation rule an object extension adds, by the object walk's own rule pass WIP: pins, changeset and migration entry follow. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyToDkPxCjvNiWsv6e --- packages/lint/src/authoring-rules.ts | 7 + packages/lint/src/validate-expressions.ts | 220 ++++++++++++++-------- 2 files changed, 145 insertions(+), 82 deletions(-) diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 0665a31547e..77c094aad8c 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -838,6 +838,13 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // extension draft is refused, because that batch's pending set carries no // extension drafts (#33152); publishing the extension first through the // per-item door works. + // + // [#33154] The same walk judges each `validations[]` rule the written + // extension adds, by the object walk's own rule pass, so a rule the + // registry merges onto the target is refused at this door and in the + // build alike (`object 'TARGET' · objectExtensions[0] · validation 'N'`). + // MEASURED first: 0 first-party `objectExtensions` entries carry a + // validation rule (examples/**, packages/**, HotCRM). surfaces: CLI_AND_RUNTIME, runtimeTypes: ['flow', 'action', 'hook', 'object', 'view', 'page', 'object_extension'], run: (stack, ctx) => diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index c22f05c13f1..cac51bd176c 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -2268,9 +2268,13 @@ export interface StackExpressionOptions { * extension walk, `judgeFieldFormula`), against the extended object as * served — the door's live objects with the entry folded in by * `objectsAsServed`, the build's own fold — and located at the entry, as the - * build locates it. The object walk reads an empty list (the carried - * objects are the universe the field resolves in, not the subject) and so - * does every other pass; the function returns after the extension walk. + * build locates it. [#33154] The same walk judges each validation rule the + * written entry adds, by the object walk's own rule pass + * (`judgeValidationRule`), against the same served target and located at + * the entry (`object 'T' · objectExtensions[0] · validation 'N'`). The + * object walk reads an empty list (the carried objects are the universe the + * field or rule resolves in, not the subject) and so does every other pass; + * the function returns after the extension walk. * A package-wide draft publish (`publishPackageDrafts`) whose drafts depend * on a sibling extension draft is refused, because that batch's pending set * carries no extension drafts (#33152); publishing the extension first @@ -2335,8 +2339,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // the shape of the snapshot the gate happens to build today. const objectWrite = options.runtimeWriteType === 'object'; // [#33072] On an `object_extension` write exactly ONE pass judges: the - // extension-field walk below (#32875), over the written entry, against the - // extended object as served. Every other loop reads an empty list under it + // extension walk below (#32875: each added field's formula; #33154: each + // added validation rule), over the written entry, against the extended + // object as served. Every other loop reads an empty list under it // (the object walk and the flows included), and the function returns right // after that walk, so the claim holds by construction. See // {@link StackExpressionOptions.runtimeWriteType}. @@ -3543,6 +3548,101 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression } }; + /** + * [#22032, pass 1] One `validations[]` rule's verdict, the pass the object + * save door and the build both run: its `condition` and `when`, every + * predicate nested in a `conditional` rule's `then` / `otherwise`, the + * `parent` root verdict and the #4763 null-guard gate. + * + * [#33154] Hoisted out of the object walk so the extension walk judges a + * rule an `objectExtensions` entry adds by this same body: the registry + * merges an extension's `validations` onto its target by name, so every + * save of the target runs them as it runs the object's own. The site names + * where the rule is judged — `objectName` is the object the rule runs on + * (an extension's target), `locus` the human locator every finding opens + * with (`object 'T'`, or `object 'T' · objectExtensions[i]` for an + * extension's rule), and `rulePath` the rule's key path, absent when the + * authored list has no index to spell. + */ + const judgeValidationRule = ( + rule: AnyRec, + site: { objectName: string | undefined; locus: string; rulePath: string | undefined }, + ): void => { + const { objectName, locus, rulePath } = site; + const where = `${locus} · validation '${(rule.name as string) ?? '?'}'`; + // [#29926] One outcome for every predicate the rule carries: a nested + // branch is governed by the top-level rule's severity at runtime. + const ruleOutcome = faultOutcomeOf({ kind: 'validation rule', severity: rule.severity }); + // [#27643] Every finding below also carries the judged slot's key path + // (`objects[0].validations[1].condition`), indexed over the lists the + // author wrote, in the spelling a flow edge's findings use (#26858), so + // a draft's `_diagnostics` reports it item-relative + // (`validations.1.condition`). `where` stays the human locator. + const atSlot = (key: string, first: number): void => { + if (!rulePath) return; + const path = `${rulePath}.${key}`; + for (let k = first; k < issues.length; k++) issues[k] = { ...issues[k]!, path }; + }; + // The declared predicate key is `condition` (see `rulePredicates`). + // Validation predicates are `record`-scoped — no field flattening — so + // bare refs are flagged (#1928). + // [#18682] The sites where a relationship traversal is SERVED: these are + // the `script` / `cross_field` conditions ObjectQL's `checkPredicate` + // hydrates, and (#24512) a `conditional` rule's `when`, which + // `checkConditional` evaluates on the same hydrated scope. + // `traversalHydration` is passed on those two slots here and nested below + // (#22042), and on a formula field's `expression` (`judgeFieldFormula`, + // #24197), and NOWHERE else. + let first = issues.length; + check(where, rule.condition, objectName, 'record', undefined, true, undefined, undefined, ruleOutcome); + atSlot('condition', first); + first = issues.length; + check(`${where} when`, (rule as AnyRec).when, objectName, 'record', undefined, true, undefined, undefined, ruleOutcome); + atSlot('when', first); + const predicates = rulePredicates(rule, ''); + // [#22042] The same verdict one level down, and every level below it: a + // `conditional` rule's `then` / `otherwise` is a rule the evaluator runs + // (`checkConditional` hands the branch to `evaluateRule`), so its + // predicates meet `check()` exactly as the two calls above do — located + // at the label `rulePredicates` builds, the location the null-guard gate + // below already gives the same predicate. Depth 0 is skipped: the rule's + // own `condition` / `when` met `check()` above, under their own location. + // Hydration follows the evaluator, as at the top level: ObjectQL's + // `collectPredicateRelationships` reaches a nested `condition` and a + // nested `when` alike, and both are evaluated hydrated, so both slots + // meet the traversal checks. + for (const p of predicates) { + if (p.depth === 0) continue; + first = issues.length; + check(`${locus} · ${p.label}`, p.raw, objectName, 'record', undefined, true, undefined, undefined, ruleOutcome); + atSlot(p.key, first); + } + // [#24720] The rule's root verdict, over every predicate it carries, + // located where `check()` above located the same predicate. `parent` is + // a `SCOPE_ROOTS` member, so `check()` never reports a bare reference to + // it and the two verdicts stay disjoint; see + // {@link validationRuleParentIssue}. + for (const p of predicates) { + const source = celSourceOf(p.raw); + const message = source ? validationRuleParentIssue(objectName, p.ruleName, p.slot, source) : null; + if (!message) continue; + const at = p.depth > 0 + ? `${locus} · ${p.label}` + : p.slot === 'when' ? `${where} when` : where; + // `error`: a rule the runtime cannot evaluate must not pass a door; see the docblock. + first = issues.length; + issues.push({ where: at, message, source: source!, severity: 'error' }); + atSlot(p.key, first); + } + // #4763 — null-guard gate over every predicate the rule carries, nested + // `then`/`otherwise` branches included. + for (const p of predicates) { + first = issues.length; + checkNullGuards(`${locus} · ${p.label}`, p.label, p.raw, objectName, ruleOutcome); + atSlot(p.key, first); + } + }; + // ── Object validation-rule + formula predicates ──────────────────── // [#32529] The object's position in `objects`, which is its position in // `typedObjects` too (the served body the stored-expression member reads). @@ -3564,80 +3664,14 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // validation-rule pass the object save door runs, at the build's own // position, so the door's findings and their order are the build's. for (const rule of recordsOf(validations)) { - const where = `object '${objectName}' · validation '${(rule.name as string) ?? '?'}'`; - // [#29926] One outcome for every predicate the rule carries: a nested - // branch is governed by the top-level rule's severity at runtime. - const ruleOutcome = faultOutcomeOf({ kind: 'validation rule', severity: rule.severity }); - // [#27643] Every finding below also carries the judged slot's key path - // (`objects[0].validations[1].condition`), indexed over the lists the - // author wrote, in the spelling a flow edge's findings use (#26858), so - // a draft's `_diagnostics` reports it item-relative - // (`validations.1.condition`). `where` stays the human locator. + // [#27643] The object's index in the authored list, for the finding's + // key path; see {@link judgeValidationRule}. const ruleIndex = objectIndex >= 0 && Array.isArray(obj.validations) ? obj.validations.indexOf(rule) : -1; - const rulePath = ruleIndex >= 0 ? `objects[${objectIndex}].validations[${ruleIndex}]` : undefined; - const atSlot = (key: string, first: number): void => { - if (!rulePath) return; - const path = `${rulePath}.${key}`; - for (let k = first; k < issues.length; k++) issues[k] = { ...issues[k]!, path }; - }; - // The declared predicate key is `condition` (see `rulePredicates`). - // Validation predicates are `record`-scoped — no field flattening — so - // bare refs are flagged (#1928). - // [#18682] The sites where a relationship traversal is SERVED: these are - // the `script` / `cross_field` conditions ObjectQL's `checkPredicate` - // hydrates, and (#24512) a `conditional` rule's `when`, which - // `checkConditional` evaluates on the same hydrated scope. - // `traversalHydration` is passed on those two slots here and nested below - // (#22042), and on a formula field's `expression` (`judgeFieldFormula`, - // #24197), and NOWHERE else. - let first = issues.length; - check(where, rule.condition, objectName, 'record', undefined, true, undefined, undefined, ruleOutcome); - atSlot('condition', first); - first = issues.length; - check(`${where} when`, (rule as AnyRec).when, objectName, 'record', undefined, true, undefined, undefined, ruleOutcome); - atSlot('when', first); - const predicates = rulePredicates(rule, ''); - // [#22042] The same verdict one level down, and every level below it: a - // `conditional` rule's `then` / `otherwise` is a rule the evaluator runs - // (`checkConditional` hands the branch to `evaluateRule`), so its - // predicates meet `check()` exactly as the two calls above do — located - // at the label `rulePredicates` builds, the location the null-guard gate - // below already gives the same predicate. Depth 0 is skipped: the rule's - // own `condition` / `when` met `check()` above, under their own location. - // Hydration follows the evaluator, as at the top level: ObjectQL's - // `collectPredicateRelationships` reaches a nested `condition` and a - // nested `when` alike, and both are evaluated hydrated, so both slots - // meet the traversal checks. - for (const p of predicates) { - if (p.depth === 0) continue; - first = issues.length; - check(`object '${objectName}' · ${p.label}`, p.raw, objectName, 'record', undefined, true, undefined, undefined, ruleOutcome); - atSlot(p.key, first); - } - // [#24720] The rule's root verdict, over every predicate it carries, - // located where `check()` above located the same predicate. `parent` is - // a `SCOPE_ROOTS` member, so `check()` never reports a bare reference to - // it and the two verdicts stay disjoint; see - // {@link validationRuleParentIssue}. - for (const p of predicates) { - const source = celSourceOf(p.raw); - const message = source ? validationRuleParentIssue(objectName, p.ruleName, p.slot, source) : null; - if (!message) continue; - const at = p.depth > 0 - ? `object '${objectName}' · ${p.label}` - : p.slot === 'when' ? `${where} when` : where; - // `error`: a rule the runtime cannot evaluate must not pass a door; see the docblock. - first = issues.length; - issues.push({ where: at, message, source: source!, severity: 'error' }); - atSlot(p.key, first); - } - // #4763 — null-guard gate over every predicate the rule carries, nested - // `then`/`otherwise` branches included. - for (const p of predicates) { - first = issues.length; - checkNullGuards(`object '${objectName}' · ${p.label}`, p.label, p.raw, objectName, ruleOutcome); - atSlot(p.key, first); - } + judgeValidationRule(rule, { + objectName, + locus: `object '${objectName}'`, + rulePath: ruleIndex >= 0 ? `objects[${objectIndex}].validations[${ruleIndex}]` : undefined, + }); } // Field-level formulas (computed fields) reference the same object. const fields = obj.fields; @@ -4005,7 +4039,8 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression } } - // ── [#32875] Computed fields an `objectExtensions` entry adds ────── + // ── [#32875] Computed fields (and, #33154, validation rules) an + // `objectExtensions` entry adds ────────────────────────────────────── // The engine plans and stores a field an extension adds exactly as a // declared one (the registry folds it into the target's field map), so the // field-formula pass judges its `expression` too: each field of each entry @@ -4029,8 +4064,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // [#33072] The `object_extension` publish door runs this walk and nothing // else: its snapshot carries the written entry as the sole member of // `objectExtensions` and the door's live objects as `objects`, so the field - // is judged against its target as served and located where the build - // locates it (`objectExtensions[0]` for a one-entry stack). + // (and, #33154, the rule) is judged against its target as served and + // located where the build locates it (`objectExtensions[0]` for a one-entry + // stack). for (const [target, entries] of objectWrite ? [] : objectExtensionsByTarget(stack)) { // The target's position in `objects`, which is its position in // `typedObjects` too (see `objectPosition` above); -1 when undeclared. @@ -4059,7 +4095,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression const extensionOptionFields = [...fieldDefs] .filter(([, def]) => declaresOptionsOnceServed(def)) .map(([n]) => n); - for (const { path: entryPath, fields: added } of entries) { + for (const { path: entryPath, fields: added, validations: rules } of entries) { for (const f of added) { const fname = typeof f.name === 'string' ? f.name : '?'; judgeFieldFormula(fname, f, { @@ -4069,6 +4105,26 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression where: `object '${target}' · ${entryPath} · field '${fname}' expression`, }); } + // [#33154] Each validation rule the entry adds, by the object walk's + // own rule pass ({@link judgeValidationRule}): the registry merges an + // extension's `validations` onto the target by name, so every save of + // the target runs it as it runs the target's own rules. Judged against + // the target as served, through the same indexes, so a read of 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. Located at the entry + // (`object 'T' · objectExtensions[0] · validation 'N'`), the key path at + // the rule's slot under the entry, which the door re-spells + // item-relative (`validations.0.condition`). The index is the authored + // one: `ObjectExtensionSchema` declares `validations` an array of rule + // records, and `recordsOf` hands an array's records back in order. + for (const [ruleIndex, rule] of rules.entries()) { + judgeValidationRule(rule, { + objectName: target, + locus: `object '${target}' · ${entryPath}`, + rulePath: `${entryPath}.validations[${ruleIndex}]`, + }); + } } } From 790206fd483f4d4fa8dd543a111efdb6523a84d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:42:01 +0000 Subject: [PATCH 2/8] test(lint, runtime): pin an extension's validation rule at the build, the object_extension gate and the real publish door Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyToDkPxCjvNiWsv6e --- ...runtime-gate.object-formula-writes.test.ts | 128 ++++++++++++++++++ .../meta-object-extension-item.test.ts | 54 ++++++++ 2 files changed, 182 insertions(+) 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 540f9e85090..d42d5fba6a3 100644 --- a/packages/lint/src/runtime-gate.object-formula-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-formula-writes.test.ts @@ -452,3 +452,131 @@ describe('#33072 — the object_extension door judges an extension field\'s form expect(runtimeAuthoringRulesFor('object').map((r) => r.name)).toContain('validateStackExpressions'); }); }); + +describe('#33154 — an extension\'s validation rules are judged at the build and the object_extension door by the object\'s own rule pass', () => { + /** The extended object, as the door's live universe carries it. */ + 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' } }, + }; + const script = (name: string, condition: string) => ({ name, type: 'script', condition, message: 'Refused.' }); + /** One extension of `fx_ticket` adding the given rules (and fields). */ + const extension = (validations: unknown[], fields: Record = {}) => ({ extend: 'fx_ticket', fields, validations }); + const RULE_WHERE = (rule: string) => `object 'fx_ticket' · objectExtensions[0] · validation '${rule}'`; + 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')); + + it('⭐ LIT — a rule reading a field the extended object does not serve is REFUSED, at the entry, with the slot\'s key path', () => { + const result = gateExtension(extension([script('amount_positive', 'record.amont < 0')])); + + const errs = expressionFindings(result.errors); + expect(errs, dump(result)).toHaveLength(1); + expect(errs[0]).toMatchObject({ + severity: 'error', + where: RULE_WHERE('amount_positive'), + path: 'objectExtensions[0].validations[0].condition', + }); + expect(errs[0]!.message).toContain('amont'); + }); + + it('⭐ LIT — a rule calling an unregistered function (`sqrt`) is REFUSED, and a nested `then` branch is judged too', () => { + const result = gateExtension(extension([ + script('first_ok', 'record.amount != null && record.amount < 0'), + { + name: 'big_ticket', type: 'conditional', message: 'Refused.', + when: 'record.amount != null && record.amount > 100', + then: script('root_check', 'record.amount != null && sqrt(record.amount) > 10'), + }, + ])); + + const errs = expressionFindings(result.errors); + expect(errs.map((f) => [f.where, f.path]), dump(result)).toEqual([ + [`object 'fx_ticket' · objectExtensions[0] · validation rule 'big_ticket' then → 'root_check'`, 'objectExtensions[0].validations[1].then.condition'], + ]); + }); + + it('⭐ PARITY — on one shared input set, the door\'s findings deep-equal the build\'s', () => { + for (const item of [ + extension([script('typo', 'record.amont < 0')]), + extension([script('fn', 'sqrt(record.amount) > 1')]), + extension([script('bare', 'amount < 0')]), + ]) { + const atDoor = gateExtension(item); + const atBuild = buildFindings({ objects: [target, staff], objectExtensions: [item] }); + + expect(atBuild.length, dump(atBuild)).toBeGreaterThan(0); + expect([...atDoor.errors, ...atDoor.advisories]).toEqual(atBuild); + } + }); + + it('⭐ CONTROL — a valid rule, a rule reading a field the same extension adds, and a one-hop read publish clean', () => { + for (const item of [ + extension([script('ok', 'record.amount != null && record.amount < 0')]), + extension([script('bonus_ok', 'record.bonus != null && record.amount != null && record.bonus > record.amount')], { bonus: { type: 'number', label: 'Bonus' } }), + // The one-hop read the rule pass serves, in the shape its traversal + // check prescribes: gated on the reference being set. + extension([{ + name: 'hop_ok', type: 'conditional', message: 'Refused.', + when: 'record.employee != null', + then: script('long_day', 'record.employee.daily_hours > 12'), + }]), + ]) { + const result = gateExtension(item); + expect(result.errors, dump(result)).toEqual([]); + expect(result.advisories, dump(result)).toEqual([]); + expect(buildFindings({ objects: [target, staff], objectExtensions: [item] }), dump(item)).toEqual([]); + } + }); + + it('a rule reading a field a SIBLING package\'s extension adds resolves at the build; a misspelling of it is refused', () => { + const sibling = { extend: 'fx_ticket', fields: { bonus: { type: 'number', label: 'Bonus' } } }; + // An artifact: its top level repeats its bodies' objects, and the fold + // reads each body's extensions. + const stackWith = (item: unknown) => ({ + objects: [target, staff], + packages: [ + { manifest: { objects: [target, staff] } }, + { manifest: { objectExtensions: [sibling] } }, + { manifest: { objectExtensions: [item] } }, + ], + }); + + expect(buildFindings(stackWith(extension([script('sib', 'record.bonus != null && record.bonus > 0')])))).toEqual([]); + const typo = buildFindings(stackWith(extension([script('sib', 'record.bonsu != null && record.bonsu > 0')]))); + expect(typo.map((f) => [f.rule, f.where]), dump(typo)).toEqual([ + [EXPRESSION_INVALID, "object 'fx_ticket' · packages[2].manifest.objectExtensions[0] · validation 'sib'"], + ]); + }); + + it('an extension of an object the door does not carry is judged on what does not depend on its fields', () => { + expect(expressionFindings(gateExtension(extension([script('fn', 'sqrt(record.amount) > 1')]), []).errors)).toHaveLength(1); + const read = gateExtension(extension([script('read', 'record.amount != null && record.amount < 0')]), []); + expect(read.errors, dump(read)).toEqual([]); + }); + + it('on an extension write only the extension walk judges: the target\'s own broken rule is not this write\'s to answer for', () => { + const broken = { ...target, validations: [script('own_typo', 'record.amont < 0')] }; + const stack = { objects: [broken, staff], objectExtensions: [extension([script('ok', 'record.amount != null && record.amount < 0')])] }; + // The build judges the object's own rule… + expect(validateStackExpressions(stack).map((i) => i.where)).toEqual(["object 'fx_ticket' · validation 'own_typo'"]); + // …the extension door's pass reads only the written entry. + expect(runStackExpressionPasses(stack, { runtimeWriteType: 'object_extension' })).toEqual([]); + }); + + it('CONTROL — the object save door still judges the object\'s own rule at its own location, and no extension rule', () => { + const own = { ...target, validations: [script('own_typo', 'record.amont < 0')] }; + const result = gateObject(own); + expect(expressionFindings(result.errors).map((f) => f.where)).toEqual(["object 'fx_ticket' · validation 'own_typo'"]); + }); +}); 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 33dc0b8af36..5d1a44254f5 100644 --- a/packages/runtime/src/domains/meta-object-extension-item.test.ts +++ b/packages/runtime/src/domains/meta-object-extension-item.test.ts @@ -462,6 +462,60 @@ describe('[#33072] the publish door judges an extension field\'s formula as `os }, 60_000); }); +describe('[#33154] the publish door judges an extension\'s validation rule as `os build` does', () => { + /** Studio's body for an extension adding one validation rule (and fields) to the account. */ + const ruleBody = (condition: string, fields: Record = {}) => ({ + extend: TARGET, + fields, + validations: [{ name: 'no_blocked__c', type: 'script', condition, message: 'Blocked.' }], + }); + const WHERE = "object 'crm_account' · objectExtensions[0] · validation 'no_blocked__c'"; + const servedRules = (rig: Awaited>) => + ((rig.engine.registry.getObject(TARGET) as any)?.validations ?? []).map((r: any) => r?.name); + + it('⭐ LIT — a rule reading a field the account does not serve is refused with the build\'s rule id and location; the rule is not served', async () => { + const rig = await boot(); + await rig.protocol.saveMetaItem({ type: TYPE, name: TARGET, item: ruleBody("record.nmae == 'blocked'"), 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 }); + const issue = (err.issues ?? []).find((i: any) => i.rule === 'expression-invalid'); + expect(issue, JSON.stringify(err.issues)).toBeDefined(); + expect({ where: issue.where, path: issue.path }) + .toEqual({ where: WHERE, path: 'objectExtensions[0].validations[0].condition' }); + expect(issue.message).toContain('nmae'); + expect(servedRules(rig)).not.toContain('no_blocked__c'); + expect(await rig.rows()).toEqual([{ name: TARGET, package_id: PAIR, state: 'draft' }]); + }, 60_000); + + it('⭐ CONTROL — a valid rule over the account\'s own field publishes and is served on the account', async () => { + const rig = await boot(); + await rig.saveAndPublish(PAIR, ruleBody("record.name != null && record.name == 'blocked'")); + + expect(servedRules(rig)).toContain('no_blocked__c'); + expect(await rig.rows()).toEqual([{ name: TARGET, package_id: PAIR, state: 'active' }]); + }, 60_000); + + it('⭐ LIT (republish) — dropping a field the extension\'s own rule still reads is refused: the stored self lends it nothing', async () => { + const rig = await boot(); + const BONUS = { bonus__c: { type: 'number', label: 'Bonus' } }; + const condition = 'record.bonus__c != null && record.bonus__c > 100'; + await rig.saveAndPublish(PAIR, ruleBody(condition, BONUS)); + expect(servedRules(rig)).toContain('no_blocked__c'); + + await rig.protocol.saveMetaItem({ type: TYPE, name: TARGET, item: ruleBody(condition), mode: 'draft', packageId: PAIR }); + const err: any = await rig.protocol.publishMetaItem({ type: TYPE, name: TARGET, packageId: PAIR }).catch((e: any) => e); + + expect({ code: err?.code, status: err?.status }, 'the stored self still lent bonus__c').toEqual({ code: 'INVALID_METADATA', status: 422 }); + const issue = (err.issues ?? []).find((i: any) => i.rule === 'expression-invalid'); + expect(issue?.where, JSON.stringify(err.issues)).toBe(WHERE); + expect(issue.message).toContain('bonus__c'); + // The served extension is the one published before, untouched. + expect((await rig.fieldsOn()).registry).toContain('bonus__c'); + }, 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'; From a65b8bc5c675b7f8e062d241191775f675542cf8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:42:57 +0000 Subject: [PATCH 3/8] docs, changeset: an extension's validation rules are judged at the build and the object_extension door Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyToDkPxCjvNiWsv6e --- ...bject-extension-validation-rules-judged.md | 22 ++++++++++ .../docs/deployment/validating-metadata.mdx | 4 ++ ...nsion-validation-rule-expression-judged.ts | 40 +++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 .changeset/33154-object-extension-validation-rules-judged.md create mode 100644 packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts diff --git a/.changeset/33154-object-extension-validation-rules-judged.md b/.changeset/33154-object-extension-validation-rules-judged.md new file mode 100644 index 00000000000..b3f952f0936 --- /dev/null +++ b/.changeset/33154-object-extension-validation-rules-judged.md @@ -0,0 +1,22 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': minor +--- + +fix(lint): `os build` and the runtime `object_extension` publish door judge each validation rule an object extension adds by the object's own rule pass, against the extended object as served + +Clause-②: no (narrowing) — `os build`, `os validate` and the `object_extension` publish door (Studio, `PUT /api/v1/meta/object_extension/TARGET`, the MCP and AI authoring doors) now refuse an extension whose validation rule carries a `condition` or `when` the same rule on the object itself is refused for. No exported type or signature changes. Measured first-party: 0 extension entries carry 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 object extension door paragraph names the rule pass); `skills/objectstack-data` teaches validation rules on the object and `defineObjectExtension({ extend, fields })` without saying an extension's rules are exempt, so the build and the door now give the verdict the object's own rules already get. + + + +**BREAKING** accept-set narrowing of `os build`, `os validate` and the runtime `object_extension` publish door. + +**Before:** the registry merges an extension's `validations` onto its target object by name, so every save of the target runs them, but the expression rule judged only the rules an object declares. A rule an extension added with a misspelt field (`record.nmae`), an unregistered function (`sqrt(…)`) or an unguarded nullable operand was accepted by the build and published with a 200, and failed only when an end user saved a record. + +**Now:** each rule an `objectExtensions` entry adds is judged by the object's own rule pass (its `condition` and `when`, every nested `then` / `otherwise` branch, the `parent` root verdict and the null-guard gate), with the same rule id `expression-invalid`, against the extended object as served (its own fields and every field an extension adds). A finding is located at the entry: `object 'crm_account' · objectExtensions[0] · validation 'no_blocked__c'`, key path `objectExtensions[0].validations[0].condition`. At the door the refusal is `422 INVALID_METADATA`, the door still runs one pass (the extension walk), and a republish is judged without the package's own stored extension, which the write replaces. + +**Unchanged:** the object save door, an object's own rules, a draft save (never gated), a stored row (judged only when it is published again), and the regex and JSON-schema checks of a `format` / `json_schema` rule, which still judge an object's own rules only. + +**Fix:** before building or publishing again, repair each refused rule the way you would on a rule declared on the same object: read `record.FIELD` for a field the object serves, call only registered functions, guard a nullable operand with `!= null`, and read through a reference only in the shape a declared rule may. diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 241b54313dc..0bdf227e8de 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -610,6 +610,10 @@ declarations, not words an app adds. The same door runs the build's field-formula pass on each computed field the written entry adds (#33072), against the target as served without the package's own stored extension, which 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'`). **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/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts b/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts new file mode 100644 index 00000000000..76f6335e17e --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts @@ -0,0 +1,40 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #33154: an accept-set narrowing of `os build`, `os validate` and the runtime +// `object_extension` publish door. The registry merges an extension's +// `validations` onto its target object by name, so every save of the target +// runs them, but the expression rule of `@objectstack/lint` +// (`validateStackExpressions`) judged only the rules an object declares. It now +// judges each rule an `objectExtensions` entry adds by the object's own rule +// pass, against the extended object as served, at the build and the door. No D2 +// conversion: how a refused rule is repaired (the field it meant, a registered +// function, a null guard) 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-expression-judged', + surface: + 'a validation rule an `objectExtensions` entry adds (`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) whose `condition` or `when` (a nested `then` / `otherwise` branch included) ' + + 'is CEL, e.g. `{ extend: \'crm_account\', validations: [{ name: \'no_blocked\', type: \'script\', ' + + 'condition: \'record.nmae == "blocked"\', message: \'Blocked.\' }] }`.', + replacement: + 'A rule the expression rule accepts on a declared rule of the same object: CEL that reads `record.FIELD` for ' + + 'a field the extended object serves (its own fields and every field an extension adds), calls only ' + + 'registered functions, guards a nullable operand with `!= null`, and reads one hop through a reference ' + + 'only as a declared rule may.', + reason: + 'The registry merges an extension\'s rules onto the target, so every save of the target runs them, but ' + + 'neither `os build` nor the `object_extension` publish door judged them: a misspelt field or an ' + + 'unregistered function was accepted and failed only when an end user saved a record. Each rule an ' + + 'extension adds is now judged by the object\'s own rule pass, against the extended object as served ' + + '(at the door, without the package\'s own stored extension, which the write replaces), and refused with ' + + 'the same rule id (`expression-invalid`; at the door `422 INVALID_METADATA`), located at ' + + '`object \'TARGET\' · objectExtensions[0] · validation \'RULE\'`.', + acceptanceCriteria: + '`os build` reports no `expression-invalid` finding located at an `objectExtensions[N] · validation` site, ' + + 'and publishing each extension that adds a validation rule again answers 200 with no such issue. A ' + + 'record of the extended object that the rule should refuse is refused on save with the rule\'s message.', +}; From bd6970c2040f6cc14d4d7b02f3e7a0086dc0a5bf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:47:46 +0000 Subject: [PATCH 4/8] test(runtime): the extension fixture's rule reads record.region__c, as a rule declared on the object must Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyToDkPxCjvNiWsv6e --- .../runtime/src/domains/meta-object-extension-item.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 5d1a44254f5..2a2ee7965d1 100644 --- a/packages/runtime/src/domains/meta-object-extension-item.test.ts +++ b/packages/runtime/src/domains/meta-object-extension-item.test.ts @@ -192,7 +192,10 @@ describe('[#28574] a writable pair saves and publishes an extension of the base\ it('the whole parsed body is registered: an extension\'s `validations` reach the object', async () => { const rig = await boot(); - const rule = { name: 'region_required', type: 'script', condition: 'region__c == null', message: 'Region is required', events: ['insert'] }; + // [#33154] `record.`-scoped, as a rule declared on the account must be: + // the door now judges an extension's rules by the object's own rule + // pass, which refuses the bare `region__c` this fixture used to carry. + const rule = { name: 'region_required', type: 'script', condition: 'record.region__c == null', message: 'Region is required', events: ['insert'] }; await rig.saveAndPublish(PAIR, regionBody({ validations: [rule] })); const names = ((rig.engine.registry.getObject(TARGET) as any)?.validations ?? []).map((v: any) => v?.name); From 9b977c294eaa7122c8c9f3f990b2c263819ae299 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:55:27 +0000 Subject: [PATCH 5/8] test(lint): the authored-site enumeration reads the hoisted rule pass; the extension rule loop adds no receiver Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyToDkPxCjvNiWsv6e --- packages/lint/src/authored-site-expression.test.ts | 11 ++++++----- packages/lint/src/validate-expressions.ts | 6 +++++- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/lint/src/authored-site-expression.test.ts b/packages/lint/src/authored-site-expression.test.ts index 2bc8c3bc6dc..4907441b1d2 100644 --- a/packages/lint/src/authored-site-expression.test.ts +++ b/packages/lint/src/authored-site-expression.test.ts @@ -94,8 +94,6 @@ function walkPushes(code: string): string[] { const SITE_MEMBER_CALLS: Record> = { validation: { get: 'a Map read (the object index, the field definitions)', - indexOf: 'a string offset, reading the slot key', - isArray: '`Array.isArray`', push: "appends a finding to the walk's list", }, formula: { @@ -130,14 +128,17 @@ const CYCLE = { }, }; -/** Where each site's calls are read: the rule loop and the `check` helper it calls; the field-formula pass and what follows the fields loop. */ +/** Where each site's calls are read: the rule pass (`judgeValidationRule`) and the `check` helper it calls; the field-formula pass and what follows the fields loop. */ const SITE_REGIONS: Record> = { validation: [ [' const check = (', ' const fieldRuleRootVerdict = ('], - [' for (const rule of recordsOf(validations)) {', ' // Field-level formulas'], + // [#33154] The rule pass, hoisted out of the object walk so the extension + // walk judges an extension's rules by the same body; the object walk's + // loop now calls it and nothing else. + [' const judgeValidationRule = (', ' // ── Object validation-rule'], ], formula: [ - [' const judgeFieldFormula = (', ' // ── Object validation-rule'], + [' const judgeFieldFormula = (', ' const judgeValidationRule = ('], [ ' judgeFieldFormula(fname, f, { objectName, optionFields: optionFieldNames, fieldDefs });\n }', " // [#26646] A field group's section predicate", diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index cac51bd176c..a3c3164d03b 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -4118,7 +4118,11 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // item-relative (`validations.0.condition`). The index is the authored // one: `ObjectExtensionSchema` declares `validations` an array of rule // records, and `recordsOf` hands an array's records back in order. - for (const [ruleIndex, rule] of rules.entries()) { + // Counted by hand, as `objectPosition` is, so the #5017 key scan sees + // no new receiver. + let ruleIndex = -1; + for (const rule of rules) { + ruleIndex += 1; judgeValidationRule(rule, { objectName: target, locus: `object '${target}' · ${entryPath}`, From ffd89720d32a4b1724664b8417e00a3eff3a0635 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 01:36:35 +0000 Subject: [PATCH 6/8] test(runtime): the disable-door suite's tenant extension rule guards its nullable operand Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyToDkPxCjvNiWsv6e --- .../domains/packages-disable-module-extension-fields.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts b/packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts index d646b6ef6cc..f15a222f239 100644 --- a/packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts +++ b/packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts @@ -589,7 +589,10 @@ describe('[#30379] the disable door refuses while an enabled package\'s validati extend: ACCOUNT, validations: [{ name: RULE_TENANT, type: 'script', severity: 'error', message: 'Credit is capped', - condition: `record.${CREDIT} > 5000000`, + // Null-guarded: the publish door judges an extension's rule by + // the object's own rule pass, whose null-guard gate refuses an + // unguarded nullable operand (#33154). + condition: `record.${CREDIT} != null && record.${CREDIT} > 5000000`, }], }, }); From e4ee8af8ed1265369b1ea79acb26a3a9b786cb47 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 01:37:55 +0000 Subject: [PATCH 7/8] docs(changeset, spec): name the null-guard refusal an extension rule now meets, and its fix Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyToDkPxCjvNiWsv6e --- .../33154-object-extension-validation-rules-judged.md | 4 +++- ....object-extension-validation-rule-expression-judged.ts | 8 +++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/.changeset/33154-object-extension-validation-rules-judged.md b/.changeset/33154-object-extension-validation-rules-judged.md index b3f952f0936..c6441245428 100644 --- a/.changeset/33154-object-extension-validation-rules-judged.md +++ b/.changeset/33154-object-extension-validation-rules-judged.md @@ -17,6 +17,8 @@ Skills-docs: none owed — this PR edits `content/docs/deployment/validating-met **Now:** each rule an `objectExtensions` entry adds is judged by the object's own rule pass (its `condition` and `when`, every nested `then` / `otherwise` branch, the `parent` root verdict and the null-guard gate), with the same rule id `expression-invalid`, against the extended object as served (its own fields and every field an extension adds). A finding is located at the entry: `object 'crm_account' · objectExtensions[0] · validation 'no_blocked__c'`, key path `objectExtensions[0].validations[0].condition`. At the door the refusal is `422 INVALID_METADATA`, the door still runs one pass (the extension walk), and a republish is judged without the package's own stored extension, which the write replaces. +The null-guard gate is part of that pass, and it is the narrowing most likely to meet a working tenant: an extension rule that reads a nullable field with no guard, such as `record.credit > 5000000` on a `number` field with no `required: true` and no `defaultValue`, is now refused. At runtime that predicate aborts on every save where the field is empty, and the save is refused fail-closed. The repository's own suite carried one such rule and now guards it. + **Unchanged:** the object save door, an object's own rules, a draft save (never gated), a stored row (judged only when it is published again), and the regex and JSON-schema checks of a `format` / `json_schema` rule, which still judge an object's own rules only. -**Fix:** before building or publishing again, repair each refused rule the way you would on a rule declared on the same object: read `record.FIELD` for a field the object serves, call only registered functions, guard a nullable operand with `!= null`, and read through a reference only in the shape a declared rule may. +**Fix:** before building or publishing again, repair each refused rule the way you would on a rule declared on the same object: read `record.FIELD` for a field the object serves, call only registered functions, guard a nullable operand with `!= null` (`record.credit != null && record.credit > 5000000`), and read through a reference only in the shape a declared rule may. diff --git a/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts b/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts index 76f6335e17e..071e72916f2 100644 --- a/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts +++ b/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts @@ -23,12 +23,14 @@ export const entry: SemanticMigration = { replacement: 'A rule the expression rule accepts on a declared rule of the same object: CEL that reads `record.FIELD` for ' + 'a field the extended object serves (its own fields and every field an extension adds), calls only ' - + 'registered functions, guards a nullable operand with `!= null`, and reads one hop through a reference ' - + 'only as a declared rule may.', + + 'registered functions, guards a nullable operand with `!= null` (`record.credit != null && record.credit > ' + + '5000000`, not a bare `record.credit > 5000000` on a field with no `required: true` and no `defaultValue`), ' + + 'and reads one hop through a reference only as a declared rule may.', reason: 'The registry merges an extension\'s rules onto the target, so every save of the target runs them, but ' + 'neither `os build` nor the `object_extension` publish door judged them: a misspelt field or an ' - + 'unregistered function was accepted and failed only when an end user saved a record. Each rule an ' + + 'unregistered function was accepted and failed only when an end user saved a record, and a rule reading a ' + + 'nullable field with no guard aborted and refused every save where that field was empty. Each rule an ' + 'extension adds is now judged by the object\'s own rule pass, against the extended object as served ' + '(at the door, without the package\'s own stored extension, which the write replaces), and refused with ' + 'the same rule id (`expression-invalid`; at the door `422 INVALID_METADATA`), located at ' From 9d07ffa069baf93055b4da43e19fccbf9237159c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 03:34:25 +0000 Subject: [PATCH 8/8] fix(lint): read the extension door's objects without injected system columns The object_extension door hands the objects as the registry serves them, with the injected system columns (created_at, owner_id, ...) declared, so the null-guard gate judged record.created_at as a declared nullable field and refused an extension rule os build accepts. On that write each object is now read through stripInjectedSystemColumns, as the authored-site expression judge does. Pinned at the gate and the real door (accepted at both; a declared nullable field still refused at both). Comments, the changeset and the semantic entry now say that the leaf of a one-hop read through an extension-added reference is not judged, that the door's 422 keeps the stack path, that os lint narrows too, and that the null-guard gate judges ordering and arithmetic operands only. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyToDkPxCjvNiWsv6e --- ...bject-extension-validation-rules-judged.md | 14 +++--- ...runtime-gate.object-formula-writes.test.ts | 18 +++++++ packages/lint/src/validate-expressions.ts | 49 ++++++++++++++----- .../meta-object-extension-item.test.ts | 29 +++++++++++ ...nsion-validation-rule-expression-judged.ts | 19 ++++--- 5 files changed, 102 insertions(+), 27 deletions(-) diff --git a/.changeset/33154-object-extension-validation-rules-judged.md b/.changeset/33154-object-extension-validation-rules-judged.md index c6441245428..a9533619a6e 100644 --- a/.changeset/33154-object-extension-validation-rules-judged.md +++ b/.changeset/33154-object-extension-validation-rules-judged.md @@ -5,20 +5,20 @@ fix(lint): `os build` and the runtime `object_extension` publish door judge each validation rule an object extension adds by the object's own rule pass, against the extended object as served -Clause-②: no (narrowing) — `os build`, `os validate` and the `object_extension` publish door (Studio, `PUT /api/v1/meta/object_extension/TARGET`, the MCP and AI authoring doors) now refuse an extension whose validation rule carries a `condition` or `when` the same rule on the object itself is refused for. No exported type or signature changes. Measured first-party: 0 extension entries carry 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. +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 an extension whose validation rule carries a `condition` or `when` the same rule on the object itself is refused for. No exported type or signature changes. Measured first-party: 0 extension entries carry 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 object extension door paragraph names the rule pass); `skills/objectstack-data` teaches validation rules on the object and `defineObjectExtension({ extend, fields })` without saying an extension's rules are exempt, so the build and the door now give the verdict the object's own rules already get. -**BREAKING** accept-set narrowing of `os build`, `os validate` and the runtime `object_extension` publish door. +**BREAKING** accept-set narrowing of `os build`, `os validate`, `os lint` and the runtime `object_extension` publish door. -**Before:** the registry merges an extension's `validations` onto its target object by name, so every save of the target runs them, but the expression rule judged only the rules an object declares. A rule an extension added with a misspelt field (`record.nmae`), an unregistered function (`sqrt(…)`) or an unguarded nullable operand was accepted by the build and published with a 200, and failed only when an end user saved a record. +**Before:** the registry merges an extension's `validations` onto its target object by name, so every save of the target runs them, but the expression rule judged only the rules an object declares. A rule an extension added with a misspelt field (`record.nmae`), an unregistered function (`sqrt(…)`) or an unguarded nullable operand was accepted by `os build`, `os validate` and `os lint` and published with a 200, and failed only when an end user saved a record. -**Now:** each rule an `objectExtensions` entry adds is judged by the object's own rule pass (its `condition` and `when`, every nested `then` / `otherwise` branch, the `parent` root verdict and the null-guard gate), with the same rule id `expression-invalid`, against the extended object as served (its own fields and every field an extension adds). A finding is located at the entry: `object 'crm_account' · objectExtensions[0] · validation 'no_blocked__c'`, key path `objectExtensions[0].validations[0].condition`. At the door the refusal is `422 INVALID_METADATA`, the door still runs one pass (the extension walk), and a republish is judged without the package's own stored extension, which the write replaces. +**Now:** each rule an `objectExtensions` entry adds is judged by the object's own rule pass (its `condition` and `when`, every nested `then` / `otherwise` branch, the `parent` root verdict and the null-guard gate), with the same rule id `expression-invalid`, in `os build`, `os validate` and `os lint` as at the door. A `record.FIELD` read resolves against the extended object as served (its own fields and every field an extension adds). The door reads the objects without the system columns the registry injects, as the build does, so a column such as `created_at` is a known field and is not judged nullable at either. A finding is located at the entry: `object 'crm_account' · objectExtensions[0] · validation 'no_blocked__c'`, key path `objectExtensions[0].validations[0].condition`. At the door the refusal is `422 INVALID_METADATA`, the door still runs one pass (the extension walk), and a republish is judged without the package's own stored extension, which the write replaces. -The null-guard gate is part of that pass, and it is the narrowing most likely to meet a working tenant: an extension rule that reads a nullable field with no guard, such as `record.credit > 5000000` on a `number` field with no `required: true` and no `defaultValue`, is now refused. At runtime that predicate aborts on every save where the field is empty, and the save is refused fail-closed. The repository's own suite carried one such rule and now guards it. +The null-guard gate is part of that pass, and it is the narrowing most likely to meet a working tenant: an extension rule that applies an ordering or arithmetic operator (`>`, `<`, `+`, …) to a nullable field with no guard, such as `record.credit > 5000000` on a declared `number` field with no `required: true` and no `defaultValue`, is now refused. An equality such as `record.credit == null` is not. At runtime that predicate aborts on every save where the field is empty, and the save is refused fail-closed. The repository's own suite carried one such rule and now guards it. -**Unchanged:** the object save door, an object's own rules, a draft save (never gated), a stored row (judged only when it is published again), and the regex and JSON-schema checks of a `format` / `json_schema` rule, which still judge an object's own rules only. +**Unchanged:** the object save door, an object's own rules, a draft save (never gated), a stored row (judged only when it is published again), and the regex and JSON-schema checks of a `format` / `json_schema` rule, which still judge an object's own rules only. The leaf of a one-hop read through a reference an extension adds (`record.manager__c.nmae`) is still not judged, at the build or the door: the hop checks read the declared objects. A hop through a reference the target declares is judged. -**Fix:** before building or publishing again, repair each refused rule the way you would on a rule declared on the same object: read `record.FIELD` for a field the object serves, call only registered functions, guard a nullable operand with `!= null` (`record.credit != null && record.credit > 5000000`), and read through a reference only in the shape a declared rule may. +**Fix:** before building or publishing again, repair each refused rule the way you would on a rule declared on the same object: read `record.FIELD` for a field the object serves, call only registered functions, guard a nullable operand of an ordering or arithmetic operator with `!= null` (`record.credit != null && record.credit > 5000000`), and read through a reference only in the shape a declared rule may. 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 d42d5fba6a3..f1187687dff 100644 --- a/packages/lint/src/runtime-gate.object-formula-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-formula-writes.test.ts @@ -38,6 +38,7 @@ * the #22019 block of `packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts`. */ import { describe, expect, it } from 'vitest'; +import { applyInjectedSystemColumns } from '@objectstack/metadata-core'; import { EXPRESSION_INVALID, runAuthoringRules } from './authoring-rules.js'; import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js'; import { runStackExpressionPasses, validateStackExpressions } from './validate-expressions.js'; @@ -520,6 +521,23 @@ describe('#33154 — an extension\'s validation rules are judged at the build an } }); + it('⭐ PARITY — the door reads the objects as served, injected system columns and all: an unguarded ordering over `created_at` is accepted there as at the build, one over a declared nullable field is refused at both', () => { + // As the registry serves them: `created_at`, `owner_id`, … declared. + const served = [applyInjectedSystemColumns(target), applyInjectedSystemColumns(staff)]; + expect(Object.keys(served[0]!.fields)).toContain('created_at'); + for (const [condition, refused] of [ + ["record.created_at > timestamp('2020-01-01T00:00:00Z')", false], + ['record.amount > 0', true], + ] as const) { + const item = extension([script('since', condition)]); + const atDoor = gateExtension(item, served); + const atBuild = buildFindings({ objects: [target, staff], objectExtensions: [item] }); + + expect([...atDoor.errors, ...atDoor.advisories], condition).toEqual(atBuild); + expect(atBuild.length > 0, `${condition}: ${dump(atBuild)}`).toBe(refused); + } + }); + it('⭐ CONTROL — a valid rule, a rule reading a field the same extension adds, and a one-hop read publish clean', () => { for (const item of [ extension([script('ok', 'record.amount != null && record.amount < 0')]), diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index a3c3164d03b..72951696caa 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -158,6 +158,7 @@ import type { FlowCelEntrance } from './flow-cel-root-scope.js'; import { injectedColumnDefsFor, injectedColumnsFor, unprovisionedInjectedColumnsFor } from './system-fields.js'; import { findUnguardedNullableOperands, nullGuardMessage, provenNonNullKeys } from './validate-null-guards.js'; import type { NullGuardOptions, NullGuardOutcome } from './validate-null-guards.js'; +import { stripInjectedSystemColumns } from '@objectstack/metadata-core'; import { objectExtensionsByTarget, objectsAsServed, objectsWithoutTiedFields, recordsOf } from './object-graph.js'; import { storedExpressionInputIssues } from './stored-expression-inputs.js'; import { formulaCycleIssues } from './formula-cycle-issues.js'; @@ -2270,8 +2271,12 @@ export interface StackExpressionOptions { * `objectsAsServed`, the build's own fold — and located at the entry, as the * build locates it. [#33154] The same walk judges each validation rule the * written entry adds, by the object walk's own rule pass - * (`judgeValidationRule`), against the same served target and located at - * the entry (`object 'T' · objectExtensions[0] · validation 'N'`). The + * (`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 + * (`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 * object walk reads an empty list (the carried objects are the universe the * field or rule resolves in, not the subject) and so does every other pass; * the function returns after the extension walk. @@ -2359,6 +2364,17 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression if (options.runtimeWriteType === 'page') { return actionCopyTemplateIssues(stack, { actions: false, objects: false, pages: true }); } + // [#33154] The extension door hands the objects as the registry SERVES + // them, and a served definition carries the system columns the registry + // injects (`created_at`, `owner_id`, …) as declared fields; the build reads + // the objects as authored. Unstripped, the null-guard gate judged + // `record.created_at` as a declared nullable field and refused at the door + // an extension rule `os build` accepts. So on that write each object is read + // through `stripInjectedSystemColumns` (`@objectstack/metadata-core`, the + // write path's own strip of exactly those, as `authored-site-expression.ts` + // reads the served objects), and the indexes re-derive the injected columns + // themselves, as they do at the build. + if (extensionWrite) stack = { ...stack, objects: recordsOf(stack.objects).map((o) => stripInjectedSystemColumns(o)) }; const objects = recordsOf(stack.objects); // [#30471] The field indexes read the objects as the registry SERVES them, // every `objectExtensions` field of any body folded in (`objectsAsServed`, @@ -4064,9 +4080,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // [#33072] The `object_extension` publish door runs this walk and nothing // else: its snapshot carries the written entry as the sole member of // `objectExtensions` and the door's live objects as `objects`, so the field - // (and, #33154, the rule) is judged against its target as served and - // located where the build locates it (`objectExtensions[0]` for a one-entry - // stack). + // (and, #33154, the rule's field reads) is judged against its target as + // served and located where the build locates it (`objectExtensions[0]` for + // a one-entry stack). for (const [target, entries] of objectWrite ? [] : objectExtensionsByTarget(stack)) { // The target's position in `objects`, which is its position in // `typedObjects` too (see `objectPosition` above); -1 when undeclared. @@ -4108,14 +4124,21 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // [#33154] Each validation rule the entry adds, by the object walk's // own rule pass ({@link judgeValidationRule}): the registry merges an // extension's `validations` onto the target by name, so every save of - // the target runs it as it runs the target's own rules. Judged against - // the target as served, through the same indexes, so a read of 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. Located at the entry - // (`object 'T' · objectExtensions[0] · validation 'N'`), the key path at - // the rule's slot under the entry, which the door re-spells - // item-relative (`validations.0.condition`). The index is the authored + // the target runs it as it runs the target's own rules. A `record.FIELD` + // read resolves against the target's fields as served (`fieldIndex`, + // 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] · + // 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` + // re-spell it item-relative (`validations.0.condition`). The index is the authored // one: `ObjectExtensionSchema` declares `validations` an array of rule // records, and `recordsOf` hands an array's records back in order. // Counted by hand, as `objectPosition` is, so the #5017 key scan sees 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 2a2ee7965d1..3e30f989edb 100644 --- a/packages/runtime/src/domains/meta-object-extension-item.test.ts +++ b/packages/runtime/src/domains/meta-object-extension-item.test.ts @@ -35,6 +35,7 @@ import { SqlDriver } from '@objectstack/driver-sql'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; import { ObjectExtensionSchema } from '@objectstack/spec/data'; +import { runAuthoringRules } from '@objectstack/lint'; import { HttpDispatcher } from '../http-dispatcher.js'; // The [#29594] rehearsal boots the real dispatcher, whose package door reaches // `import('@objectstack/metadata')` in standalone-stack.ts; pay that load @@ -500,6 +501,34 @@ describe('[#33154] the publish door judges an extension\'s validation rule as `o expect(await rig.rows()).toEqual([{ name: TARGET, package_id: PAIR, state: 'active' }]); }, 60_000); + it('⭐ PARITY — an unguarded ordering over the injected `created_at` publishes at the door, as `os build` accepts the same entry; one over a declared nullable field is refused at both', async () => { + /** `os build`'s findings at the extension, over the account as authored. */ + const atBuild = (item: unknown) => { + const stack = { objects: baseManifest().objects, objectExtensions: [item] }; + return runAuthoringRules('build', { normalized: stack, parsed: stack } as any) + .filter((f) => f.where.includes('objectExtensions')) + .map((f) => ({ rule: f.rule, where: f.where, path: f.path })); + }; + const since = ruleBody("record.created_at > timestamp('2020-01-01T00:00:00Z')"); + expect(atBuild(since)).toEqual([]); + + const rig = await boot(); + // Served, the account declares the columns the registry injects. + expect((await rig.fieldsOn()).registry).toContain('created_at'); + await rig.saveAndPublish(PAIR, since); + expect(servedRules(rig)).toContain('no_blocked__c'); + expect(await rig.rows()).toEqual([{ name: TARGET, package_id: PAIR, state: 'active' }]); + + // The null-guard gate still judges a field the account declares nullable. + const unguarded = ruleBody('record.bonus__c > 100', { bonus__c: { type: 'number', label: 'Bonus' } }); + const refusedAtBuild = atBuild(unguarded); + expect(refusedAtBuild).toHaveLength(1); + await rig.protocol.saveMetaItem({ type: TYPE, name: TARGET, item: unguarded, mode: 'draft', packageId: PAIR }); + const err: any = await rig.protocol.publishMetaItem({ type: TYPE, name: TARGET, packageId: PAIR }).catch((e: any) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + expect((err.issues ?? []).map((i: any) => ({ rule: i.rule, where: i.where, path: i.path }))).toEqual(refusedAtBuild); + }, 60_000); + it('⭐ LIT (republish) — dropping a field the extension\'s own rule still reads is refused: the stored self lends it nothing', async () => { const rig = await boot(); const BONUS = { bonus__c: { type: 'number', label: 'Bonus' } }; diff --git a/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts b/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts index 071e72916f2..69b47cfb295 100644 --- a/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts +++ b/packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts @@ -8,7 +8,8 @@ import type { SemanticMigration } from '../../types.js'; // runs them, but the expression rule of `@objectstack/lint` // (`validateStackExpressions`) judged only the rules an object declares. It now // judges each rule an `objectExtensions` entry adds by the object's own rule -// pass, against the extended object as served, at the build and the door. No D2 +// pass, its field reads resolved against the extended object as served, at the +// build and the door. No D2 // conversion: how a refused rule is repaired (the field it meant, a registered // function, a null guard) is a fact only the author holds, and a stored row is // not re-judged until it is published again. @@ -23,18 +24,22 @@ export const entry: SemanticMigration = { replacement: 'A rule the expression rule accepts on a declared rule of the same object: CEL that reads `record.FIELD` for ' + 'a field the extended object serves (its own fields and every field an extension adds), calls only ' - + 'registered functions, guards a nullable operand with `!= null` (`record.credit != null && record.credit > ' + + 'registered functions, guards a nullable operand of an ordering or arithmetic operator with `!= null` ' + + '(`record.credit != null && record.credit > ' + '5000000`, not a bare `record.credit > 5000000` on a field with no `required: true` and no `defaultValue`), ' + 'and reads one hop through a reference only as a declared rule may.', reason: 'The registry merges an extension\'s rules onto the target, so every save of the target runs them, but ' + 'neither `os build` nor the `object_extension` publish door judged them: a misspelt field or an ' - + 'unregistered function was accepted and failed only when an end user saved a record, and a rule reading a ' - + 'nullable field with no guard aborted and refused every save where that field was empty. Each rule an ' - + 'extension adds is now judged by the object\'s own rule pass, against the extended object as served ' + + 'unregistered function was accepted and failed only when an end user saved a record, and a rule applying an ' + + 'ordering or arithmetic operator to a nullable field with no guard aborted and refused every save where ' + + 'that field was empty (an equality such as `== null` is accepted). Each rule an extension adds is now ' + + 'judged by the object\'s own rule pass, its field reads resolved against the extended object as served ' + '(at the door, without the package\'s own stored extension, which the write replaces), and refused with ' - + 'the same rule id (`expression-invalid`; at the door `422 INVALID_METADATA`), located at ' - + '`object \'TARGET\' · objectExtensions[0] · validation \'RULE\'`.', + + 'the same rule id (`expression-invalid`; at the door `422 INVALID_METADATA`), located at the entry: ' + + '`object \'TARGET\' · objectExtensions[N] · validation \'RULE\'`, where N is the entry\'s own index, ' + + '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 no `expression-invalid` finding located at an `objectExtensions[N] · validation` site, ' + 'and publishing each extension that adds a validation rule again answers 200 with no such issue. A '