Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/39434-sharing-rule-option-label-criteria.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@objectstack/plugin-sharing': patch
---

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

Clause-②: yes (narrowing)
Metadata-protocol: none

<!-- 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 -->

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`.

- **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.
- **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`.
- 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.

**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.
223 changes: 223 additions & 0 deletions packages/plugins/plugin-sharing/src/rule-criteria-option-label.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#39434] A sharing rule's criteria that compares a choice field with one of
* its option LABELS, where the records hold the option's VALUE.
*
* The evaluator hands the criteria to `engine.find` as written, and a choice
* field stores option values, so a label literal matches no record the engine
* wrote under the current options: the positive comparands (`F: L`,
* `$eq`, `$in`, `$contains` on a multi-value field) make a rule that shares
* nothing, and the negated ones (`$ne`, `$nin`, `$notContains`) a rule that
* shares EVERY record — the ones the author meant to exclude included. Both
* save as active with no signal: the silently inert (or silently wide)
* metadata ADR-0078 prohibits. The two `sys_sharing_rule` save doors refuse
* it (maintainer ruling on this card, option A): the `/data` door through
* `bindRuleCriteriaGuard` (`rule-hooks.ts`) and `defineRule`
* (`sharing-rule-service.ts`, `POST /sharing/rules`), with the one sentence
* {@link optionLabelCriteriaRefusal} builds.
*
* What is judged — the reading `flow-condition-option-label` (`@objectstack/lint`
* `flow-select-options.ts`) defined for flows, applied to the runtime registry:
*
* - a field of the rule's own object (a top-level key; a dotted path is not
* judged) of type `select`, `radio`, `multiselect` or `checkboxes`, with an
* inline non-empty `options` list, not `readonly` (a readonly choice value
* is judged by shape only on a write, so a stored value may be anything) and
* not bound to a shared `picklist`;
* - a literal equal to an option's label that is NOT also some option's value
* (a value is never a mistake, whichever option's label it also is);
* - anywhere under `$and` / `$or` / `$not`. (The array spelling,
* `['F', '=', 'L']`, never reaches this check: both doors refuse it first as
* a criteria that narrows nothing, `isMatchAllCriteria`.)
*
* The comparand shapes judged, per the filter grammar the engine runs
* (`FILTER_OPERATORS`, `@objectstack/spec/data`):
*
* - single-value field: bare equality, `$eq`, `$ne` (a string), `$in`, `$nin`
* (each string member);
* - multi-value field (`isMultiValueField`): `$contains`, `$notContains` — the
* membership tests the engine runs on a JSON-stored column.
*
* Deliberately not judged: the ordering and range operators (`$gt`…`$lte`,
* `$between`) — they order text and claim no option; the substring and
* pattern operators on a single-value field (`$contains`, `$notContains`,
* `$startsWith`, `$endsWith`, `$icontains`, `$like`, `$ilike`) — a pattern
* names no option, and its text may legitimately sit inside a value; the
* equality family on a multi-value field — the engine refuses it on a
* JSON-stored column for a reason of its own, so naming a value to write
* would not make the rule run; `$null` / `$exists` / `$empty` — no literal.
*
* A literal that is neither a value nor a label is NOT refused: the spec
* admits stored values outside the options (`createMissingOptions`, a retired
* option rows still hold), so such a literal may match real records.
*/

import { isMultiValueField } from '@objectstack/spec/data';

import { parseCriteria } from './rule-criteria.js';

/** Field types whose value is one or more option codes. */
const OPTION_FIELD_TYPES: ReadonlySet<string> = new Set(['select', 'radio', 'multiselect', 'checkboxes']);

/** Comparands that name one option on a single-value field. */
const SINGLE_VALUE_SCALAR_OPS: ReadonlySet<string> = new Set(['$eq', '$ne']);
const SINGLE_VALUE_LIST_OPS: ReadonlySet<string> = new Set(['$in', '$nin']);
/** Comparands that name one member on a multi-value field. */
const MULTI_VALUE_MEMBER_OPS: ReadonlySet<string> = new Set(['$contains', '$notContains']);

const LOGICAL_LIST_KEYS: ReadonlySet<string> = new Set(['$and', '$or']);

type AnyRec = Record<string, unknown>;
const isRec = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v);

