diff --git a/.changeset/37909-rule-message-render.md b/.changeset/37909-rule-message-render.md new file mode 100644 index 00000000000..16bf6035ee9 --- /dev/null +++ b/.changeset/37909-rule-message-render.md @@ -0,0 +1,18 @@ +--- +'@objectstack/objectql': minor +'@objectstack/spec': minor +'@objectstack/lint': minor +--- + +feat(objectql): a validation rule's refusal fills its message's `{{ }}` holes with the judged record's values + +Clause-②: yes (widening) +Metadata-protocol: semantic + +A validation rule's `message`, and the translation of it a refusal shows, is now filled when a write is refused: `{{ record.FIELD }}` shows the merged record the rule judged and `{{ previous.FIELD }}` the stored row before an update, through the template formatters (`currency`, `number`, `percent`, `date`, `datetime`, `upper`, `lower`, `trim`, `truncate`, `default`, `json`). `Total {{ record.total_price | currency }} is below what was received ({{ record.received_amount | currency }})` now reads `Total $1,200.00 is below what was received ($1,500.00)`. Before, the sentence was returned as written, holes and all. A message with no `{{` is returned exactly as before. + +- **What a hole may show.** A hole shows a field only when the person the refusal is worded for may read it unmasked, as the security service answers for that person. On an ordinary write that is the person who wrote. On an elevated write made for a person (a `runAs: 'system'` flow they started, whose refusal reaches them as the run's `innerRefusal`; an action body; an approval decision), the security service is asked for that person, with their own permission sets, never for the system; if their grants cannot be read, every hole renders empty. Only an elevated write that names no person (a schedule, a platform sweep) is answered as the system, and its sentence reaches the server log alone. A field the reader cannot read, a field masked for them, a `secret` / `password` or `internal` field, a field the object does not declare, a read through a field (`{{ record.account.name }}`) and a hole over any other root render empty. If no security service is registered, or the one registered cannot answer, answers nothing or fails, every hole renders empty and the server log says why, once per write. The rule's verdict never depends on the sentence, and no value is added to the error's other fields. +- **Formatting.** The formatters render in the refusal's language. `| currency` with no argument formats in the organization's default currency (Setup → Localization, `localization.currency`); `| currency:EUR` names one. If no default currency reaches the write (the organization has none set, or the write carried none), a `| currency` hole with no argument renders empty, the rest of the sentence renders, and a warning in the server log names the rule and the setting to fill; the amount is never formatted in a currency nobody chose. `{{ previous.FIELD }}` renders empty on an insert. +- **Translations first.** The translation for the refusal's language is filled first. A translation that does not render (one stored before `objectstack validate` judged it) is replaced by the authored message, filled, and a warning in the server log names the translation. An authored message that does not render is shown as written, as before, and the log names the rule. + +What changes for a deployed app: a rule message that already carries a `{{ record.FIELD }}` hole shows the value from this release. A message stored before `objectstack validate` judged its holes may carry one no reader can ever see filled: a hole over another root (`{{ from }}`), a bare root (`{{ record }}`), a read through a field, or a field the object does not declare. Such a hole now renders empty where it used to be shown as written, and the server log names the rule and the hole on each write that renders it. Run `objectstack validate` and rewrite each hole it names. diff --git a/.changeset/37909-rule-message-template-holes.md b/.changeset/37909-rule-message-template-holes.md index 1539376223e..59ff6e33dd9 100644 --- a/.changeset/37909-rule-message-template-holes.md +++ b/.changeset/37909-rule-message-template-holes.md @@ -21,7 +21,7 @@ The message is now a `{{ }}` template (ADR-0032 §3) over the record the rule ju Filling the holes at run time is the next change on this card; until it lands, a hole that passes the doors is returned as written. -- **Exports.** `@objectstack/spec/data` gains `VALIDATION_MESSAGE_TEMPLATE_ROOTS` (`['record', 'previous']`). The `message` describe of the six validation-rule variants and of the `_validations` translation entry now state the template. +- **Exports.** `@objectstack/spec/data` gains `VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS` (`['record', 'previous']`). The `message` describe of the six validation-rule variants and of the `_validations` translation entry now state the template. - **The ADR-0087 ledger** gains the semantic entry `validation-rule-message-template-holes` under step 19. FROM → TO: diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 87f8f63a9b4..ff29fd9e7cd 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -158,6 +158,7 @@ bugs — it is the protection or the side effect that silently does not happen. | 29d | The recycle bin's tenant wall does not apply: `restore`, `purge` and `empty` read and remove **every organization's** entries | objectql | Get: the bin's own doors reach any entry, as the system reaches every wall. Every caller that is not system is held to the Layer-0 verdict: one the wall denies (a signed-in caller with no active organization under a walled posture) sees no entry, so `restore` answers `null`, `purge` `false` and `empty` `0`, and the removal is scoped by the verdict the security layer recorded on the dispatch when it recorded one (#30237) | `recycleBinWallDenies` | | 29e | A restore of an entry someone else deleted asks **no recycle-bin grant** | objectql | Get: the system restores any entry. Every caller that is not system restores only the entries whose `deleted_by` is its own `userId` unless its effective permissions grant `manageRecycleBin` on the entry's object; otherwise `403 PERMISSION_DENIED`, and the same refusal when no permission resolver is registered or it throws (#30237, ADR-0148 D5) | `assertCallerMayRestoreEntry` | | 29f | Listing the recycle bin of an object asks **no recycle-bin grant** | objectql | Get: the system lists every entry of any object the bin takes. Every caller that is not system lists an object's entries only when its effective permissions grant `manageRecycleBin` on the object; otherwise `403 PERMISSION_DENIED`, and the same refusal when no permission resolver is registered or it throws (#30237, ADR-0148 D5) | `assertCallerManagesRecycleBin` | +| 29g | A validation rule message's `{{ }}` holes show **every field the system may read**, only when the write names no person | objectql | Get: a user-less system write (a schedule, a platform sweep) fills a refused write's message holes with the security service's system answer, every field less credential and `internal` ones; that sentence reaches the server log alone. An elevated write that names a person (`userId`: a `runAs: 'system'` flow they started, whose refusal reaches them as `innerRefusal`; an action body; the approvals mirror) is not read as the system: both field projections are asked for that person, with the permission sets the context carries or their own grants (`resolveUserAuthzGrants`), and every hole renders empty when those grants cannot be read (#37909) | `readerContext` | | 30 | **Bulk data event `organizationId` OMITTED** — the batch is published "not asserted" | plugin-security | Get: nothing — the `data.records.*` event still publishes. Lose: the per-organization attribution: this exit is taken before the security middleware composes any tenant wall, so it records no Layer 0 verdict on the operation (`OperationContext.tenantLayer0Verdict`, #15813), and the engine's bulk producer — which reads that recorded verdict and nothing else — omits the key rather than filling it from the caller's `tenantId`; a tenant-scoped consumer then does not deliver the event inside an organization wall (#15225) | `registerAuthzMiddleware` | | 30b | **The import doors admit a control opt-out** — `runAutomations: false` and `treatAsHistorical: true` on `POST /data/:object/import` and `/import/jobs` | rest | Get: an import whose rows are written with `skipAutomations` (no metadata-bound hook, no record-change trigger: an app's approvals and record freezes among them) or with `skipStateMachine` and `preserveAudit`. Every other caller, every signed-in user and administrator included, is refused `403 PERMISSION_DENIED` before the body is parsed, so nothing is written and no job is created. Inbound HTTP never carries the flag, so this is an in-process caller's door. Note: the flag still suppresses none of those controls by itself (see below); it only admits the opt-outs that do | `importControlOptOutRefusal` | | 30c | **The import undo keeps the control skips** — `POST /data/import/jobs/:jobId/undo` | rest | Get: an undo whose deletes and restores are written with `skipAutomations` and `skipStateMachine`, so no metadata-bound hook, record-change trigger or `state_machine` rule refuses a reversal. Every other caller, every signed-in user and administrator included, undoes under those controls: a reversal one of them refuses is reported per row in the undo answer's `failures` and kept in the job's undo log, and the job is stamped reverted only once every row is. A historical job's `preserveAudit` belongs to the job, not the caller, and rides every undo. Inbound HTTP never carries the flag, so this is an in-process caller's door | `importUndoWriteContext` | @@ -561,6 +562,7 @@ and CI refuses one that differs from what the tree produces. | `packages/objectql/src/engine-referential-integrity.ts#masterDetailHeadersCallerReads` | 1 | 29c | | `packages/objectql/src/engine-referential-integrity.ts#referencesCheckedBeforeRules` | 1 | 23 | | `packages/objectql/src/engine-referential-integrity.ts#storedReferencesCallerReads` | 1 | 23 | +| `packages/objectql/src/engine-rule-message-rendering.ts#readerContext` | 1 | 29g | | `packages/objectql/src/engine-scoped-context.ts#appAuthoredHookApi` | 1 | 1b | | `packages/objectql/src/engine-secret-internal-fields.ts#encryptSecretFields` | 1 | 23e | | `packages/objectql/src/engine-secret-internal-fields.ts#stripSearchCompanionFromRead` | 1 | 27 | diff --git a/packages/lint/src/validate-rule-message-templates.ts b/packages/lint/src/validate-rule-message-templates.ts index 45f1e759a61..5d5b0cd52ff 100644 --- a/packages/lint/src/validate-rule-message-templates.ts +++ b/packages/lint/src/validate-rule-message-templates.ts @@ -5,7 +5,7 @@ * `objects.OBJECT._validations.RULE.message` translations — as the ADR-0032 §3 * `{{ }}` template it is, over the judged record. * - * The roots are the spec's, `VALIDATION_MESSAGE_TEMPLATE_ROOTS` + * The roots are the spec's, `VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS` * (`@objectstack/spec/data`): `record`, the merged record the rule judged, and * `previous`, the stored row before an update. Three steps, the action copy * pass's two (`validate-action-copy-templates.ts`) and one that is the rule @@ -35,7 +35,7 @@ import { validateExpression } from '@objectstack/formula'; import { closedScopeTemplateRefusal } from '@objectstack/spec/automation'; -import { VALIDATION_MESSAGE_TEMPLATE_ROOTS } from '@objectstack/spec/data'; +import { VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS } from '@objectstack/spec/data'; import { nearestName } from './object-graph.js'; import type { ExprIssue } from './validate-expressions.js'; @@ -55,7 +55,7 @@ const HOLE = /\{\{([^}]*)\}\}/g; /** A hole's path — the template engine's `PATH_ONLY_RE`; a hole that fails it is the compile step's to name. */ const HOLE_PATH = /^[\w$.[\]]+$/; -const ROOTS: ReadonlySet = new Set(VALIDATION_MESSAGE_TEMPLATE_ROOTS); +const ROOTS: ReadonlySet = new Set(VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS); /** A path's segments as the engine resolves them (`[i]` read as `.i`). */ function segmentsOf(path: string): string[] { @@ -129,7 +129,7 @@ export function ruleMessageTemplateIssues(text: unknown, site: RuleMessageSite): const refuse = (message: string, source: string): void => { issues.push({ where: site.where, message, source, severity: 'error', ...(site.path ? { path: site.path } : {}) }); }; - const refusal = closedScopeTemplateRefusal(text, { slot: site.slot, roots: VALIDATION_MESSAGE_TEMPLATE_ROOTS }); + const refusal = closedScopeTemplateRefusal(text, { slot: site.slot, roots: VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS }); if (refusal !== undefined) { refuse(refusal, text); return issues; diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index c0abb8e5e91..86f07a674f9 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -81,6 +81,7 @@ import type { } from './engine-top-level.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { InsertManyRowOutcome, ObjectQL as ObjectQLClass } from './engine.js'; +import { attachRuleMessageRendering } from './engine-rule-message-rendering.js'; /** * The `ObjectQL` members the bodies of {@link InsertFacet} read — every one of @@ -1190,6 +1191,9 @@ export class InsertFacet { // Locale + translation hooks for the rejection messages (#3957) — // resolved once for the batch, identical for every row. const msgCtx = this.validationMessageContext(object, opCtx.context); + // [#37909] What a rule message's `{{ }}` holes may show on this write, + // and the currency they format in — computed once, beside the context. + await attachRuleMessageRendering(msgCtx, this.facade, this.logger, object, schemaForValidation, opCtx.context); // [#3407 / #5126] This is the strip site both standing notes on // `insert()` pointed at, so both members of `WriteObservabilityOptions` // discharge here — the same one-per-call choice `update` offers, and by diff --git a/packages/objectql/src/engine-rule-message-rendering.test.ts b/packages/objectql/src/engine-rule-message-rendering.test.ts new file mode 100644 index 00000000000..7b96d9eb2b5 --- /dev/null +++ b/packages/objectql/src/engine-rule-message-rendering.test.ts @@ -0,0 +1,257 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#37909, ruling P3, parameters 5–6] The engine's half of a rule message's + * holes: what they may show on a write (`attachRuleMessageRendering`), asked + * of the registered security service, and the tenant default currency they + * format in. Driven through real `insert` / `update` / `validate` calls on a + * real engine; the security service is a double in the engine's + * security-service source slot, as `ObjectQLPlugin` fills it. The flow path of + * an elevated write (`runAs: 'system'` → `innerRefusal`) is pinned end to end + * in service-automation's `flow-rule-message-reader.integration.test.ts`. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectQL } from './index.js'; + +const OBJ = 'rm_order'; +const SLOT = Symbol.for('objectstack.objectql.securityServiceSource'); + +const MESSAGE = 'Total {{ record.total_price | currency }} · note {{ record.note }} · code {{ record.code }} ' + + '· key {{ record.api_key }} · hash {{ record.hash }}'; + +const body = (message = MESSAGE) => ({ + name: OBJ, + label: 'Order', + fields: { + total_price: { type: 'currency', label: 'Total' }, + note: { type: 'text', label: 'Note' }, + code: { type: 'text', label: 'Code', maskingRule: { strategy: 'partial', pattern: '****' } }, + api_key: { type: 'password', label: 'API key' }, + hash: { type: 'text', label: 'Hash', internal: true }, + status: { type: 'text', label: 'Status' }, + }, + validations: [{ + type: 'script', + name: 'too_low', + message, + condition: 'record.total_price < 100', + }], +}); + +function makeDriver() { + const rows = new Map(); + return { + name: 'com.objectstack.driver.memory.rm', + version: '1.0.0', + async connect() { /* noop */ }, + async disconnect() { /* noop */ }, + async initObjects() { /* noop */ }, + async find() { return [...rows.values()]; }, + async findOne(_o: string, options?: any) { return rows.get(String(options?.where?.id)) ?? null; }, + async count() { return rows.size; }, + async create(_o: string, data: any) { rows.set(String(data.id), data); return data; }, + async update(_o: string, id: any, data: any) { const next = { ...(rows.get(String(id)) ?? {}), ...data }; rows.set(String(id), next); return next; }, + async delete() { return false; }, + } as any; +} + +type Security = { + getReadableFields?: (object: string, context?: unknown) => Promise; + getQueryableFields?: (object: string, context?: unknown) => Promise; +}; + +let engine: ObjectQL; +let warns: string[] = []; + +const ALL_FIELDS = ['total_price', 'note', 'code', 'api_key', 'hash', 'status']; +/** A service that lets the reader read every field, unmasked. */ +const OPEN: Security = { getReadableFields: async () => ALL_FIELDS, getQueryableFields: async () => ALL_FIELDS }; + +async function boot(security?: Security | (() => never), message?: string) { + warns = []; + engine = new ObjectQL({ + logger: { + debug() { /* noop */ }, info() { /* noop */ }, error() { /* noop */ }, + warn(m: string) { if (String(m).startsWith('[validation]')) warns.push(String(m)); }, + }, + } as any); + engine.registerDriver(makeDriver(), true); + await engine.init(); + engine.registry.registerObject(body(message) as any, 'com.objectstack.test.rule-message'); + if (security !== undefined) { + (engine as any)[SLOT] = typeof security === 'function' ? security : () => security; + } +} + +afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } +}); + +const ROW = { id: 'o1', total_price: 42, note: 'rush', code: 'ABC-123', api_key: 'sk_live_1', hash: 'h4sh', status: 'open' }; + +async function refused(write: () => Promise): Promise { + try { + await write(); + } catch (e: any) { + const fields: Array<{ message?: unknown }> = Array.isArray(e?.fields) ? e.fields : []; + if (fields.length > 0) return fields.map((f) => String(f.message)).join(' | '); + throw e; + } + throw new Error('expected the write to be refused'); +} + +const ctx = (over: Record = {}) => ({ context: { locale: 'en-US', currency: 'USD', isSystem: true, ...over } } as any); + +describe('a rule message shows what its reader may read, unmasked (#37909)', () => { + it('⭐ LIT — the readable, unmasked fields show; masked, secret and internal fields render empty', async () => { + await boot({ + getReadableFields: async () => ['total_price', 'note', 'code', 'api_key', 'hash', 'status'], + getQueryableFields: async () => ['total_price', 'note', 'api_key', 'hash', 'status'], + }); + expect(await refused(() => engine.insert(OBJ, { ...ROW }, ctx()))) + .toBe('Total $42.00 · note rush · code · key · hash '); + }); + + it('⭐ LIT — a field the caller cannot read renders empty', async () => { + await boot({ getReadableFields: async () => ['total_price'], getQueryableFields: async () => ['total_price'] }); + expect(await refused(() => engine.insert(OBJ, { ...ROW }, ctx()))) + .toBe('Total $42.00 · note · code · key · hash '); + }); + + it('⭐ LIT — a service with no `getQueryableFields` cannot say who sees a mask: a `maskingRule` field renders empty', async () => { + await boot({ getReadableFields: async () => ['total_price', 'note', 'code'] }); + expect(await refused(() => engine.insert(OBJ, { ...ROW }, ctx()))) + .toBe('Total $42.00 · note rush · code · key · hash '); + }); + + it('⭐ LIT — a mask lifted for this caller (the field is queryable) shows the value', async () => { + await boot({ + getReadableFields: async () => ['total_price', 'note', 'code'], + getQueryableFields: async () => ['total_price', 'note', 'code'], + }); + expect(await refused(() => engine.insert(OBJ, { ...ROW }, ctx()))) + .toBe('Total $42.00 · note rush · code ABC-123 · key · hash '); + }); + + it('⭐ LIT — a service that cannot be asked, answers nothing, or throws: every hole empty, the write still refused, the cause logged once', async () => { + const empty = 'Total · note · code · key · hash '; + const cases: Array<[Security | (() => never), RegExp]> = [ + [{ getReadableFields: async () => undefined }, /getReadableFields\(\) answered no field list/], + [{ getReadableFields: async () => { throw new Error('down'); } }, /getReadableFields\(\) threw \(down\)/], + [{ getReadableFields: async () => ['total_price', 'note'], getQueryableFields: async () => { throw new Error('down'); } }, + /getQueryableFields\(\) threw \(down\)/], + [(() => { throw new Error('no security service'); }) as () => never, /no security service is registered/], + [{}, /has no getReadableFields\(\)/], + ]; + for (const [security, cause] of cases) { + await boot(security); + expect(await refused(() => engine.insert(OBJ, { ...ROW }, ctx()))).toBe(empty); + const lines = warns.filter((w) => w.includes('rule message holes render empty on this write')); + expect(lines).toHaveLength(1); + expect(lines[0]).toMatch(cause); + await engine.destroy(); + } + }); + + it('⭐ LIT — with no security service registered, every hole renders empty (fail closed), and the log says why', async () => { + await boot(); + expect(await refused(() => engine.insert(OBJ, { ...ROW }, ctx()))) + .toBe('Total · note · code · key · hash '); + expect(warns).toEqual(['[validation] rule message holes render empty on this write: no security service is registered.']); + }); + + it('⭐ LIT — a hole empty only for this reader is never reported', async () => { + await boot({ getReadableFields: async () => ['total_price'], getQueryableFields: async () => ['total_price'] }); + await refused(() => engine.insert(OBJ, { ...ROW }, ctx())); + expect(warns).toEqual([]); + }); + + it('⭐ LIT — a stored hole no reader could see filled is named with its rule, once per write', async () => { + await boot(OPEN, 'Owner {{ record.owner }}, account {{ record.account.name }}, from {{ from }}, row {{ record }} · {{ record.note }}'); + expect(await refused(() => engine.insert(OBJ, [{ ...ROW, id: 'a' }, { ...ROW, id: 'b' }], ctx()))) + .toContain('Owner , account , from , row · rush'); + expect(warns).toEqual([ + "[validation] the message of validation rule 'too_low' on object 'rm_order': the hole {{ record.owner }} names `owner`, which the object does not declare, so it renders empty for every reader. Rewrite it; `objectstack validate` names it.", + "[validation] the message of validation rule 'too_low' on object 'rm_order': the hole {{ record.account.name }} reads through a field; a hole reads one of the object's own fields, one segment deep, so it renders empty for every reader. Rewrite it; `objectstack validate` names it.", + "[validation] the message of validation rule 'too_low' on object 'rm_order': the hole {{ from }} reads `from`, which is not a root a rule message reads (`record`, `previous`), so it renders empty for every reader. Rewrite it; `objectstack validate` names it.", + "[validation] the message of validation rule 'too_low' on object 'rm_order': the hole {{ record }} names the root `record` alone, not one of its fields, so it renders empty for every reader. Rewrite it; `objectstack validate` names it.", + ]); + }); +}); + +describe('an elevated write made for a person shows what THAT person may read (#37909, L2 M1)', () => { + /** A service that answers the system every field, and the rep two, with `note` masked for them. */ + function personal(asked: unknown[]): Security { + const answer = (masked: boolean) => async (_o: string, c?: any) => { + asked.push(c); + if (c?.isSystem) return ALL_FIELDS; + if (c?.userId === 'u_rep' && Array.isArray(c?.permissions) && c.permissions.includes('rep')) { + return masked ? ['total_price', 'note'] : ['total_price']; + } + return []; + }; + return { getReadableFields: answer(true), getQueryableFields: answer(false) }; + } + + it('⭐ LIT — `{ ...caller, isSystem: true }` (an action body): asked for the caller with their own sets, never as the system', async () => { + const asked: any[] = []; + await boot(personal(asked)); + expect(await refused(() => engine.insert(OBJ, { ...ROW }, ctx({ userId: 'u_rep', permissions: ['rep'], positions: [] })))) + .toBe('Total $42.00 · note · code · key · hash '); + expect(asked.length).toBeGreaterThan(0); + for (const c of asked) { + expect(c.isSystem).toBe(false); + expect(c.userId).toBe('u_rep'); + expect(c.permissions).toEqual(['rep']); + } + }); + + it('⭐ LIT — `{ isSystem: true, userId }` with no sets (a system flow, the approvals mirror) whose grants cannot be read: every hole empty, the cause logged', async () => { + const asked: any[] = []; + await boot(personal(asked)); + // A bare engine registers no permission store: the person's grants are unreadable. + const message = await refused(() => engine.insert(OBJ, { ...ROW }, ctx({ userId: 'u_rep' }))); + expect(message).toBe('Total · note · code · key · hash '); + // Never asked as the system; not asked at all, since the reader is unknown. + expect(asked).toEqual([]); + expect(warns).toHaveLength(1); + expect(warns[0]).toMatch(/^\[validation\] rule message holes render empty on this write: the grants of the person this elevated write was made for could not be read \(.*`sys_member`/); + }); + + it('⭐ LIT — CONTROL: a user-less system write keeps the system\'s answer', async () => { + const asked: any[] = []; + await boot(personal(asked)); + expect(await refused(() => engine.insert(OBJ, { ...ROW }, ctx()))) + .toBe('Total $42.00 · note rush · code ABC-123 · key · hash '); + expect(asked.every((c) => c?.isSystem === true)).toBe(true); + }); + + it('⭐ LIT — CONTROL: the same person\'s own (unelevated) write reads the same answer', async () => { + await boot(personal([])); + expect(await refused(() => engine.insert(OBJ, { ...ROW }, ctx({ isSystem: false, userId: 'u_rep', permissions: ['rep'] })))) + .toBe('Total $42.00 · note · code · key · hash '); + }); +}); + +describe('the currency and the paths (#37909)', () => { + it('⭐ LIT — `| currency` formats in the write\'s tenant default currency, in the refusal\'s locale', async () => { + await boot(OPEN); + expect(await refused(() => engine.insert(OBJ, { ...ROW }, ctx({ currency: 'EUR', locale: 'de-DE' })))) + .toMatch(/^Total 42,00\s€ · note rush/u); + }); + + it('⭐ LIT — an update fills `previous` with the stored row', async () => { + await boot(OPEN, 'Total was {{ previous.total_price }}, now {{ record.total_price }} ({{ record.status }}).'); + await engine.insert(OBJ, { ...ROW, total_price: 500 }, ctx()); + expect(await refused(() => engine.update(OBJ, { total_price: 10 }, { where: { id: 'o1' }, ...ctx() } as any))) + .toBe('Total was 500, now 10 (open).'); + }); + + it('⭐ LIT — a dry run (`validate`) refuses with the same filled sentence', async () => { + await boot(OPEN, 'Total {{ record.total_price | currency }} is too low.'); + const result: any = await engine.validate(OBJ, { ...ROW }, ctx()); + const messages = JSON.stringify(result); + expect(messages).toContain('Total $42.00 is too low.'); + }); +}); diff --git a/packages/objectql/src/engine-rule-message-rendering.ts b/packages/objectql/src/engine-rule-message-rendering.ts new file mode 100644 index 00000000000..4b2426561f2 --- /dev/null +++ b/packages/objectql/src/engine-rule-message-rendering.ts @@ -0,0 +1,260 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#37909, ruling P3, parameters 5–6] What a validation rule message's + * `{{ }}` holes may show on one write, and what they format with — + * `ValidationMessageContext.rendering`, which `rule-message-render.ts` reads. + * + * Computed once per write, beside the message context it rides + * (`ObjectQL#validationMessageContext`), on the insert, update and dry-run + * (`validate()`) paths, and only for an object whose rule messages — a nested + * `conditional` branch's included — or whose translations of them carry a + * `{{`: every other write asks the security service nothing more than it did. + * + * ## The showable fields (parameter 6, the human floor) + * + * A hole shows a field's value only when the person the refusal is worded for + * may read that field UNMASKED. The answer is the registered security + * service's (`ISecurityService`, through the engine's security-service source + * slot, `SECURITY_SERVICE_SOURCE_SLOT`): + * + * - `getReadableFields` — the fields that person may read. A masked field is + * in it: it is served, its value replaced by the mask. + * - `getQueryableFields` — the readable fields less the ones masked for that + * person (the security contract: "the difference between the two is + * exactly the fields this caller sees masked"). Where the service does not + * implement it, or answers `undefined`, every field that declares a + * `maskingRule` counts as masked, whoever reads: the fallback the contract + * prescribes for it, and never wider than the read. + * + * Every credential field the engine masks on a read (`secret`, and `password` + * off a `better-auth` object) and every `internal` field it omits is never + * showable, whatever the service answers. + * + * ## Whose read: the person an elevated write was made for + * + * Both projections are asked under the write's own context, except on an + * ELEVATED write (`isSystem`) that names a person (`userId`): a `runAs: + * 'system'` flow started by someone, an action body, the approvals mirror. + * Elevation lifts the write's own gates, and the security contract answers a + * system context with every field; but the refusal is carried back to that + * person (a flow's `innerRefusal`, an action's error), so both projections + * are asked for THEM: the same context with `isSystem` off, carrying the + * positions and permission sets it carries, or — where it carries none — the + * person's own grants, resolved through the one resolver the platform seeds a + * user's grants with (`resolveUserAuthzGrants`, `@objectstack/core`), as a + * `runAs: 'user'` hook fired by the same write is. Where those grants cannot + * be read, no field is showable. A user-less system write (a schedule, a + * platform sweep) has no reader but the server log, and keeps the system's + * answer. + * + * ## When the field security cannot be asked: every hole renders empty + * + * ⛔ Fail closed. No security service registered (an engine or a kernel + * composed without one: the kernel throws on a name nothing registered), one + * registered that cannot be asked (not a function in the slot, no + * `getReadableFields`), one that answers nothing or throws, and the grants of + * the person an elevated write was made for unreadable: no field is showable, + * every hole renders empty, and the cause is written once to the server log + * (`RuleMessageRendering.unanswered`) when a hole renders empty for it. The + * verdict is the same either way. + * + * ## The currency and the zone + * + * The tenant default currency is the write's `ExecutionContext.currency` (the + * organization's `localization.currency`, resolved with the request's context) + * and the reference timezone its `timezone`: the channels a currency field and + * a `datetime` hole already read. ⛔ Neither is guessed. + */ + +import { resolveUserAuthzGrants } from '@objectstack/core'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { SECURITY_SERVICE_SOURCE_SLOT } from './engine-top-level.js'; +import { collectInternalReadFields, collectMaskedReadFields } from './secret-fields.js'; +import type { ValidationMessageContext } from './validation/record-validator.js'; +import { carriesTemplateHole, type RuleMessageRendering } from './validation/rule-message-render.js'; + +type AnyRec = Record; + +const isRec = (v: unknown): v is AnyRec => typeof v === 'object' && v !== null && !Array.isArray(v); + +/** The members of a security service this module asks. */ +interface RuleMessageFieldSecurity { + getReadableFields?: (object: string, context?: unknown) => Promise; + getQueryableFields?: (object: string, context?: unknown) => Promise; +} + +/** Whether a rule — or a `conditional` branch under it, at any depth — carries a hole in its message. */ +function ruleCarriesHole(rule: unknown): boolean { + if (!isRec(rule)) return false; + if (carriesTemplateHole(rule.message)) return true; + return ruleCarriesHole(rule.then) || ruleCarriesHole(rule.otherwise); +} + +/** Whether any translation the write's refusal may pick of a rule message of `objectName` carries a hole. */ +function translationCarriesHole(objectName: string, messages: ValidationMessageContext): boolean { + let bundle: unknown; + try { + bundle = messages.labelTranslation?.()?.bundle; + } catch { + return false; + } + if (!isRec(bundle)) return false; + for (const data of Object.values(bundle)) { + const node = isRec(data) && isRec(data.objects) ? data.objects[objectName] : undefined; + if (!isRec(node) || !isRec(node._validations)) continue; + for (const entry of Object.values(node._validations)) { + if (isRec(entry) && carriesTemplateHole(entry.message)) return true; + } + } + return false; +} + +/** Whether a write on `schema` may render a rule message carrying a hole. */ +export function rendersRuleMessageHoles(schema: unknown, messages: ValidationMessageContext): boolean { + const validations = isRec(schema) && Array.isArray(schema.validations) ? schema.validations : []; + if (validations.length === 0) return false; + if (validations.some(ruleCarriesHole)) return true; + return typeof messages.objectName === 'string' && translationCarriesHole(messages.objectName, messages); +} + +/** The security service in the engine's source slot, or why it cannot be asked. */ +function fieldSecurityOf(facade: unknown): { svc: RuleMessageFieldSecurity } | { unanswered: string } { + const source = facade !== null && typeof facade === 'object' + ? (facade as Record)[SECURITY_SERVICE_SOURCE_SLOT] + : undefined; + if (source === undefined || source === null) return { unanswered: 'no security service is registered' }; + if (typeof source !== 'function') return { unanswered: 'the security-service source slot holds no function' }; + let svc: unknown; + try { + svc = source(); + } catch { + // The in-repo kernels throw on a name nothing registered. + return { unanswered: 'no security service is registered (resolving "security" threw)' }; + } + if (svc === undefined || svc === null) return { unanswered: 'no security service is registered' }; + const candidate = svc as RuleMessageFieldSecurity; + return typeof candidate.getReadableFields === 'function' + ? { svc: candidate } + : { unanswered: 'the registered security service has no getReadableFields()' }; +} + +/** The fields declaring a `maskingRule` — masked for a reader the service cannot say otherwise of. */ +function maskingRuleFields(fields: AnyRec): Set { + const out = new Set(); + for (const [name, def] of Object.entries(fields)) { + if (isRec(def) && def.maskingRule !== undefined && def.maskingRule !== null) out.add(name); + } + return out; +} + +const reasonOf = (error: unknown): string => (error instanceof Error ? error.message : String(error)); + +/** + * The context both projections are asked under (see the module header, "Whose + * read"): the write's own, or — on an elevated write that names a person — + * that person's, or why it cannot be had. + */ +async function readerContext( + facade: unknown, + context: ExecutionContext | undefined, +): Promise<{ reader: ExecutionContext | undefined } | { unanswered: string }> { + if (context?.isSystem !== true) return { reader: context }; + const userId = context.userId; + if (typeof userId !== 'string' || userId === '') return { reader: context }; + const person = { ...context, isSystem: false } as ExecutionContext & AnyRec; + if (Array.isArray(person.permissions)) return { reader: person }; + try { + const grants = await resolveUserAuthzGrants(facade, userId, context.tenantId ? { tenantId: context.tenantId } : {}); + return { + reader: { + ...person, + positions: grants.positions, + permissions: grants.permissions, + ...(grants.permissionSetAddresses ? { permissionSetAddresses: grants.permissionSetAddresses } : {}), + ...(grants.principalKind ? { principalKind: grants.principalKind, systemPermissions: [] } : {}), + ...(Array.isArray(person.accessible_org_ids) ? {} : { accessible_org_ids: grants.accessible_org_ids }), + } as ExecutionContext, + }; + } catch (error) { + return { unanswered: `the grants of the person this elevated write was made for could not be read (${reasonOf(error)})` }; + } +} + +/** The fields a hole may show on this write, or why none is (see the module header). */ +async function showableFields( + facade: unknown, + objectName: string, + schema: unknown, + context: ExecutionContext | undefined, +): Promise<{ showable: Set; unanswered?: string }> { + const fields = isRec(schema) && isRec(schema.fields) ? schema.fields : {}; + const never = new Set([ + ...collectMaskedReadFields(schema as never), + ...collectInternalReadFields(schema as never), + ]); + const masked = maskingRuleFields(fields); + const declared = Object.keys(fields).filter((name) => !never.has(name)); + const none = (unanswered: string) => ({ showable: new Set(), unanswered }); + const security = fieldSecurityOf(facade); + if ('unanswered' in security) return none(security.unanswered); + const reader = await readerContext(facade, context); + if ('unanswered' in reader) return none(reader.unanswered); + let readable: string[] | undefined; + try { + readable = await security.svc.getReadableFields!(objectName, reader.reader); + } catch (error) { + return none(`the security service's getReadableFields() threw (${reasonOf(error)})`); + } + if (!Array.isArray(readable)) return none('the security service\'s getReadableFields() answered no field list'); + let unmasked: Set | undefined; + if (typeof security.svc.getQueryableFields === 'function') { + try { + const queryable = await security.svc.getQueryableFields(objectName, reader.reader); + if (Array.isArray(queryable)) unmasked = new Set(queryable); + } catch (error) { + return none(`the security service's getQueryableFields() threw (${reasonOf(error)})`); + } + } + const read = new Set(readable); + return { showable: new Set(declared.filter((name) => read.has(name) && (unmasked ? unmasked.has(name) : !masked.has(name)))) }; +} + +/** An ISO 4217 code in three capitals, or `undefined`. */ +function currencyCode(value: unknown): string | undefined { + return typeof value === 'string' && /^[A-Z]{3}$/.test(value) ? value : undefined; +} + +/** + * Hand `messages` what this write's rule messages render with — + * {@link RuleMessageRendering} on `messages.rendering` — when the object's rule + * messages or their translations carry a hole; otherwise leave it as it is. + */ +export async function attachRuleMessageRendering( + messages: ValidationMessageContext, + facade: unknown, + logger: { warn?: (message: string, meta?: Record) => void } | undefined, + objectName: string, + schema: unknown, + context: ExecutionContext | undefined, +): Promise { + if (!rendersRuleMessageHoles(schema, messages)) return; + const { showable, unanswered } = await showableFields(facade, objectName, schema, context); + const declared = new Set(isRec(schema) && isRec(schema.fields) ? Object.keys(schema.fields) : []); + const currency = currencyCode((context as { currency?: unknown } | undefined)?.currency); + const timezone = (context as { timezone?: unknown } | undefined)?.timezone; + // Each distinct line once per write: a bulk refusal fills the same holes on every row. + const written = new Set(); + messages.rendering = { + showable, + declared, + ...(unanswered !== undefined ? { unanswered } : {}), + ...(currency !== undefined ? { currency } : {}), + ...(typeof timezone === 'string' && timezone !== '' ? { timezone } : {}), + warn: (message) => { + if (written.has(message)) return; + written.add(message); + logger?.warn?.(`[validation] ${message}`, { object: objectName }); + }, + } satisfies RuleMessageRendering; +} diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index a3e6432fb8a..ba446ea29e8 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -89,6 +89,7 @@ import type { OperationContext, ReferentialClearOption, StoredExpressionServing import { REFERENTIAL_CLEAR_OPTION } from './engine-top-level.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { ObjectQL as ObjectQLClass } from './engine.js'; +import { attachRuleMessageRendering } from './engine-rule-message-rendering.js'; /** * [#34746] The columns the platform stamps on every update, and nothing a @@ -1251,6 +1252,8 @@ export class UpdateFacet { const mediaValueShapeStrict = await this.mediaValueShapeStrictFor(updateSchema); const valueShapeStrict = await this.valueShapeStrictFor(updateSchema); const updateMsgCtx = this.validationMessageContext(object, opCtx.context); + // [#37909] See the insert path: what a rule message's holes may show. + await attachRuleMessageRendering(updateMsgCtx, this.facade, this.logger, object, updateSchema, opCtx.context); // [#4769] See the insert path — an update admits values on the same // terms, so it owes the same counterexample. const onAdmittedValueShapeViolation = this.admittedViolationSink(object); diff --git a/packages/objectql/src/engine-validate.ts b/packages/objectql/src/engine-validate.ts index 08351b0a809..0fe7c292709 100644 --- a/packages/objectql/src/engine-validate.ts +++ b/packages/objectql/src/engine-validate.ts @@ -70,6 +70,7 @@ import { } from './engine.js'; import type { ObjectQL, WriteWallRowVerdict } from './engine.js'; import { ObjectQLStatics } from './engine.js'; +import { attachRuleMessageRendering } from './engine-rule-message-rendering.js'; /** * The `ObjectQL` members the functions below read — every one of them, and no @@ -369,6 +370,8 @@ export async function validate( const mediaValueShapeStrict = await this.mediaValueShapeStrictFor(schemaForValidation); const valueShapeStrict = await this.valueShapeStrictFor(schemaForValidation); const messages = this.validationMessageContext(object, options?.context); + // [#37909] What a rule message's holes may show, as the write computes it. + await attachRuleMessageRendering(messages, this.facade, this.logger, object, schemaForValidation, options?.context); const currentUser = this.buildEvalUser(options?.context); const skipStateMachine = shouldSkipStateMachine(options?.context); diff --git a/packages/objectql/src/validation/record-validator.ts b/packages/objectql/src/validation/record-validator.ts index 9b051ea867d..d9adf519685 100644 --- a/packages/objectql/src/validation/record-validator.ts +++ b/packages/objectql/src/validation/record-validator.ts @@ -106,6 +106,7 @@ * the UI can highlight the specific input. */ +import type { RuleMessageRendering } from './rule-message-render.js'; import { isMultiValueField as specIsMultiValueField, valueSchemaFor, @@ -447,8 +448,11 @@ export interface ValidationMessageContext { * language: `i18n.sourceLocale`, else `defaultLocale`). So a request in the * authored language reads the label as written, never the `defaultLocale` * row `t()` would fall to, and a refusal names a field with the word the - * form showed. A thunk, asked only when a refusal names something: building - * the bundle reads every locale the service holds. + * form showed. A thunk, asked when a refusal names something, and [#37909] + * once per write to an object that has a rule and no `{{` in an authored + * message, to learn whether a translation of one carries a hole + * (`rendersRuleMessageHoles`): building the bundle reads every locale the + * service holds. * * Absent, or answering `undefined` (no i18n service, no locale): the * declared labels. @@ -471,6 +475,15 @@ export interface ValidationMessageContext { * diverge from, and the catalog applies, as on `/meta`. */ packagedRule?: (ruleName: string) => unknown; + /** + * [#37909, ruling P3] What an authored rule message's `{{ }}` holes may show + * and format with: the fields the caller may read unmasked, the tenant + * default currency and the reference timezone, computed by the engine once + * per write (`engine-rule-message-rendering.ts`), only for an object whose + * rule messages or their translations carry a hole. Absent, every hole + * renders empty. + */ + rendering?: RuleMessageRendering; } /** diff --git a/packages/objectql/src/validation/rule-message-render.test.ts b/packages/objectql/src/validation/rule-message-render.test.ts new file mode 100644 index 00000000000..e5a7a7c7e42 --- /dev/null +++ b/packages/objectql/src/validation/rule-message-render.test.ts @@ -0,0 +1,287 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#37909, ruling P3, parameters 5–8] A validation rule's message is a `{{ }}` + * template over the judged record: the refusal of a write fills its holes. + * Driven through `evaluateValidationRules`, the evaluator every write path + * runs, with the `rendering` the engine computes per write handed in by hand + * (`engine-rule-message-rendering.test.ts` drives the engine's own). + */ + +import { describe, expect, it } from 'vitest'; +import '@objectstack/spec'; +import '@objectstack/formula'; + +import { ValidationError, type ValidationMessageContext } from './record-validator.js'; +import { evaluateValidationRules } from './rule-validator.js'; +import type { RuleMessageRendering } from './rule-message-render.js'; + +const FIELDS = { + total_price: { type: 'currency', label: 'Total' }, + received_amount: { type: 'currency', label: 'Received' }, + status: { type: 'select', label: 'Status', options: [{ value: 'draft', label: 'Draft' }, { value: 'confirmed', label: 'Confirmed' }] }, + account: { type: 'lookup', reference: 'crm_account', label: 'Account' }, + ssn: { type: 'text', label: 'SSN' }, + due: { type: 'date', label: 'Due' }, +}; + +const ALL = new Set(Object.keys(FIELDS)); + +const order = (validations: unknown[]) => ({ name: 'sales_order', fields: FIELDS, validations }); + +const below = (message: string, over: Record = {}) => ({ + name: 'total_below_received', + type: 'script', + condition: 'record.total_price < record.received_amount', + message, + ...over, +}); + +const rendering = (over: Partial = {}): RuleMessageRendering => ({ + showable: ALL, + currency: 'USD', + ...over, +}); + +/** The messages the refusal of one write carries. */ +function refusal( + schema: unknown, + data: Record, + options: { mode?: 'insert' | 'update'; previous?: Record; messages?: ValidationMessageContext; related?: unknown } = {}, +): string[] { + try { + evaluateValidationRules(schema as never, data, options.mode ?? 'insert', { + ...(options.previous ? { previous: options.previous } : {}), + ...(options.messages ? { messages: options.messages } : {}), + ...(options.related ? { related: options.related as never } : {}), + }); + } catch (error) { + if (error instanceof ValidationError) return error.fields.map((f) => String(f.message)); + throw error; + } + throw new Error('expected the write to be refused'); +} + +const row = { total_price: 1200, received_amount: 1500, status: 'confirmed', account: 'acc_1', ssn: '123-45-6789' }; + +describe('a rule message renders the judged record (#37909)', () => { + it('⭐ LIT — holes over `record` render the merged record, through the whitelisted formatters', () => { + const messages = { locale: 'en-US', rendering: rendering() }; + expect(refusal(order([below( + 'Total {{ record.total_price | currency }} is below what was received ({{ record.received_amount | currency }}).', + )]), row, { messages })).toEqual(['Total $1,200.00 is below what was received ($1,500.00).']); + expect(refusal(order([below('Total {{ record.total_price | number }} for {{ record.status }}.')]), row, { messages })) + .toEqual(['Total 1,200 for confirmed.']); + expect(refusal(order([below('Total {{ record.total_price | currency:EUR }}.')]), row, { messages })) + .toEqual(['Total €1,200.00.']); + }); + + it('⭐ LIT — the formatters render in the refusal\'s locale, and `currency` in the tenant default', () => { + const messages = { locale: 'zh-CN', rendering: rendering({ currency: 'CNY' }) }; + expect(refusal(order([below('总价 {{ record.total_price | currency }}')]), row, { messages })) + .toEqual(['总价 ¥1,200.00']); + }); + + it('⭐ LIT — on an update, `previous` is the stored row and `record` the merged one', () => { + const rule = { + name: 'no_reopen', + type: 'script', + condition: "previous.status == 'confirmed' && record.status == 'draft'", + message: 'Status cannot move from {{ previous.status }} to {{ record.status }} (total {{ record.total_price }}).', + }; + expect(refusal(order([rule]), { status: 'draft' }, { + mode: 'update', + previous: { id: 'o1', ...row }, + messages: { locale: 'en-US', rendering: rendering() }, + })).toEqual(['Status cannot move from confirmed to draft (total 1200).']); + }); + + it('DARK — on an insert `previous` is null, so a `previous.FIELD` hole renders empty', () => { + expect(refusal(order([below('Was {{ previous.total_price }}, now {{ record.total_price }}.', { events: ['insert'] })]), row, { + messages: { locale: 'en-US', rendering: rendering() }, + })).toEqual(['Was , now 1200.']); + }); + + it('DARK — a message carrying no hole is returned as written, a single brace included', () => { + const messages = { locale: 'en-US', rendering: rendering() }; + expect(refusal(order([below('Support Config must be { tier: standard }.')]), row, { messages })) + .toEqual(['Support Config must be { tier: standard }.']); + expect(refusal(order([below('Total too low.')]), row)).toEqual(['Total too low.']); + }); +}); + +describe('a hole shows only what the caller may read, unmasked (#37909, parameter 6)', () => { + const text = 'Total {{ record.total_price }} · SSN {{ record.ssn }} · was {{ previous.ssn }}.'; + + it('⭐ LIT — a field outside `showable` renders empty, under both roots, and is never reported', () => { + const warnings: string[] = []; + const messages = { + locale: 'en-US', + rendering: rendering({ showable: new Set(['total_price', 'received_amount']), declared: ALL, warn: (w) => warnings.push(w) }), + }; + expect(refusal(order([below(text)]), { total_price: 1200 }, { + mode: 'update', + previous: { id: 'o1', ...row }, + messages, + })).toEqual(['Total 1200 · SSN · was .']); + expect(warnings).toEqual([]); + }); + + it('⭐ LIT — the scope holds showable values only: a hole the blanking builds reads nothing (L2 N5)', () => { + // `{{ record.status }}` is blanked first, which leaves `{{ record.ssn }}}`: + // a hole over a withheld field the engine then evaluates (its trailing + // brace with it). The scope has no `ssn`. + const messages = { locale: 'en-US', rendering: rendering({ showable: new Set(['total_price']) }) }; + const [message] = refusal(order([below('SSN {{ record.ssn }{{ record.status }}} end')]), row, { messages }); + expect(message).not.toContain('123-45-6789'); + expect(message).toBe('SSN end'); + }); + + it('⭐ LIT — when the field security could not be asked, every hole is empty and the cause is reported', () => { + const warnings: string[] = []; + const messages = { + locale: 'en-US', + rendering: rendering({ showable: new Set(), unanswered: 'no security service is registered', warn: (w) => warnings.push(w) }), + }; + expect(refusal(order([below(text)]), row, { messages })).toEqual(['Total · SSN · was .']); + expect(warnings[0]).toBe('rule message holes render empty on this write: no security service is registered.'); + }); + + it('⭐ LIT — with no rendering handed in, every hole renders empty', () => { + expect(refusal(order([below(text)]), row, { messages: { locale: 'en-US' } })).toEqual(['Total · SSN · was .']); + expect(refusal(order([below(text)]), row)).toEqual(['Total · SSN · was .']); + }); + + it('⭐ LIT — a read through a field, a bare root, another root and an undeclared field render empty, each named with its rule (L2 S2)', () => { + const warnings: string[] = []; + const messages = { + locale: 'en-US', + rendering: rendering({ showable: new Set([...ALL, 'nope']), declared: ALL, warn: (w) => warnings.push(w) }), + objectName: 'sales_order', + }; + expect(refusal(order([below( + '[{{ record.account.name }}][{{ record }}][{{ current_user.id }}][{{ amount }}][{{ record.nope }}][{{ record.account }}]', + )]), row, { messages })).toEqual(['[][][][][][acc_1]']); + const subject = "the message of validation rule 'total_below_received' on object 'sales_order': the hole"; + expect(warnings).toEqual([ + `${subject} {{ record.account.name }} reads through a field; a hole reads one of the object's own fields, one segment deep, so it renders empty for every reader. Rewrite it; \`objectstack validate\` names it.`, + `${subject} {{ record }} names the root \`record\` alone, not one of its fields, so it renders empty for every reader. Rewrite it; \`objectstack validate\` names it.`, + `${subject} {{ current_user.id }} reads \`current_user\`, which is not a root a rule message reads (\`record\`, \`previous\`), so it renders empty for every reader. Rewrite it; \`objectstack validate\` names it.`, + `${subject} {{ amount }} reads \`amount\`, which is not a root a rule message reads (\`record\`, \`previous\`), so it renders empty for every reader. Rewrite it; \`objectstack validate\` names it.`, + `${subject} {{ record.nope }} names \`nope\`, which the object does not declare, so it renders empty for every reader. Rewrite it; \`objectstack validate\` names it.`, + ]); + }); + + it('⭐ LIT — a reference field renders its stored id, never the related row a predicate read through it', () => { + const rule = { + name: 'partner_cap', + type: 'script', + condition: "record.account.type == 'partner' && record.total_price > 1000", + message: 'Account {{ record.account }} is a partner; total {{ record.total_price }}.', + }; + expect(refusal(order([rule]), row, { + messages: { locale: 'en-US', rendering: rendering() }, + related: { account: { object: 'crm_account', row: { id: 'acc_1', type: 'partner', credit_card: '4111' } } }, + })).toEqual(['Account acc_1 is a partner; total 1200.']); + }); + + it('⭐ LIT — no record value enters the violation\'s machine fields', () => { + try { + evaluateValidationRules(order([below('Total {{ record.total_price }} · {{ record.ssn }}')]) as never, row, 'insert', { + messages: { locale: 'en-US', rendering: rendering() }, + }); + } catch (error) { + const [violation] = (error as ValidationError).fields; + expect(violation!.message).toBe('Total 1200 · 123-45-6789'); + const { message: _message, ...machine } = violation as unknown as Record; + expect(JSON.stringify(machine)).not.toContain('1200'); + expect(JSON.stringify(machine)).not.toContain('123-45-6789'); + return; + } + throw new Error('expected the write to be refused'); + }); +}); + +describe('a nested branch, the field-scoped rules and the state machine fill their messages too (#37909)', () => { + const messages = { locale: 'en-US', rendering: rendering() }; + + it('⭐ LIT — a `conditional` branch\'s message', () => { + const rule = { + name: 'confirm_checks', + type: 'conditional', + when: "record.status == 'confirmed'", + message: 'Confirmation checks.', + then: below('Confirmed order total {{ record.total_price }} is below {{ record.received_amount }}.'), + }; + expect(refusal(order([rule]), row, { messages })).toEqual(['Confirmed order total 1200 is below 1500.']); + }); + + it('⭐ LIT — a `format` rule\'s message', () => { + const rule = { name: 'ssn_shape', type: 'format', field: 'ssn', regex: '^\\d{9}$', message: 'SSN for {{ record.status }} order must be nine digits.' }; + expect(refusal(order([rule]), row, { messages })).toEqual(['SSN for confirmed order must be nine digits.']); + }); + + it('⭐ LIT — a `state_machine` rule\'s message', () => { + const rule = { + name: 'status_flow', + type: 'state_machine', + field: 'status', + transitions: { confirmed: [] }, + message: 'Status {{ previous.status }} cannot become {{ record.status }}.', + }; + expect(refusal(order([rule]), { status: 'draft' }, { mode: 'update', previous: { id: 'o1', ...row }, messages })) + .toEqual(['Status confirmed cannot become draft.']); + }); +}); + +describe('translation first, then filled (#37909, parameter 7)', () => { + const bundle = (message: string) => ({ + 'zh-CN': { objects: { sales_order: { _validations: { total_below_received: { message } } } } }, + }); + const context = (message: string, warnings: string[]): ValidationMessageContext => ({ + objectName: 'sales_order', + locale: 'zh-CN', + labelTranslation: () => ({ bundle: bundle(message) as never, options: { locale: 'zh-CN' } }), + rendering: rendering({ currency: 'CNY', warn: (w) => warnings.push(w) }), + }); + + it('⭐ LIT — the translated template is picked, then filled', () => { + const warnings: string[] = []; + expect(refusal(order([below('Total {{ record.total_price | currency }} is too low.')]), row, { + messages: context('总价 {{ record.total_price | currency }} 低于已收 {{ record.received_amount | currency }}。', warnings), + })).toEqual(['总价 ¥1,200.00 低于已收 ¥1,500.00。']); + expect(warnings).toEqual([]); + }); + + it('⭐ LIT — a translation that does not render falls back to the authored message, filled, and is named', () => { + const warnings: string[] = []; + expect(refusal(order([below('Total {{ record.total_price | currency }} is too low.')]), row, { + messages: context('总价 {{ record.total_price + 1 }} 过低。', warnings), + })).toEqual(['Total ¥1,200.00 is too low.']); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain("zh-CN translation of validation rule 'total_below_received' on object 'sales_order'"); + expect(warnings[0]).toContain('objects.sales_order._validations.total_below_received.message'); + }); + + it('DARK — an authored message stored before the doors judged it is shown as written, and named', () => { + const warnings: string[] = []; + expect(refusal(order([below('Total {{ record.total_price | shout }} is too low.')]), row, { + messages: { locale: 'en-US', rendering: rendering({ warn: (w) => warnings.push(w) }) }, + })).toEqual(['Total {{ record.total_price | shout }} is too low.']); + expect(warnings[0]).toContain("the message of validation rule 'total_below_received'"); + expect(warnings[0]).toContain('shown as written'); + }); +}); + +describe('a `currency` hole with no argument and no tenant default (#37909, parameter 8 — the fork, provisional)', () => { + it('⭐ LIT — the hole renders empty, the rest of the sentence renders, and the setting is named', () => { + const warnings: string[] = []; + expect(refusal(order([below('Total {{ record.total_price | currency }} ({{ record.total_price | currency:EUR }}).')]), row, { + messages: { locale: 'en-US', rendering: rendering({ currency: undefined, warn: (w) => warnings.push(w) }) }, + })).toEqual(['Total (€1,200.00).']); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain("the message of validation rule 'total_below_received'"); + expect(warnings[0]).toContain('the organization has none set, or the write carried none'); + expect(warnings[0]).toContain('localization.currency'); + }); +}); diff --git a/packages/objectql/src/validation/rule-message-render.ts b/packages/objectql/src/validation/rule-message-render.ts new file mode 100644 index 00000000000..3419238338a --- /dev/null +++ b/packages/objectql/src/validation/rule-message-render.ts @@ -0,0 +1,251 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#37909, ruling P3, parameters 5–8] Fill the `{{ }}` holes of a validation + * rule's message — or of the translation of it a refusal shows — with the + * judged record's values. + * + * The message is an ADR-0032 §3 template over two roots, + * `VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS` (`@objectstack/spec/data`): + * `record`, the merged record the rule judged, and `previous`, the stored row + * before an update (`null` on an insert, so a `previous.FIELD` hole renders + * empty there). The doors (`objectstack validate` / `compile`, the publish + * gate) judge every message and every translation as that template; this + * module renders it, through the formula template engine (`templateEngine`) — + * ⛔ never a second engine — with the formatters that engine whitelists and + * nothing implicit: a value renders as the engine renders it (`null` and an + * absent value as nothing), and a formatter makes the rest explicit. + * + * ## What a hole may show (parameter 6, the human floor) + * + * A hole names one of the object's own fields, one segment deep, and shows its + * value only when that field is in {@link RuleMessageRendering.showable}: the + * fields the person the refusal is worded for may read, unmasked (the engine + * computes the set once per write, `engine-rule-message-rendering.ts`). Every + * other hole renders empty: a field that person cannot read, a field masked + * for them, a credential or internal field, a field the object does not + * declare, a read through a field (`{{ record.account.name }}`), a bare root + * and a hole over any other root. With no {@link RuleMessageRendering} at all, + * every hole renders empty. The scope the engine evaluates over holds the + * showable values only, so a hole is empty twice over: blanked before the + * render, and absent from its scope. + * + * What the deployment is told, through {@link RuleMessageRendering.warn}: a + * hole no reader could ever see filled — over another root, a bare root, a + * read through a field, a field the object does not declare: a message stored + * before the doors judged it — is named with its rule, so it can be rewritten. + * A hole empty only for this reader (a field they cannot read, or see masked) + * is ⛔ never reported: that is the floor working, not a fault. When the field + * security could not be asked at all ({@link RuleMessageRendering.unanswered}), + * the cause is written once. + * + * The verdict never depends on this: the rule was judged before its message is + * rendered, and the rendered sentence is the violation's `message` alone — + * ⛔ no value is written into the envelope's machine fields. + * + * ## When a template does not render + * + * A message carrying no `{{` is returned as written, exactly as before. A + * template that does not compile (a message stored before the doors judged it: + * a hole holding logic, an unknown formatter, unbalanced delimiters) does not + * render; {@link renderRuleMessage} says so, and the caller decides (a + * translation falls back to the authored message, an authored message that + * does not render is shown as written, as it was). A template that passes the + * doors always renders: see {@link tenantCurrencyHole} for the one hole the + * doors accept whose value depends on the deployment. + */ + +import { currencyDefaultRefusal, templateEngine } from '@objectstack/formula'; +import { VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS } from '@objectstack/spec/data'; + +/** What a rule message's holes may show and format with — computed by the engine once per write. */ +export interface RuleMessageRendering { + /** + * The fields of the object a hole may show the value of: the fields the + * person the refusal is worded for may read, unmasked, less every + * credential and internal field. A hole over any other field renders empty. + */ + readonly showable: ReadonlySet; + /** + * The fields the object declares. A hole over a field outside it is one no + * reader could see filled, and {@link warn} names it; without this set, no + * hole is reported for its field. + */ + readonly declared?: ReadonlySet; + /** + * Why no field is showable on this write, when the field security could not + * be asked (no security service, one that does not answer, the grants of the + * person an elevated write was made for unreadable). Written to {@link warn} + * when a hole renders empty for it. + */ + readonly unanswered?: string; + /** + * The tenant default currency (`ExecutionContext.currency`, the organization's + * `localization.currency`) a `currency` hole with no argument formats in; + * `undefined` when the organization has none. + */ + readonly currency?: string; + /** The reference timezone a `datetime` hole renders in (`ExecutionContext.timezone`). */ + readonly timezone?: string; + /** + * Where a message that does not render as authored is reported (the write's + * logger; the engine writes each distinct line once per write). + */ + readonly warn?: (message: string) => void; +} + +/** The values a rule message's holes read: the record the rule judged, and the stored row before it. */ +export interface RuleMessageValues { + /** The merged record the rule judged (the prior row overlaid with the write). */ + readonly record: Record; + /** The stored row before an update; `null` on an insert, `undefined` when not in hand. */ + readonly previous: Record | null | undefined; +} + +/** A rendered message, or why the template did not render. */ +export type RuleMessageRender = { readonly ok: true; readonly text: string } | { readonly ok: false; readonly reason: string }; + +/** Every `{{ … }}` hole — the template engine's `HOLE_RE`. */ +const HOLE = /\{\{([^}]*)\}\}/g; + +/** A hole's path — the template engine's `PATH_ONLY_RE`; a hole that fails it is left to the compile. */ +const HOLE_PATH = /^[\w$.[\]]+$/; + +const ROOTS: ReadonlySet = new Set(VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS); + +/** Whether `text` carries a `{{` — the only messages this module renders. */ +export function carriesTemplateHole(text: unknown): text is string { + return typeof text === 'string' && text.includes('{{'); +} + +/** The values of `row` a hole may show: the showable fields it carries, in a container with no prototype. */ +function showableValues(row: Record | null | undefined, showable: ReadonlySet): Record | undefined { + if (row === null || row === undefined || typeof row !== 'object') return undefined; + const out: Record = Object.create(null); + for (const field of showable) { + if (Object.prototype.hasOwnProperty.call(row, field)) out[field] = row[field]; + } + return out; +} + +/** + * [Parameter 8 — the fork, pending the maintainer's ruling] A `currency` hole + * with no argument formats in the tenant default currency, and the doors + * accept it whatever the deployment. With no tenant default the engine refuses + * the whole sentence (`currencyDefaultRefusal`), so a template that passed the + * doors would not render. Provisionally (option A of the fork put to the + * maintainer), the hole renders empty, as a hole over a field the caller cannot + * read does, and the deployment is told which setting fills it; ⛔ the amount + * is never formatted in a currency nobody chose, nor shown unformatted. + */ +function tenantCurrencyHole(hole: string, subject: string, warn: ((message: string) => void) | undefined): string { + warn?.( + `${subject}: the hole ${hole} formats in the tenant default currency, and none reached this write (the ` + + 'organization has none set, or the write carried none): the hole renders empty. Set the default currency ' + + 'in Setup → Localization (`localization.currency`), or name the currency in the hole (`currency:EUR`).', + ); + return ''; +} + +/** + * Why a hole can never show a value, whoever reads it, or `undefined` when it + * can: the doors refuse each of these, so only a message stored before them + * carries one. + */ +function structuralBlank(segments: readonly string[], declared: ReadonlySet | undefined): string | undefined { + const [root, field] = segments; + if (root === undefined || !ROOTS.has(root)) { + return `reads \`${root ?? ''}\`, which is not a root a rule message reads (${[...ROOTS].map((r) => `\`${r}\``).join(', ')})`; + } + if (field === undefined) return `names the root \`${root}\` alone, not one of its fields`; + if (segments.length > 2) return 'reads through a field; a hole reads one of the object\'s own fields, one segment deep'; + if (declared !== undefined && !declared.has(field)) return `names \`${field}\`, which the object does not declare`; + return undefined; +} + +/** + * The template with every hole that may not show a value blanked (see the + * module header). A hole that does not parse as a path is left as written, + * for the compile to refuse. + */ +function blankUnshowableHoles( + template: string, + values: RuleMessageValues, + rendering: RuleMessageRendering | undefined, + subject: string, +): string { + return template.replace(HOLE, (hole, inner: string) => { + const bar = inner.indexOf('|'); + const path = (bar === -1 ? inner : inner.slice(0, bar)).trim(); + // Not a path: the compile names it, and the template does not render. + if (!HOLE_PATH.test(path)) return hole; + const segments = path.replace(/\[(\w+)\]/g, '.$1').split('.').filter((segment) => segment !== ''); + if (rendering === undefined) return ''; + const structural = structuralBlank(segments, rendering.declared); + if (structural !== undefined) { + rendering.warn?.(`${subject}: the hole ${hole} ${structural}, so it renders empty for every reader. Rewrite it; \`objectstack validate\` names it.`); + return ''; + } + const [root, field] = segments as [string, string]; + if (!rendering.showable.has(field)) { + // Empty for this reader only: the floor, reported only when the field + // security could not be asked at all. + if (rendering.unanswered !== undefined) { + rendering.warn?.(`rule message holes render empty on this write: ${rendering.unanswered}.`); + } + return ''; + } + if (root === 'previous' && (values.previous === null || values.previous === undefined)) return ''; + if (bar !== -1) { + const formatter = inner.slice(bar + 1).trim(); + const colon = formatter.indexOf(':'); + const name = (colon === -1 ? formatter : formatter.slice(0, colon)).trim(); + if (name === 'currency' && colon === -1 && currencyDefaultRefusal(hole, rendering.currency) !== null) { + return tenantCurrencyHole(hole, subject, rendering.warn); + } + } + return hole; + }); +} + +/** + * Render one rule message (or one translation of it) over the judged record. + * + * A message carrying no `{{` comes back as written. Otherwise each hole that + * may not show a value is blanked, and the rest render through the template + * engine in `locale` (the refusal's negotiated locale) over the showable + * values of `values.record` and `values.previous`. `subject` names the + * message in what {@link RuleMessageRendering.warn} is told (the rule, its + * object, and which translation). + */ +export function renderRuleMessage( + template: string, + values: RuleMessageValues, + rendering: RuleMessageRendering | undefined, + locale: string | undefined, + subject = 'a validation rule message', +): RuleMessageRender { + if (!carriesTemplateHole(template)) return { ok: true, text: template }; + const source = blankUnshowableHoles(template, values, rendering, subject); + const showable = rendering?.showable ?? new Set(); + const record = showableValues(values.record, showable); + const previous = showableValues(values.previous, showable); + try { + const result = templateEngine.evaluate( + { dialect: 'template', source }, + { + ...(record !== undefined ? { record } : {}), + ...(previous !== undefined ? { previous } : {}), + ...(locale ? { locale } : {}), + ...(rendering?.currency ? { currency: rendering.currency } : {}), + ...(rendering?.timezone ? { timezone: rendering.timezone } : {}), + }, + ); + if (!result.ok) return { ok: false, reason: result.error.message }; + return { ok: true, text: String(result.value) }; + } catch (error) { + // A formatter refuses by throwing (`currency:eur`); the doors refuse every + // such hole, so only a message stored before them meets this. + return { ok: false, reason: error instanceof Error ? error.message : String(error) }; + } +} diff --git a/packages/objectql/src/validation/rule-validator.state-machine-option-labels.test.ts b/packages/objectql/src/validation/rule-validator.state-machine-option-labels.test.ts index eb2db779680..8f547c6b0b5 100644 --- a/packages/objectql/src/validation/rule-validator.state-machine-option-labels.test.ts +++ b/packages/objectql/src/validation/rule-validator.state-machine-option-labels.test.ts @@ -144,10 +144,14 @@ describe('state_machine invalid_transition — the built-in sentence names optio expect(err.message).toBe('Status不允许从 Presented 变更为 Draft'); }); - it('leaves an author-written message exactly as written — no holes are filled in it', () => { + // [#37909, ruling P3] An authored message is a template over `record` and + // `previous` only: a hole over the built-in sentence's own parameters + // (`from`, `to`) names another root, is refused at the doors, and renders + // empty here — the built-in wording's values never fill an authored hole. + it('never fills an author-written message with the built-in sentence\'s parameters', () => { const authored = 'Cannot move a quote from {{from}} to {{to}}.'; const [err] = failing(quoteSchema(authored), { status: 'draft' }, { previous: { status: 'presented' } }); - expect(err.message).toBe(authored); + expect(err.message).toBe('Cannot move a quote from to .'); expect(err.code).toBe('invalid_transition'); expect(err.constraint).toEqual({ from: 'presented', to: 'draft' }); }); diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index 58a2a26200c..3033904e294 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -257,6 +257,7 @@ import { type FieldValidationError, type ValidationMessageContext, } from './record-validator.js'; +import { renderRuleMessage, type RuleMessageValues } from './rule-message-render.js'; // Shared with the declarative hook-condition gate (#4770) so the two surfaces // that evaluate CEL against "the record" cannot drift apart on what that record // contains — see the module's own doc comment. @@ -4078,10 +4079,17 @@ export function emitValidationAdvisories( * built-in MESSAGES only. What #14253 added was a key shape for an * author-written rule, not a channel to resolve one. * - * The authored message is handed over verbatim on a miss and the translation is - * handed over verbatim on a hit: no `{{…}}` interpolation, because an authored - * message has no parameter contract and never had one. Only the language - * changes. + * ## The message is a template — #37909, ruling P3 + * + * The sentence it picks is then FILLED: a `{{ record.FIELD }}` / + * `{{ previous.FIELD }}` hole shows the judged record's value + * (`renderRuleMessage`, `rule-message-render.ts`, which says which holes may + * show a value and which render empty). Translation first (parameter 7): the + * translated template is picked and filled; if it does not render, the + * authored template is filled instead and `messages.rendering.warn` names the + * translation. An authored message that does not render (one stored before the + * doors judged it) is shown as written, as every message was before. A message + * carrying no `{{` is returned as written, translated or not. * * `rule.name` is the address — including a nested `conditional` branch's own * name, since the branch is the rule whose message the caller sees. @@ -4106,21 +4114,55 @@ export function emitValidationAdvisories( function authoredRuleMessage( rule: Pick, messages: ValidationMessageContext | undefined, + values: RuleMessageValues, ): string { - if (messages?.objectName && messages.locale && typeof rule.name === 'string' && rule.name.length > 0) { - if (scalarOverridesPackagedBase(messages.packagedRule?.(rule.name), 'message', rule.message)) { - return rule.message; - } - const doc = translatedLabels( - { name: messages.objectName, validations: [{ name: rule.name, message: rule.message }] }, - messages, + const object = messages?.objectName ?? '?'; + const translated = translatedRuleMessage(rule, messages); + if (translated !== undefined && translated !== rule.message) { + const translation = `the ${messages?.locale ?? '?'} translation of validation rule '${rule.name}' on object ` + + `'${object}' (objects.${object}._validations.${rule.name}.message)`; + const filled = renderRuleMessage(translated, values, messages?.rendering, messages?.locale, translation); + if (filled.ok) return filled.text; + messages?.rendering?.warn?.( + `${translation} does not render (${filled.reason}): the authored message is shown instead.`, ); - const translated: unknown = doc.validations[0]?.message; - if (typeof translated === 'string' && translated.length > 0) return translated; } + const subject = `the message of validation rule '${rule.name}' on object '${object}'`; + const authored = renderRuleMessage(rule.message, values, messages?.rendering, messages?.locale, subject); + if (authored.ok) return authored.text; + messages?.rendering?.warn?.( + `${subject} does not render ` + + `(${authored.reason}): it is shown as written. Run \`objectstack validate\`, which names the hole to fix.`, + ); return rule.message; } +/** + * The translation of a rule's message a refusal picks, or `undefined` when it + * shows the authored text: no object name or locale, a tenant's rewrite of + * the packaged rule (ADR-0029 D9.2a), or no translation. + */ +function translatedRuleMessage( + rule: Pick, + messages: ValidationMessageContext | undefined, +): string | undefined { + if (!messages?.objectName || !messages.locale || typeof rule.name !== 'string' || rule.name.length === 0) { + return undefined; + } + if (scalarOverridesPackagedBase(messages.packagedRule?.(rule.name), 'message', rule.message)) return undefined; + const doc = translatedLabels( + { name: messages.objectName, validations: [{ name: rule.name, message: rule.message }] }, + messages, + ); + const translated: unknown = doc.validations[0]?.message; + return typeof translated === 'string' && translated.length > 0 ? translated : undefined; +} + +/** [#37909] The values a rule message's holes read in `ctx`: the merged record, and `previous` as bound. */ +function ruleMessageValues(ctx: Pick): RuleMessageValues { + return { record: ctx.merged, previous: ctx.previous }; +} + /** * Dispatch a single rule to its checker, returning the violation (or null). * Shared by the top-level loop and by `checkConditional`, which recurses into @@ -4134,11 +4176,11 @@ function evaluateRule(rule: BaseRule, ctx: RuleContext): FieldValidationError | return checkStateMachine(rule as StateMachineRule, ctx.mode, ctx.data, ctx.previous, ctx); case 'script': case 'cross_field': - return checkPredicate(rule as PredicateRule, ctx.merged, ctx.previous, failClosedLogger(ctx), ctx.messages, ctx.related, ctx.fields); + return checkPredicate(rule as PredicateRule, ctx.merged, ctx.previous, failClosedLogger(ctx), ctx.messages, ctx.related, ctx.fields, ruleMessageValues(ctx)); case 'format': - return checkFormat(rule as FormatRule, ctx.data, ctx.logger, ctx.messages); + return checkFormat(rule as FormatRule, ctx.data, ctx.logger, ctx.messages, ruleMessageValues(ctx)); case 'json_schema': - return checkJsonSchema(rule as JsonSchemaRule, ctx.data, ctx.logger, ctx.messages); + return checkJsonSchema(rule as JsonSchemaRule, ctx.data, ctx.logger, ctx.messages, ruleMessageValues(ctx)); case 'conditional': return checkConditional(rule as ConditionalRule, ctx); default: @@ -4168,7 +4210,7 @@ function checkStateMachine( mode: Mode, data: Record, previous: PreviousBinding, - ctx?: Pick, + ctx?: Pick, ): FieldValidationError | null { // An author-written `rule.message` wins over the built-in fallback, and is // itself resolved against `objects.._validations..message` before it @@ -4187,7 +4229,7 @@ function checkStateMachine( return { field: rule.field, code, - message: authoredRuleMessage(rule, ctx?.messages), + message: authoredRuleMessage(rule, ctx?.messages, { record: ctx?.merged ?? data, previous }), label: resolveFieldLabel(rule.field, def, ctx?.messages), // An authored message replaces the built-in WORDING — not the // machine-readable facts beside it. `constraint` and `value` are @@ -4958,6 +5000,10 @@ function checkPredicate( messages?: ValidationMessageContext, related?: RelatedRecordBinding, fields?: Record, + // [#37909] The values the message's holes read: the merged record as judged + // BEFORE any related row is hydrated into a reference field below, so a + // `{{ record.account }}` hole shows the stored id, never the related row. + values: RuleMessageValues = { record, previous }, ): FieldValidationError | null { const expr = toExpression(rule.condition); const field = rule.fields?.[0] ?? '_record'; @@ -4997,7 +5043,7 @@ function checkPredicate( return { field, code: 'rule_violation', - message: authoredRuleMessage(rule, messages), + message: authoredRuleMessage(rule, messages, values), }; } return null; @@ -5025,7 +5071,8 @@ function checkFormat( rule: FormatRule, data: Record, logger: EvaluateRulesOptions['logger'], - messages?: ValidationMessageContext, + messages: ValidationMessageContext | undefined, + values: RuleMessageValues, ): FieldValidationError | null { if (!(rule.field in data)) return null; const value = data[rule.field]; @@ -5040,11 +5087,11 @@ function checkFormat( logger?.warn?.(`Validation rule '${rule.name}' has an invalid regex — skipped`); return null; } - if (!re.test(str)) return formatViolation(rule, messages); + if (!re.test(str)) return formatViolation(rule, messages, values); } if (rule.format && !matchesNamedFormat(rule.format, str)) { - return formatViolation(rule, messages); + return formatViolation(rule, messages, values); } return null; } @@ -5077,8 +5124,9 @@ function matchesNamedFormat(format: FormatRule['format'], str: string): boolean function formatViolation( rule: FormatRule, messages: ValidationMessageContext | undefined, + values: RuleMessageValues, ): FieldValidationError { - return { field: rule.field, code: 'invalid_format', message: authoredRuleMessage(rule, messages) }; + return { field: rule.field, code: 'invalid_format', message: authoredRuleMessage(rule, messages, values) }; } /** @@ -5092,7 +5140,8 @@ function checkJsonSchema( rule: JsonSchemaRule, data: Record, logger: EvaluateRulesOptions['logger'], - messages?: ValidationMessageContext, + messages: ValidationMessageContext | undefined, + values: RuleMessageValues, ): FieldValidationError | null { if (!(rule.field in data)) return null; let value = data[rule.field]; @@ -5102,7 +5151,7 @@ function checkJsonSchema( try { value = JSON.parse(value); } catch { - return { field: rule.field, code: 'invalid_json', message: authoredRuleMessage(rule, messages) }; + return { field: rule.field, code: 'invalid_json', message: authoredRuleMessage(rule, messages, values) }; } } @@ -5121,7 +5170,7 @@ function checkJsonSchema( } if (!validate(value)) { - return { field: rule.field, code: 'json_schema_violation', message: authoredRuleMessage(rule, messages) }; + return { field: rule.field, code: 'json_schema_violation', message: authoredRuleMessage(rule, messages, values) }; } return null; } diff --git a/packages/services/service-automation/src/flow-rule-message-reader.integration.test.ts b/packages/services/service-automation/src/flow-rule-message-reader.integration.test.ts new file mode 100644 index 00000000000..fbc76b067b7 --- /dev/null +++ b/packages/services/service-automation/src/flow-rule-message-reader.integration.test.ts @@ -0,0 +1,150 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#37909, ruling P3, parameter 6] A validation rule message's holes, on a + * write a `runAs: 'system'` flow makes for a person, show what THAT person + * may read — not what the elevated write may. + * + * The flow's data nodes write under `{ isSystem: true, userId: , + * tenantId }` (`resolveRunDataContext`), and a refused write's sentence is + * handed back to that person as the run's `innerRefusal.message` + * (`refusalCarriedBy`). The security contract answers a system context with + * every field, so a hole over a field the person cannot read would have shown + * its value to them. The engine asks the field security for the person + * instead (`engine-rule-message-rendering.ts`, "Whose read"), resolving their + * grants through `resolveUserAuthzGrants` since the run's context carries + * none. + * + * Directions decided before running: + * - a system flow started by a member who cannot read `margin`: the margin + * hole renders empty in `innerRefusal.message`, the other holes fill (was: + * the margin's value); + * - CONTROL, the member's own request making the same write: the same sentence; + * - CONTROL, a user-less system write: the margin shows — the only reader + * of that sentence is the server log. + * + * The real stack: ObjectKernel, ObjectQLPlugin, driver-sql on better-sqlite3 + * `:memory:`, the identity objects and the real SecurityPlugin, plus the real + * AutomationEngine and its CRUD nodes. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectKernel, resolveUserAuthzGrants, type PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { createIdentityObjectsPlugin } from '@objectstack/plugin-auth'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { AutomationServicePlugin } from './plugin.js'; +import type { AutomationEngine } from './engine.js'; + +const SYS = { isSystem: true } as const; + +const MESSAGE = 'Amount {{ record.amount }} is below the margin {{ record.margin }} on {{ record.name }}.'; + +const deal = { + name: 'rmr_deal', + label: 'Deal', + sharingModel: 'public_read_write', + fields: { + name: { name: 'name', label: 'Name', type: 'text' }, + amount: { name: 'amount', label: 'Amount', type: 'number' }, + margin: { name: 'margin', label: 'Margin', type: 'number' }, + }, + validations: [{ type: 'script', name: 'amount_not_negative', message: MESSAGE, condition: 'record.amount < 0', fields: ['amount'] }], +}; + +/** The deployment's member profile: deals, with the margin withheld. */ +const memberProfile = PermissionSetSchema.parse({ + name: 'rmr_member', label: 'Rule message reader: member profile', + objects: { rmr_deal: { allowRead: true, allowCreate: true, allowEdit: true } }, + fields: { 'rmr_deal.margin': { readable: false, editable: false } }, +}); + +/** start → update_record(rmr_deal, amount = -1) → end. */ +const repriceFlow = (runAs: 'system' | 'user', id: string) => ({ + name: `rmr_reprice_${runAs}`, label: `rmr_reprice_${runAs}`, type: 'autolaunched', runAs, + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'write', type: 'update_record', label: 'Write', config: { objectName: 'rmr_deal', filter: { id }, fields: { amount: -1 } } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'write' }, { id: 'e2', source: 'write', target: 'end' }], +}); + +describe('a rule message on a system flow\'s write shows what the person who started it may read', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let orgA = ''; + const DEAL = 'deal_1'; + + beforeAll(async () => { + kernel = new ObjectKernel({ logger: { level: 'fatal' } }); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await kernel.use({ + name: 'test.driver.sqlite', type: 'standard', version: '1.0.0', + async init(ctx: PluginContext) { ctx.registerService('driver.default', driver); }, + }); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin({ suspendedRunStore: 'memory' })); + await kernel.use(createIdentityObjectsPlugin()); + await kernel.use(new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, memberProfile], + fallbackPermissionSet: 'rmr_member', + })); + await kernel.bootstrap(); + + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + ql.registry.registerObject(deal as any, 'rule-message-reader-test', 'rule-message-reader-test'); + await ql.syncSchemas(); + for (const runAs of ['system', 'user'] as const) automation.registerFlow(`rmr_reprice_${runAs}`, repriceFlow(runAs, DEAL) as never); + + const orgs = await ql.find('sys_organization', { context: SYS }); + orgA = String(orgs[0].id); + await ql.insert('sys_user', { id: 'usr_rep', name: 'Rep', email: 'rep@example.test' }, { context: SYS }); + await ql.insert('sys_member', { id: 'mem_rep', user_id: 'usr_rep', organization_id: orgA, role: 'member' }, { context: SYS }); + await ql.insert('rmr_deal', { id: DEAL, name: 'Acme', amount: 100, margin: 30 }, { context: { ...SYS, tenantId: orgA } }); + }, 30_000); + + afterAll(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + const refusal = async (write: () => Promise): Promise => { + try { + await write(); + } catch (e: any) { + return String(e?.message); + } + throw new Error('expected the write to be refused'); + }; + + it('⭐ LIT — runAs: \'system\' started by a member who cannot read the margin: the margin hole is empty in innerRefusal', async () => { + const res = await automation.execute('rmr_reprice_system', { userId: 'usr_rep', tenantId: orgA }); + expect(res.success).toBe(false); + expect(res.innerRefusal).toEqual({ + code: 'VALIDATION_FAILED', + message: 'Amount -1 is below the margin on Acme.', + }); + }); + + it('⭐ LIT — runAs: \'user\', the same member: the same sentence', async () => { + const res = await automation.execute('rmr_reprice_user', { userId: 'usr_rep', tenantId: orgA }); + expect(res.success).toBe(false); + expect(res.innerRefusal?.message).toBe('Amount -1 is below the margin on Acme.'); + }); + + it('⭐ LIT — CONTROL: the member\'s own request making the same write reads the same sentence', async () => { + const g = await resolveUserAuthzGrants(ql, 'usr_rep', { tenantId: orgA, bypassGrantsCache: true }); + const context = { userId: 'usr_rep', tenantId: orgA, isSystem: false, positions: g.positions, permissions: g.permissions, org_user_ids: g.org_user_ids }; + expect(await refusal(() => ql.update('rmr_deal', { amount: -1 }, { where: { id: DEAL }, context } as any))) + .toBe('Amount -1 is below the margin on Acme.'); + }); + + it('⭐ LIT — CONTROL: a user-less system write keeps the system\'s answer: the margin shows', async () => { + expect(await refusal(() => ql.update('rmr_deal', { amount: -1 }, { where: { id: DEAL }, context: { ...SYS, tenantId: orgA } } as any))) + .toBe('Amount -1 is below the margin 30 on Acme.'); + }); +}); diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 555669f5bdd..b587763393f 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -983,7 +983,7 @@ "UnknownImportMappingTarget (interface)", "UnorderedPaginationConformanceCase (interface)", "UserActionTransferResolution (interface)", - "VALIDATION_MESSAGE_TEMPLATE_ROOTS (const)", + "VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS (const)", "VALID_AST_OPERATORS (const)", "VALUE_DOMAIN_FIELD_TYPES (const)", "VALUE_ROUNDTRIP_CASES (const)", diff --git a/packages/spec/docs/references/system/translation.md b/packages/spec/docs/references/system/translation.md index c65e53a9763..e24a4358521 100644 --- a/packages/spec/docs/references/system/translation.md +++ b/packages/spec/docs/references/system/translation.md @@ -162,7 +162,7 @@ Translation data for a single field | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **message** | `string` | optional | Translated rejection message — overlays the rule's authored `message` on every rejected write. The same `{{ }}` template the authored message is, over the same roots (`record`, `previous`; `VALIDATION_MESSAGE_TEMPLATE_ROOTS`): a single-brace `{…}` token, a hole over another root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. | +| **message** | `string` | optional | Translated rejection message — overlays the rule's authored `message` on every rejected write. The same `{{ }}` template the authored message is, over the same roots (`record`, `previous`; `VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS`): a single-brace `{…}` token, a hole over another root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. | ### Nested Shape: `ObjectTranslationData._milestones[string][string]` diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 69a9161b135..04a164f2e3f 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -968,7 +968,7 @@ "UnknownImportMappingTarget": "src/data/import-mapping-target.ts#UnknownImportMappingTarget (interface)", "UnorderedPaginationConformanceCase": "src/data/pagination-conformance.ts#UnorderedPaginationConformanceCase (interface)", "UserActionTransferResolution": "src/data/user-action-transfer.ts#UserActionTransferResolution (interface)", - "VALIDATION_MESSAGE_TEMPLATE_ROOTS": "src/data/validation.zod.ts#VALIDATION_MESSAGE_TEMPLATE_ROOTS (const)", + "VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS": "src/data/validation.zod.ts#VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS (const)", "VALID_AST_OPERATORS": "src/data/filter.zod.ts#VALID_AST_OPERATORS (const)", "VALUE_DOMAIN_FIELD_TYPES": "src/data/field.zod.ts#VALUE_DOMAIN_FIELD_TYPES (const)", "VALUE_ROUNDTRIP_CASES": "src/data/value-roundtrip-conformance.ts#VALUE_ROUNDTRIP_CASES (const)", diff --git a/packages/spec/src/data/validation.zod.ts b/packages/spec/src/data/validation.zod.ts index 7e3a688606b..ac486a1d5ee 100644 --- a/packages/spec/src/data/validation.zod.ts +++ b/packages/spec/src/data/validation.zod.ts @@ -143,7 +143,7 @@ import { lazySchema } from '../shared/lazy-schema'; * The message stays a string; a stored rule that carries a refused message * keeps loading and is judged at its next save. */ -export const VALIDATION_MESSAGE_TEMPLATE_ROOTS = ['record', 'previous'] as const; +export const VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS = ['record', 'previous'] as const; /** The `.describe()` text of a validation rule's `message`, shared by the six variants. */ const VALIDATION_MESSAGE_DESCRIPTION = diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index da1c6a8fdab..7983c699ac1 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -955,7 +955,7 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ * * **A translation is the same template the authored message is.** The rule * message is a `{{ }}` template over the judged record - * (`VALIDATION_MESSAGE_TEMPLATE_ROOTS`, `data/validation.zod.ts`), and each + * (`VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS`, `data/validation.zod.ts`), and each * translation carries the same holes in its own words. The doors judge every * translation exactly as they judge the authored message — not this parse, * so a stored bundle keeps loading and is judged at its next save. @@ -988,7 +988,7 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ .describe( "Translated rejection message — overlays the rule's authored `message` on every rejected write. The same " + '`{{ }}` template the authored message is, over the same roots (`record`, `previous`; ' - + '`VALIDATION_MESSAGE_TEMPLATE_ROOTS`): a single-brace `{…}` token, a hole over another root or field, ' + + '`VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS`): a single-brace `{…}` token, a hole over another root or field, ' + 'and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate.', ), })).optional().describe('Custom validation-rule messages keyed by rule name (`ValidationRuleSchema.name`)'),