Skip to content

Commit 8feef82

Browse files
fix(plugin-sharing)!: refuse a sharing-rule criteria that compares a choice field with an option label (#39543)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DMmPgXVVfb8MdCS5amdMX6N)_ Fixes #39434 Refs #39418 Clause-②: yes (narrowing) Metadata-protocol: none Skills-docs: follow-up #39583 — content/docs/permissions/sharing-rules.mdx (the page lists each save-time refusal on this door; outside this claim's file surface). No `skills/**` change owed: the skills teach declared `stack.sharingRules` CEL conditions, which are not `sys_sharing_rule` rows and never pass this door. `Metadata-protocol: none` is provisional, as the ruling leaves it: narrowed versus none is the contract reviewer's. Both same-door precedents declared `none` (PR #30953, the object-enforcement refusal; PR #39361, the user-recipient refusal), because a `sys_sharing_rule` row is an organization's data, not package metadata. ## 维护者速读 - 管理员或替他搭应用的 AI 在共享规则里把下拉、单选、多选字段的「显示名」当成值写(例如写「紧急」而记录里存的是内部值),以前照常保存却一条都不共享(取反写法则反过来共享给所有记录),现在保存时当场被拒,并告诉他该写哪个值。 - 属于共享规则「存得进却永远不生效」这一类问题的收口,替报修单场景里发现规则静默失效的管理员解决(上一张卡已补界面上的选项选择器,这次补接口和手写条件)。 - 只影响新保存或改了条件的规则;已存的旧规则照常加载、照常可以停用;如果误拦,撤回这一个改动即可恢复原样。 - 需要你确认这是一个破坏性收紧(保存时拒绝)并在合并前给出同意。 ## What changes A sharing rule's criteria that compares a choice field with one of its option **labels**, where the records hold the option's **value**, is refused at save, at both `sys_sharing_rule` doors, with one sentence naming the field, the label written and the value to write. Maintainer ruling recorded on the card (comment 7403149741, option A), verbatim: > 「refuse a `sys_sharing_rule` save when a criteria literal on a choice field is an option label where the row holds the value. The refusal names the value to write. Judged only when the criteria change.」 - New module `plugin-sharing/src/rule-criteria-option-label.ts`: the label reading (the one `flow-condition-option-label` defined for flows, read from the runtime registry via `engine.getSchema`), the refusal sentence, and `sameCriteria` (key order and string-or-object spelling aside). - `/data` door: `bindRuleCriteriaGuard` (`rule-hooks.ts`) refuses `VALIDATION_FAILED` (400) with one `fields` entry `{ field: 'criteria_json', code: 'invalid_option' }`, after its existing match-all check. - `POST /sharing/rules`: `defineRule` (`sharing-rule-service.ts`) throws an error whose message is `VALIDATION_FAILED: ` followed by the same sentence, which the route already maps to 400. - Judged on insert, and on update/upsert only when the supplied criteria differs from the stored one. System-context writes are judged too, like the match-all check in the same guard (and unlike the object and recipient guards): the verdict depends on the criteria alone. A first draft skipped system writes; `check:system-context-census` then required a new row on `content/docs/permissions/system-context.mdx` (outside this claim) for that elevation read, and judging every caller is the more consistent reading anyway. Pinned both ways (ablation 3). **Scope (as ruled).** Fields: `select`, `radio`, `multiselect`, `checkboxes` of the rule's object, inline non-empty options, not `readonly`, not bound to a shared `picklist`. A literal equal to an option's label that is also some option's value is **not** a label-for-value mistake and is accepted (pinned: `stage: 'open'` where `open` is one option's label and another's value). A literal that is neither a value nor a label is accepted unchanged (the spec admits stored values outside the options, `createMissingOptions`). **Comparand shapes, enumerated from the filter grammar (`FILTER_OPERATORS`, `LOGICAL_OPERATORS`) and the drivers' multi-value semantics:** | Shape | Covered | Why | |:--|:--|:--| | bare `F: L`, `$eq`, `$in` (each member) on a single-value field | yes | positive: shares nothing (measured) | | `$ne`, `$nin` (each member) on a single-value field | yes | negated: shares every record (measured, below) | | `$contains`, `$notContains` on a multi-value field | yes | the membership tests the engine runs on a JSON-stored column | | anywhere under `$and` / `$or` / `$not` | yes | walked at any depth | | equality family on a multi-value field | no | the engine refuses equality on a JSON-stored column for a reason of its own; naming a value would not make the rule run | | `$contains`/`$notContains`/`$startsWith`/`$endsWith`/`$icontains`/`$like`/`$ilike` on a single-value field | no | a pattern names no option, and its text may legitimately sit inside a value | | `$gt`/`$gte`/`$lt`/`$lte`/`$between` | no | order text, claim no option | | `$null`/`$exists`/`$empty` | no | no literal | | array (AST) spelling `['F','=','L']` | not reached | both doors already refuse it first as a criteria that narrows nothing (`isMatchAllCriteria`), measured while writing the pins | | dotted path (`owner.status`) | no | not a field of the rule's object | <details><summary>Carried item 2: negated comparands measured first (over-share)</summary> Real `ObjectQL` + `SqlDriver` (better-sqlite3), five repair orders (three `gao`, two `jinji`), a rule row stored as before this guard, `evaluateRule`, then `sys_record_share` read off the driver: - `{"jinji_chengdu":{"$ne":"紧急"}}` → grants on all 5 records (the 2 urgent ones the author meant to exclude included); control `$ne: "jinji"` → the 3 non-urgent. - `{"jinji_chengdu":{"$nin":["紧急"]}}` → all 5; control `$nin: ["jinji"]` → the 3 non-urgent. - bare / `$eq` / `$in` on the label → 0; control on the value → the 2 urgent. These eight cases are pinned in the first `describe` of the new test and passed both before and after the fix (they measure the evaluator, not the guard). </details> ## Tests New file `packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts` (30 cases): the measurement above; the /data door refusing bare, `$eq`, `$ne`, `$in`, `$nin`, nested `$and`/`$or`/`$not`, multiselect `$contains`, checkboxes `$notContains`, each naming the value; controls (value; value under `$ne`/`$in`; a literal outside values and labels; a label that is also a value; a readonly choice field; a non-choice field; a substring operator); an update changing criteria to a label refused with the row kept; a criteria-untouched update on a legacy label row saved (also with the unchanged criteria re-sent); `defineRule` refusing with the /data door's sentence behind `VALIDATION_FAILED: `; an upsert keeping a stored label criteria saved and one changing to a label refused; the system context judged at both doors. <details><summary>Red-first, green, ablations</summary> - Red at `10ad9101` (test only): `Tests 13 failed | 17 passed (30)` — every refusal case red, every measurement and control green. - Green at `da6cbc17`: `pnpm --filter @objectstack/plugin-sharing test` → `Test Files 84 passed (84)` / `Tests 1828 passed | 11 skipped (1839)`; `pnpm --filter @objectstack/plugin-sharing typecheck` → exit 0 (`check:test-typecheck: OK`). - Ablation 1 (`scripts/ablation-replace.mjs`, mutation landed anchor 1 → 0, restored blob == HEAD): `$ne` dropped from the single-value scalar set → `Tests 3 failed | 26 passed (29)` (run before the system-context case was added) (the `$ne` /data, the update-to-`$ne`, the `$ne` defineRule cases). - Ablation 2: the /data door's `sameCriteria` skip deleted → `Tests 1 failed | 28 passed (29)` (the criteria-untouched update on a legacy label row). - Ablation 3: an `isSystem` skip re-inserted in the /data guard → `Tests 1 failed | 29 passed (30)` (the system-context case); restored blob == HEAD, `git diff HEAD` empty. </details> ## Acceptance notes - `content/docs/permissions/sharing-rules.mdx` describes each save-time refusal on this door; this one is not added there (outside the claim's file surface) — filed as #39583. - Picklist-bound fields are skipped as ruled (analysis 7399582338 scope). At runtime the registry folds a picklist's options into the field, so the same reading would be sound there; widening is a later decision, not taken here. - "Judged only when the criteria change" is read literally: an update that moves a rule to another object without touching `criteria_json` is not judged by this check. - The option reading duplicates `selectOptionsOf` in `@objectstack/lint` (`flow-select-options.ts`): plugin-sharing does not depend on `@objectstack/lint`, that helper is not exported from its index, and `packages/lint/src/**` is outside this claim. - A label in a declared `stack.sharingRules` CEL condition is not judged here (declared rules are not rows); the lint rule for it is the seat's follow-up after the claims holding `packages/lint/src` release. ## Verification Read first, by risk: `packages/plugins/plugin-sharing/src/rule-hooks.ts` (the `bindRuleCriteriaGuard` hunk: ordering after match-all, no system skip, the `sameCriteria` early return); `packages/plugins/plugin-sharing/src/sharing-rule-service.ts` (the `defineRule` hunk, judged for every caller before the non-system block); `packages/plugins/plugin-sharing/src/rule-criteria-option-label.ts` (`choiceOptionsOf`, `judgeComparand`). Two-minute check: `pnpm --filter @objectstack/plugin-sharing exec vitest run --maxWorkers=2 src/sharing-rule-option-label-39434.test.ts` → expect `Tests 30 passed (30)`. <details><summary>Gates (local subset at da6cbc1)</summary> Derived with `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at `da6cbc17` (73 commands), each run with its exit code captured before any pipe; reconciliation: ``` Run reconciliation — 73 derived, 73 run, 0 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 73 derived famil(ies) accounted for — 73 run, 0 NOT-MEASURED (a DERIVED zero — all 73 recorded an exit code and none of them is 3). ``` All 73 exited 0. ADR-0087 disposition: ``` ✓ check-adr-0087-registration: 1 declared-breaking changeset(s), each carrying an ADR-0087 disposition. .changeset/39434-sharing-rule-option-label-criteria.md [BREAKING+clause-②-narrowing] not-required (no-migration-prescription) ``` Package: `pnpm --filter @objectstack/plugin-sharing test` / `typecheck` / `build` exit 0 at `da6cbc17` (dependency closure built first with `pnpm --filter '@objectstack/plugin-sharing^...' build`). `test:repo`, `pnpm lint` and the whole-tree families are CI's. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4czHUJLmdQAqm4fdDs9 <!-- signed: repo:objectstack@os-elon-musk · os-elon-musk · session_016WV4czHUJLmdQAqm4fdDs9 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4fed008 commit 8feef82

5 files changed

Lines changed: 622 additions & 3 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/plugin-sharing': patch
3+
---
4+
5+
fix(plugin-sharing): a sharing rule whose criteria compares a choice field with an option's label, where the records hold the option's value, is refused at save
6+
7+
Clause-②: yes (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) a rule comparing a choice field with an option label was already inert (or, negated, matched every record); stored rows are untouched, still load and evaluate as before, and an update that leaves the criteria alone still saves, so there is nothing for an upgrader to migrate -->
11+
12+
Who sees it: an administrator or an agent saving a sharing rule, through the Setup sharing-rule form or any write of `sys_sharing_rule` (`POST`/`PATCH /api/v1/data/sys_sharing_rule`, an import, a batch write), and through `POST /api/v1/sharing/rules`.
13+
14+
- **Before:** a criteria such as `{"jinji_chengdu":"紧急"}` on a `radio` field whose options are 高 (`gao`) and 紧急 (`jinji`) saved and showed as active. The records hold `jinji`, so the rule shared nothing. The negated forms (`$ne` / `$nin` on the label) shared every record, the ones the author meant to exclude included.
15+
- **Now:** both doors answer `400 VALIDATION_FAILED` with one sentence naming the field, the label written and the value to write (`/data` with one `fields` entry under `criteria_json`, code `invalid_option`). Nothing is stored. Judged on `select`, `radio`, `multiselect` and `checkboxes` fields with inline options, not readonly and not bound to a shared picklist: plain equality, `$eq`, `$ne`, `$in`, `$nin`, and on a multi-value field `$contains` / `$notContains`, anywhere under `$and` / `$or` / `$not`.
16+
- A literal that is neither an option value nor a label still saves, and so does a label that is also another option's value. An update that leaves the criteria alone is not judged, so a rule saved with a label can still be switched off. As with the existing check for a criteria that narrows nothing, the verdict does not depend on who writes: system-context writes are judged too.
17+
18+
**BREAKING:** a sharing rule whose condition compares a choice field with the text shown for an option, instead of the option's stored value, used to save and quietly share nothing (or everything, when negated); it is now refused when you save it, and the message tells you which value to use. Use the option's value in the condition, as the message names it.
Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#39434] A sharing rule's criteria that compares a choice field with one of
5+
* its option LABELS, where the records hold the option's VALUE.
6+
*
7+
* The evaluator hands the criteria to `engine.find` as written, and a choice
8+
* field stores option values, so a label literal matches no record the engine
9+
* wrote under the current options: the positive comparands (`F: L`,
10+
* `$eq`, `$in`, `$contains` on a multi-value field) make a rule that shares
11+
* nothing, and the negated ones (`$ne`, `$nin`, `$notContains`) a rule that
12+
* shares EVERY record — the ones the author meant to exclude included. Both
13+
* save as active with no signal: the silently inert (or silently wide)
14+
* metadata ADR-0078 prohibits. The two `sys_sharing_rule` save doors refuse
15+
* it (maintainer ruling on this card, option A): the `/data` door through
16+
* `bindRuleCriteriaGuard` (`rule-hooks.ts`) and `defineRule`
17+
* (`sharing-rule-service.ts`, `POST /sharing/rules`), with the one sentence
18+
* {@link optionLabelCriteriaRefusal} builds.
19+
*
20+
* What is judged — the reading `flow-condition-option-label` (`@objectstack/lint`
21+
* `flow-select-options.ts`) defined for flows, applied to the runtime registry:
22+
*
23+
* - a field of the rule's own object (a top-level key; a dotted path is not
24+
* judged) of type `select`, `radio`, `multiselect` or `checkboxes`, with an
25+
* inline non-empty `options` list, not `readonly` (a readonly choice value
26+
* is judged by shape only on a write, so a stored value may be anything) and
27+
* not bound to a shared `picklist`;
28+
* - a literal equal to an option's label that is NOT also some option's value
29+
* (a value is never a mistake, whichever option's label it also is);
30+
* - anywhere under `$and` / `$or` / `$not`. (The array spelling,
31+
* `['F', '=', 'L']`, never reaches this check: both doors refuse it first as
32+
* a criteria that narrows nothing, `isMatchAllCriteria`.)
33+
*
34+
* The comparand shapes judged, per the filter grammar the engine runs
35+
* (`FILTER_OPERATORS`, `@objectstack/spec/data`):
36+
*
37+
* - single-value field: bare equality, `$eq`, `$ne` (a string), `$in`, `$nin`
38+
* (each string member);
39+
* - multi-value field (`isMultiValueField`): `$contains`, `$notContains` — the
40+
* membership tests the engine runs on a JSON-stored column.
41+
*
42+
* Deliberately not judged: the ordering and range operators (`$gt`…`$lte`,
43+
* `$between`) — they order text and claim no option; the substring and
44+
* pattern operators on a single-value field (`$contains`, `$notContains`,
45+
* `$startsWith`, `$endsWith`, `$icontains`, `$like`, `$ilike`) — a pattern
46+
* names no option, and its text may legitimately sit inside a value; the
47+
* equality family on a multi-value field — the engine refuses it on a
48+
* JSON-stored column for a reason of its own, so naming a value to write
49+
* would not make the rule run; `$null` / `$exists` / `$empty` — no literal.
50+
*
51+
* A literal that is neither a value nor a label is NOT refused: the spec
52+
* admits stored values outside the options (`createMissingOptions`, a retired
53+
* option rows still hold), so such a literal may match real records.
54+
*/
55+
56+
import { isMultiValueField } from '@objectstack/spec/data';
57+
58+
import { parseCriteria } from './rule-criteria.js';
59+
60+
/** Field types whose value is one or more option codes. */
61+
const OPTION_FIELD_TYPES: ReadonlySet<string> = new Set(['select', 'radio', 'multiselect', 'checkboxes']);
62+
63+
/** Comparands that name one option on a single-value field. */
64+
const SINGLE_VALUE_SCALAR_OPS: ReadonlySet<string> = new Set(['$eq', '$ne']);
65+
const SINGLE_VALUE_LIST_OPS: ReadonlySet<string> = new Set(['$in', '$nin']);
66+
/** Comparands that name one member on a multi-value field. */
67+
const MULTI_VALUE_MEMBER_OPS: ReadonlySet<string> = new Set(['$contains', '$notContains']);
68+
69+
const LOGICAL_LIST_KEYS: ReadonlySet<string> = new Set(['$and', '$or']);
70+
71+
type AnyRec = Record<string, unknown>;
72+
const isRec = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v);
73+
74+
/** One judgeable choice field. */
75+
interface ChoiceOptions {
76+
/** label → value, for labels that are not also some option's value. */
77+
readonly labels: ReadonlyMap<string, string>;
78+
/** Whether the stored value is a list of codes. */
79+
readonly multiple: boolean;
80+
}
81+
82+
/** The options of one field definition, or `undefined` when it is not judged. */
83+
function choiceOptionsOf(def: unknown): ChoiceOptions | undefined {
84+
if (!isRec(def) || typeof def.type !== 'string' || !OPTION_FIELD_TYPES.has(def.type)) return undefined;
85+
if (def.readonly === true) return undefined;
86+
if (typeof def.picklist === 'string' && def.picklist.length > 0) return undefined;
87+
if (!Array.isArray(def.options) || def.options.length === 0) return undefined;
88+
const values = new Set<string>();
89+
const pairs: Array<[string, string]> = [];
90+
for (const option of def.options) {
91+
if (typeof option === 'string') {
92+
values.add(option);
93+
continue;
94+
}
95+
if (!isRec(option) || option.value === undefined || option.value === null) continue;
96+
const value = String(option.value);
97+
values.add(value);
98+
if (typeof option.label === 'string') pairs.push([option.label, value]);
99+
}
100+
const labels = new Map<string, string>();
101+
for (const [label, value] of pairs) {
102+
if (label !== value && !values.has(label) && !labels.has(label)) labels.set(label, value);
103+
}
104+
if (labels.size === 0) return undefined;
105+
return { labels, multiple: isMultiValueField(def as { type: string; multiple?: boolean }) };
106+
}
107+
108+
/** One option label written where the field stores the value. */
109+
export interface OptionLabelComparand {
110+
readonly field: string;
111+
readonly label: string;
112+
readonly value: string;
113+
}
114+
115+
/** The engine's view of one object, as much of it as this check reads. */
116+
export interface OptionLabelSchemaSource {
117+
getSchema?(object: string): unknown;
118+
}
119+
120+
/**
121+
* Every option label `criteria` compares a choice field of `object` with,
122+
* in criteria order, each (field, label) pair once. `[]` when the engine
123+
* cannot say what the object's fields are.
124+
*/
125+
export function findOptionLabelComparands(
126+
engine: OptionLabelSchemaSource,
127+
object: unknown,
128+
criteria: unknown,
129+
): OptionLabelComparand[] {
130+
if (typeof object !== 'string' || object.length === 0) return [];
131+
if (typeof engine.getSchema !== 'function') return [];
132+
const fields = (engine.getSchema(object) as { fields?: unknown } | undefined)?.fields;
133+
if (!isRec(fields)) return [];
134+
135+
const found: OptionLabelComparand[] = [];
136+
const seen = new Set<string>();
137+
const note = (field: string, options: ChoiceOptions, literal: unknown) => {
138+
if (typeof literal !== 'string') return;
139+
const value = options.labels.get(literal);
140+
if (value === undefined) return;
141+
const key = JSON.stringify([field, literal]);
142+
if (seen.has(key)) return;
143+
seen.add(key);
144+
found.push({ field, label: literal, value });
145+
};
146+
const judgeComparand = (field: string, options: ChoiceOptions, comparand: unknown) => {
147+
if (!isRec(comparand)) {
148+
if (!options.multiple) note(field, options, comparand);
149+
return;
150+
}
151+
for (const [op, operand] of Object.entries(comparand)) {
152+
if (options.multiple) {
153+
if (MULTI_VALUE_MEMBER_OPS.has(op)) note(field, options, operand);
154+
continue;
155+
}
156+
if (SINGLE_VALUE_SCALAR_OPS.has(op)) note(field, options, operand);
157+
else if (SINGLE_VALUE_LIST_OPS.has(op) && Array.isArray(operand)) {
158+
for (const member of operand) note(field, options, member);
159+
}
160+
}
161+
};
162+
const walk = (node: unknown) => {
163+
if (Array.isArray(node)) {
164+
for (const child of node) walk(child);
165+
return;
166+
}
167+
if (!isRec(node)) return;
168+
for (const [key, value] of Object.entries(node)) {
169+
if (LOGICAL_LIST_KEYS.has(key)) {
170+
if (Array.isArray(value)) for (const child of value) walk(child);
171+
continue;
172+
}
173+
if (key === '$not') {
174+
walk(value);
175+
continue;
176+
}
177+
if (key.startsWith('$')) continue;
178+
const options = choiceOptionsOf(fields[key]);
179+
if (options) judgeComparand(key, options, value);
180+
}
181+
};
182+
walk(parseCriteria(criteria));
183+
return found;
184+
}
185+
186+
/**
187+
* The refusal sentence for `criteria` on `object`, or `null` when it compares
188+
* no choice field with an option label. Both save doors answer it verbatim:
189+
* the `/data` door as a `VALIDATION_FAILED` under `criteria_json`, and
190+
* `defineRule` behind the `VALIDATION_FAILED:` prefix `POST /sharing/rules`
191+
* maps to 400.
192+
*/
193+
export function optionLabelCriteriaRefusal(
194+
engine: OptionLabelSchemaSource,
195+
object: unknown,
196+
criteria: unknown,
197+
): string | null {
198+
const found = findOptionLabelComparands(engine, object, criteria);
199+
if (found.length === 0) return null;
200+
const each = found
201+
.map((f) => `${f.field} with ${JSON.stringify(f.label)} (write ${JSON.stringify(f.value)})`)
202+
.join('; ');
203+
return (
204+
`criteria compares a choice field with an option's label, but the field stores the option's value: ${each}. ` +
205+
'A label matches no record, so the rule would share nothing, or, negated, share every record. ' +
206+
'Write the option value instead.'
207+
);
208+
}
209+
210+
/** Key order and string-or-object spelling aside, is `a` the same criteria as `b`? */
211+
export function sameCriteria(a: unknown, b: unknown): boolean {
212+
if (a === b) return true;
213+
return canonical(parseCriteria(a)) === canonical(parseCriteria(b));
214+
}
215+
216+
function canonical(value: unknown): string {
217+
if (value === undefined) return 'undefined';
218+
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
219+
if (isRec(value)) {
220+
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`;
221+
}
222+
return JSON.stringify(value);
223+
}

‎packages/plugins/plugin-sharing/src/rule-hooks.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import type { SharingRuleService } from './sharing-rule-service.js';
44
import type { SharingRuleRow } from '@objectstack/spec/contracts';
55
import { isMatchAllCriteria, SharingCriteriaValidationError, SharingRuleObjectNotEnforcedError } from './rule-criteria.js';
6+
import { optionLabelCriteriaRefusal, sameCriteria, type OptionLabelSchemaSource } from './rule-criteria-option-label.js';
67
import type { SharingService } from './sharing-service.js';
78
import { isSummaryRecomputeRefusal, validationFailure } from '@objectstack/types';
89
import {
@@ -463,8 +464,21 @@ export function unbindAllRuleHooks(engine: MinimalEngine): number {
463464
* names the offending shape instead of saying "required". Defense in depth on
464465
* the null cases costs one property check and keeps this guard's better
465466
* message on paths where hooks fire before validation.
467+
*
468+
* [#39434] The same guard refuses a criteria that compares a choice field with
469+
* one of its option LABELS where the records hold the value
470+
* ({@link optionLabelCriteriaRefusal}, `defineRule`'s own sentence):
471+
* `VALIDATION_FAILED` under `criteria_json`. Judged on an insert, and on an
472+
* update only when the supplied criteria differs from the stored one, so a
473+
* rule saved with a label can still be switched off. Like the match-all check
474+
* above it, and unlike the object and recipient guards, it judges system
475+
* writes too: what it refuses depends on the criteria alone, never on who
476+
* writes it, and `defineRule` makes the same check for every caller.
466477
*/
467-
export function bindRuleCriteriaGuard(engine: MinimalEngine, logger?: MinimalLogger): void {
478+
export function bindRuleCriteriaGuard(
479+
engine: MinimalEngine & OptionLabelSchemaSource,
480+
logger?: MinimalLogger,
481+
): void {
468482
if (typeof engine.registerHook !== 'function') return;
469483
if (typeof engine.unregisterHooksByPackage === 'function') {
470484
engine.unregisterHooksByPackage(RULE_CRITERIA_GUARD_PACKAGE);
@@ -474,8 +488,16 @@ export function bindRuleCriteriaGuard(engine: MinimalEngine, logger?: MinimalLog
474488
if (!data || typeof data !== 'object' || Array.isArray(data)) return;
475489
const supplied = Object.prototype.hasOwnProperty.call(data, 'criteria_json');
476490
if (!insert && !supplied) return;
477-
if (!isMatchAllCriteria(data.criteria_json)) return;
478-
throw new SharingCriteriaValidationError();
491+
if (isMatchAllCriteria(data.criteria_json)) throw new SharingCriteriaValidationError();
492+
const previous = !insert && ctx?.previous && typeof ctx.previous === 'object'
493+
? ctx.previous as Record<string, unknown>
494+
: undefined;
495+
if (previous && sameCriteria(previous.criteria_json, data.criteria_json)) return;
496+
const object = data.object_name !== undefined ? data.object_name : previous?.object_name;
497+
const refusal = optionLabelCriteriaRefusal(engine, object, data.criteria_json);
498+
if (refusal) {
499+
throw validationFailure(refusal, [{ field: 'criteria_json', code: 'invalid_option', message: refusal }]);
500+
}
479501
};
480502
const opts = { object: 'sys_sharing_rule', packageId: RULE_CRITERIA_GUARD_PACKAGE, priority: 100 };
481503
engine.registerHook('beforeInsert', guard(true), opts);

0 commit comments

Comments
 (0)