/** One judgeable choice field. */
interface ChoiceOptions {
/** label → value, for labels that are not also some option's value. */
readonly labels: ReadonlyMap<string, string>;
/** Whether the stored value is a list of codes. */
readonly multiple: boolean;
}

/** The options of one field definition, or `undefined` when it is not judged. */
function choiceOptionsOf(def: unknown): ChoiceOptions | undefined {
if (!isRec(def) || typeof def.type !== 'string' || !OPTION_FIELD_TYPES.has(def.type)) return undefined;
if (def.readonly === true) return undefined;
if (typeof def.picklist === 'string' && def.picklist.length > 0) return undefined;
if (!Array.isArray(def.options) || def.options.length === 0) return undefined;
const values = new Set<string>();
const pairs: Array<[string, string]> = [];
for (const option of def.options) {
if (typeof option === 'string') {
values.add(option);
continue;
}
if (!isRec(option) || option.value === undefined || option.value === null) continue;
const value = String(option.value);
values.add(value);
if (typeof option.label === 'string') pairs.push([option.label, value]);
}
const labels = new Map<string, string>();
for (const [label, value] of pairs) {
if (label !== value && !values.has(label) && !labels.has(label)) labels.set(label, value);
}
if (labels.size === 0) return undefined;
return { labels, multiple: isMultiValueField(def as { type: string; multiple?: boolean }) };
}

/** One option label written where the field stores the value. */
export interface OptionLabelComparand {
readonly field: string;
readonly label: string;
readonly value: string;
}

/** The engine's view of one object, as much of it as this check reads. */
export interface OptionLabelSchemaSource {
getSchema?(object: string): unknown;
}

/**
* Every option label `criteria` compares a choice field of `object` with,
* in criteria order, each (field, label) pair once. `[]` when the engine
* cannot say what the object's fields are.
*/
export function findOptionLabelComparands(
engine: OptionLabelSchemaSource,
object: unknown,
criteria: unknown,
): OptionLabelComparand[] {
if (typeof object !== 'string' || object.length === 0) return [];
if (typeof engine.getSchema !== 'function') return [];
const fields = (engine.getSchema(object) as { fields?: unknown } | undefined)?.fields;
if (!isRec(fields)) return [];

const found: OptionLabelComparand[] = [];
const seen = new Set<string>();
const note = (field: string, options: ChoiceOptions, literal: unknown) => {
if (typeof literal !== 'string') return;
const value = options.labels.get(literal);
if (value === undefined) return;
const key = JSON.stringify([field, literal]);
if (seen.has(key)) return;
seen.add(key);
found.push({ field, label: literal, value });
};
const judgeComparand = (field: string, options: ChoiceOptions, comparand: unknown) => {
if (!isRec(comparand)) {
if (!options.multiple) note(field, options, comparand);
return;
}
for (const [op, operand] of Object.entries(comparand)) {
if (options.multiple) {
if (MULTI_VALUE_MEMBER_OPS.has(op)) note(field, options, operand);
continue;
}
if (SINGLE_VALUE_SCALAR_OPS.has(op)) note(field, options, operand);
else if (SINGLE_VALUE_LIST_OPS.has(op) && Array.isArray(operand)) {
for (const member of operand) note(field, options, member);
}
}
};
const walk = (node: unknown) => {
if (Array.isArray(node)) {
for (const child of node) walk(child);
return;
}
if (!isRec(node)) return;
for (const [key, value] of Object.entries(node)) {
if (LOGICAL_LIST_KEYS.has(key)) {
if (Array.isArray(value)) for (const child of value) walk(child);
continue;
}
if (key === '$not') {
walk(value);
continue;
}
if (key.startsWith('$')) continue;
const options = choiceOptionsOf(fields[key]);
if (options) judgeComparand(key, options, value);
}
};
walk(parseCriteria(criteria));
return found;
}

/**
* The refusal sentence for `criteria` on `object`, or `null` when it compares
* no choice field with an option label. Both save doors answer it verbatim:
* the `/data` door as a `VALIDATION_FAILED` under `criteria_json`, and
* `defineRule` behind the `VALIDATION_FAILED:` prefix `POST /sharing/rules`
* maps to 400.
*/
export function optionLabelCriteriaRefusal(
engine: OptionLabelSchemaSource,
object: unknown,
criteria: unknown,
): string | null {
const found = findOptionLabelComparands(engine, object, criteria);
if (found.length === 0) return null;
const each = found
.map((f) => `${f.field} with ${JSON.stringify(f.label)} (write ${JSON.stringify(f.value)})`)
.join('; ');
return (
`criteria compares a choice field with an option's label, but the field stores the option's value: ${each}. ` +
'A label matches no record, so the rule would share nothing, or, negated, share every record. ' +
'Write the option value instead.'
);
}

/** Key order and string-or-object spelling aside, is `a` the same criteria as `b`? */
export function sameCriteria(a: unknown, b: unknown): boolean {
if (a === b) return true;
return canonical(parseCriteria(a)) === canonical(parseCriteria(b));
}

function canonical(value: unknown): string {
if (value === undefined) return 'undefined';
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
if (isRec(value)) {
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`;
}
return JSON.stringify(value);
}
28 changes: 25 additions & 3 deletions packages/plugins/plugin-sharing/src/rule-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import type { SharingRuleService } from './sharing-rule-service.js';
import type { SharingRuleRow } from '@objectstack/spec/contracts';
import { isMatchAllCriteria, SharingCriteriaValidationError, SharingRuleObjectNotEnforcedError } from './rule-criteria.js';
import { optionLabelCriteriaRefusal, sameCriteria, type OptionLabelSchemaSource } from './rule-criteria-option-label.js';
import type { SharingService } from './sharing-service.js';
import { isSummaryRecomputeRefusal, validationFailure } from '@objectstack/types';
import {
Expand Down Expand Up @@ -463,8 +464,21 @@ export function unbindAllRuleHooks(engine: MinimalEngine): number {
* names the offending shape instead of saying "required". Defense in depth on
* the null cases costs one property check and keeps this guard's better
* message on paths where hooks fire before validation.
*
* [#39434] The same guard refuses a criteria that compares a choice field with
* one of its option LABELS where the records hold the value
* ({@link optionLabelCriteriaRefusal}, `defineRule`'s own sentence):
* `VALIDATION_FAILED` under `criteria_json`. Judged on an insert, and on an
* update only when the supplied criteria differs from the stored one, so a
* rule saved with a label can still be switched off. Like the match-all check
* above it, and unlike the object and recipient guards, it judges system
* writes too: what it refuses depends on the criteria alone, never on who
* writes it, and `defineRule` makes the same check for every caller.
*/
export function bindRuleCriteriaGuard(engine: MinimalEngine, logger?: MinimalLogger): void {
export function bindRuleCriteriaGuard(
engine: MinimalEngine & OptionLabelSchemaSource,
logger?: MinimalLogger,
): void {
if (typeof engine.registerHook !== 'function') return;
if (typeof engine.unregisterHooksByPackage === 'function') {
engine.unregisterHooksByPackage(RULE_CRITERIA_GUARD_PACKAGE);
Expand All @@ -474,8 +488,16 @@ export function bindRuleCriteriaGuard(engine: MinimalEngine, logger?: MinimalLog
if (!data || typeof data !== 'object' || Array.isArray(data)) return;
const supplied = Object.prototype.hasOwnProperty.call(data, 'criteria_json');
if (!insert && !supplied) return;
if (!isMatchAllCriteria(data.criteria_json)) return;
throw new SharingCriteriaValidationError();
if (isMatchAllCriteria(data.criteria_json)) throw new SharingCriteriaValidationError();
const previous = !insert && ctx?.previous && typeof ctx.previous === 'object'
? ctx.previous as Record<string, unknown>
: undefined;
if (previous && sameCriteria(previous.criteria_json, data.criteria_json)) return;
const object = data.object_name !== undefined ? data.object_name : previous?.object_name;
const refusal = optionLabelCriteriaRefusal(engine, object, data.criteria_json);
if (refusal) {
throw validationFailure(refusal, [{ field: 'criteria_json', code: 'invalid_option', message: refusal }]);
}
};
const opts = { object: 'sys_sharing_rule', packageId: RULE_CRITERIA_GUARD_PACKAGE, priority: 100 };
engine.registerHook('beforeInsert', guard(true), opts);
Expand Down
Loading
Loading