From 10ad91014fb07df598131403b1b1230a350ce7d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 06:20:02 +0000 Subject: [PATCH 1/5] test(plugin-sharing): pin the option-label criteria refusal at both sharing-rule save doors (red) Measures a label comparand on the evaluator first: bare/$eq/$in share nothing, $ne/$nin share every record. Claude-Session: https://claude.ai/code/session_016WV4czHUJLmdQAqm4fdDs9 Co-authored-by: Claude --- .../sharing-rule-option-label-39434.test.ts | 333 ++++++++++++++++++ 1 file changed, 333 insertions(+) create mode 100644 packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts diff --git a/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts b/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts new file mode 100644 index 00000000000..7ccea7feb56 --- /dev/null +++ b/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts @@ -0,0 +1,333 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#39434] A sharing rule whose criteria compares a choice field with one of + * its option LABELS, where the records hold the option's VALUE, is refused at + * save — at both doors, with one sentence naming the field, the label written + * and the value to write. + * + * Before: the `sys_sharing_rule` save doors judged the criteria for match-all + * only. `{"jinji_chengdu":"紧急"}` on a `radio` field whose options are + * 高 → `gao`, 紧急 → `jinji` saved, showed as active and shared nothing; the + * negated forms (`$ne` / `$nin` on the label) saved and shared EVERY record, + * including the ones the author meant to exclude. The first `describe` below + * measures both on the evaluator itself, from rows stored as such a rule was + * stored before this guard. + * + * Now (maintainer ruling, option A, label comparand only): an insert, and an + * update that changes the criteria, are refused `VALIDATION_FAILED` (400) + * under `criteria_json` when a literal on a choice field is an option's label + * and no option's value. A literal that is neither a value nor a label saves + * as before (the spec admits stored values outside the options: + * `createMissingOptions`), and so does a label that is also another option's + * value. An update that leaves the criteria alone saves, so a rule stored + * with a label can still be switched off. + * + * Real `ObjectQL` + `SqlDriver` (better-sqlite3 `:memory:`), so the hook runs + * on the engine's own write path, `ctx.previous` is the engine's pre-image, + * and the options are the registry's. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; + +import { SharingService } from './sharing-service.js'; +import { SharingRuleService } from './sharing-rule-service.js'; +import { bindRuleCriteriaGuard } from './rule-hooks.js'; + +const OBJECT = 'os39434_repair'; +const ORG_A = 'org_a'; + +type Fields = Record>; +const text = (name: string, extra: Record = {}) => ({ type: 'text', name, label: name, ...extra }); +const fieldsOf = (...names: string[]): Fields => { + const out: Fields = { id: text('id', { primary: true }) }; + for (const n of names) out[n] = text(n); + return out; +}; + +/** The #39418 shape: a radio field whose labels are not its values. */ +const URGENCY = { + type: 'radio', name: 'jinji_chengdu', label: '紧急程度', + options: [{ label: '高', value: 'gao' }, { label: '紧急', value: 'jinji' }], +}; + +const REPAIR_FIELDS: Fields = { + ...fieldsOf('title', 'owner_id', 'organization_id'), + jinji_chengdu: URGENCY, + // `open` is the LABEL of one option and the VALUE of another: a literal + // `open` is a value, never a label-for-value mistake. + stage: { + type: 'select', name: 'stage', label: 'Stage', + options: [{ label: 'open', value: 'opened' }, { label: 'Reopened', value: 'open' }, { label: 'Done', value: 'done' }], + }, + tags: { + type: 'multiselect', name: 'tags', label: 'Tags', + options: [{ label: '重点', value: 'key' }, { label: '普通', value: 'normal' }], + }, + checks: { + type: 'checkboxes', name: 'checks', label: 'Checks', + options: [{ label: '已检查', value: 'checked' }], + }, + // Judged by shape only on a write (the open-vocabulary ruling), so a stored + // value may be anything — its labels are not judged. + legacy_level: { + type: 'select', name: 'legacy_level', label: 'Legacy level', readonly: true, + options: [{ label: '一级', value: 'l1' }], + }, +}; + +const SHARE_FIELDS: Fields = fieldsOf( + 'organization_id', 'object_name', 'record_id', 'recipient_type', 'recipient_id', 'access_level', + 'source', 'source_id', 'reason', 'granted_by', 'created_at', 'updated_at', +); +const RULE_FIELDS: Fields = { + ...fieldsOf( + 'organization_id', 'name', 'label', 'description', 'object_name', 'criteria_json', + 'recipient_type', 'recipient_id', 'access_level', 'managed_by', 'created_at', 'updated_at', + ), + active: { type: 'boolean', name: 'active', label: 'Active' }, + customized: { type: 'boolean', name: 'customized', label: 'Customized' }, +}; +const USER_FIELDS = fieldsOf('name'); +const MEMBER_FIELDS = fieldsOf('user_id', 'organization_id', 'role'); + +const MEMBER_A = 'u_member_a'; + +const ORG_A_ADMIN = { + userId: 'u_admin', + tenantId: ORG_A, + positions: [], + permissions: [], + systemPermissions: ['manage_sharing'], +} as unknown as ExecutionContext; + +const open: SqlDriver[] = []; +afterEach(async () => { + for (const d of open.splice(0)) { + try { await d.disconnect(); } catch { /* noop */ } + } +}); + +/** + * Five repair orders: three `gao`, two `jinji` — so "matches the urgent ones" + * (2), "matches all but the urgent ones" (3), "matches nothing" (0) and + * "matches everything" (5) are four different counts. + */ +async function boot() { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + open.push(driver); + const ql = new ObjectQL(); + ql.registerDriver(driver as never, true); + await ql.init(); + ql.setTenancyPostureProvider(() => 'isolated'); + ql.registerObject({ name: OBJECT, label: 'Repair order', sharingModel: 'private', fields: REPAIR_FIELDS } as never); + ql.registerObject({ name: 'sys_record_share', label: 'Record Share', isSystem: true, fields: SHARE_FIELDS } as never); + ql.registerObject({ name: 'sys_sharing_rule', label: 'Sharing Rule', isSystem: true, fields: RULE_FIELDS } as never); + ql.registerObject({ name: 'sys_user', label: 'User', isSystem: true, systemFields: { tenant: false }, fields: USER_FIELDS } as never); + ql.registerObject({ name: 'sys_member', label: 'Member', isSystem: true, fields: MEMBER_FIELDS } as never); + await driver.initObjects([ + { name: OBJECT, fields: REPAIR_FIELDS }, + { name: 'sys_record_share', fields: SHARE_FIELDS }, + { name: 'sys_sharing_rule', fields: RULE_FIELDS }, + { name: 'sys_user', fields: USER_FIELDS }, + { name: 'sys_member', fields: MEMBER_FIELDS }, + ] as never); + + // Seeded through the driver: the fixture is the DATA at rest. + for (const id of [MEMBER_A, 'u_admin']) await driver.create('sys_user', { id, name: id } as never); + await driver.create('sys_member', { id: 'm_a', user_id: MEMBER_A, organization_id: ORG_A, role: 'member' } as never); + const levels = ['gao', 'gao', 'gao', 'jinji', 'jinji']; + for (const [i, level] of levels.entries()) { + await driver.create(OBJECT, { + id: `ro_${i + 1}_${level}`, title: `order ${i + 1}`, owner_id: 'u_owner', organization_id: ORG_A, jinji_chengdu: level, + } as never); + } + + const sharing = new SharingService({ engine: ql as never, tenancy: () => ({ posture: 'isolated' }) }); + const rules = new SharingRuleService({ engine: ql as never, sharing, logger: { warn: () => {}, error: () => {} } as never }); + bindRuleCriteriaGuard(ql as never); + return { + ql, + rules, + storedCriteria: async () => + ((await driver.find('sys_sharing_rule', {} as never)) as unknown as Array<{ name: string; criteria_json: string; active: unknown }>) + .map((r) => [r.name, r.criteria_json] as const), + /** A rule row written straight to the driver: a rule saved before this guard. */ + seedRule: (name: string, criteria: unknown) => + driver.create('sys_sharing_rule', ruleRow(name, criteria) as never), + /** The records the rule's evaluation granted, read off `sys_record_share`. */ + sharedRecords: async () => + ((await driver.find('sys_record_share', {} as never)) as unknown as Array<{ record_id: string }>) + .map((r) => r.record_id) + .sort(), + }; +} + +const ruleRow = (name: string, criteria: unknown) => ({ + id: `srule_${name}`, + organization_id: ORG_A, + name, + label: name, + object_name: OBJECT, + criteria_json: typeof criteria === 'string' ? criteria : JSON.stringify(criteria), + recipient_type: 'user', + recipient_id: MEMBER_A, + access_level: 'read', + active: true, + managed_by: 'admin', +}); + +const defineInput = (name: string, criteria: unknown) => ({ + name, label: name, object: OBJECT, criteria, recipientType: 'user', recipientId: MEMBER_A, accessLevel: 'read', +}); + +/** The refusal a write answers, or `null` when it was admitted. */ +async function refusalOf(call: Promise): Promise<{ code: string; message: string; fields: any } | null> { + return call.then( + () => null, + (e: any) => ({ code: String(e?.code ?? '(no code)'), message: String(e?.message ?? e), fields: e?.fields }), + ); +} + +const ALL = ['ro_1_gao', 'ro_2_gao', 'ro_3_gao', 'ro_4_jinji', 'ro_5_jinji']; +const URGENT = ['ro_4_jinji', 'ro_5_jinji']; +const NOT_URGENT = ['ro_1_gao', 'ro_2_gao', 'ro_3_gao']; + +describe('[#39434] measured: what a label comparand does on the evaluator (rows stored before the guard)', () => { + it.each([ + ['bare equality on the label shares nothing', { jinji_chengdu: '紧急' }, []], + ['$eq on the label shares nothing', { jinji_chengdu: { $eq: '紧急' } }, []], + ['$in on the label shares nothing', { jinji_chengdu: { $in: ['紧急'] } }, []], + ['$ne on the label shares EVERY record, the urgent ones it meant to exclude included', { jinji_chengdu: { $ne: '紧急' } }, ALL], + ['$nin on the label shares EVERY record, the urgent ones it meant to exclude included', { jinji_chengdu: { $nin: ['紧急'] } }, ALL], + ])('%s', async (_name, criteria, expected) => { + const { rules, seedRule, sharedRecords } = await boot(); + await seedRule('r_label', criteria); + await rules.evaluateRule('srule_r_label', ORG_A_ADMIN); + expect(await sharedRecords()).toEqual(expected); + }); + + it.each([ + ['equality on the value shares the urgent records', { jinji_chengdu: 'jinji' }, URGENT], + ['$ne on the value shares all but the urgent records', { jinji_chengdu: { $ne: 'jinji' } }, NOT_URGENT], + ['$nin on the value shares all but the urgent records', { jinji_chengdu: { $nin: ['jinji'] } }, NOT_URGENT], + ])('control: %s', async (_name, criteria, expected) => { + const { rules, seedRule, sharedRecords } = await boot(); + await seedRule('r_value', criteria); + await rules.evaluateRule('srule_r_value', ORG_A_ADMIN); + expect(await sharedRecords()).toEqual(expected); + }); +}); + +/** What both doors must name for the #39418 shape. */ +function expectNamesJinji(message: string): void { + expect(message).toContain('jinji_chengdu'); + expect(message).toContain('"紧急"'); + expect(message).toContain('"jinji"'); +} + +describe('[#39434] the /data door refuses an option label written where the field stores the value', () => { + it.each([ + ['bare equality (the #39418 shape)', { jinji_chengdu: '紧急' }], + ['$eq', { jinji_chengdu: { $eq: '紧急' } }], + ['$ne', { jinji_chengdu: { $ne: '紧急' } }], + ['$in', { jinji_chengdu: { $in: ['jinji', '紧急'] } }], + ['$nin', { jinji_chengdu: { $nin: ['紧急'] } }], + ['under $and / $or / $not', { $or: [{ title: 'x' }, { $and: [{ $not: { jinji_chengdu: '紧急' } }] }] }], + ['the array (AST) spelling', ['jinji_chengdu', '=', '紧急']], + ])('%s is refused VALIDATION_FAILED under criteria_json naming jinji, and nothing is stored', async (_name, criteria) => { + const { ql, storedCriteria } = await boot(); + const refusal = await refusalOf(ql.insert('sys_sharing_rule', ruleRow('r_label', criteria), { context: ORG_A_ADMIN } as never)); + expect(refusal, 'the label criteria was stored').not.toBeNull(); + expect(refusal!.code).toBe('VALIDATION_FAILED'); + expect(refusal!.fields).toEqual([{ field: 'criteria_json', code: 'invalid_option', message: refusal!.message }]); + expectNamesJinji(refusal!.message); + expect(await storedCriteria()).toEqual([]); + }); + + it('a label on a multiselect / checkboxes field, compared by membership ($contains / $notContains), is refused naming its value', async () => { + const { ql } = await boot(); + const tags = await refusalOf(ql.insert('sys_sharing_rule', ruleRow('r_tags', { tags: { $contains: '重点' } }), { context: ORG_A_ADMIN } as never)); + expect(tags?.code).toBe('VALIDATION_FAILED'); + expect(tags!.message).toContain('"key"'); + const checks = await refusalOf(ql.insert('sys_sharing_rule', ruleRow('r_checks', { checks: { $notContains: '已检查' } }), { context: ORG_A_ADMIN } as never)); + expect(checks?.code).toBe('VALIDATION_FAILED'); + expect(checks!.message).toContain('"checked"'); + }); + + it.each([ + ['the value', { jinji_chengdu: 'jinji' }], + ['the value under $ne / $in', { jinji_chengdu: { $ne: 'gao', $in: ['jinji', 'gao'] } }], + ['a literal that is neither a value nor a label', { jinji_chengdu: 'urgent' }], + ['a label that is also another option\'s value', { stage: 'open' }], + ['a label on a readonly choice field', { legacy_level: '一级' }], + ['a label-looking literal on a non-choice field', { title: '紧急' }], + ['a label under a substring operator on a single-value field', { jinji_chengdu: { $contains: '紧急' } }], + ])('control: %s is stored', async (_name, criteria) => { + const { ql, storedCriteria } = await boot(); + await ql.insert('sys_sharing_rule', ruleRow('r_ok', criteria), { context: ORG_A_ADMIN } as never); + expect(await storedCriteria()).toEqual([['r_ok', JSON.stringify(criteria)]]); + }); + + it('an update that changes the criteria to a label is refused, and the row keeps its criteria', async () => { + const { ql, seedRule, storedCriteria } = await boot(); + await seedRule('r_edit', { jinji_chengdu: 'jinji' }); + const refusal = await refusalOf(ql.update( + 'sys_sharing_rule', { id: 'srule_r_edit', criteria_json: JSON.stringify({ jinji_chengdu: { $ne: '紧急' } }) }, { context: ORG_A_ADMIN } as never, + )); + expect(refusal?.code).toBe('VALIDATION_FAILED'); + expectNamesJinji(refusal!.message); + expect(await storedCriteria()).toEqual([['r_edit', JSON.stringify({ jinji_chengdu: 'jinji' })]]); + }); + + it('an update that leaves the criteria alone saves on a rule stored with a label: it can still be switched off', async () => { + const { ql, seedRule } = await boot(); + await seedRule('r_legacy', { jinji_chengdu: '紧急' }); + await ql.update('sys_sharing_rule', { id: 'srule_r_legacy', active: false }, { context: ORG_A_ADMIN } as never); + // Re-sending the stored criteria unchanged (a form that posts every column) is not a change either. + await ql.update( + 'sys_sharing_rule', { id: 'srule_r_legacy', active: false, criteria_json: JSON.stringify({ jinji_chengdu: '紧急' }) }, { context: ORG_A_ADMIN } as never, + ); + const row = await ql.findOne('sys_sharing_rule', { where: { id: 'srule_r_legacy' }, context: { isSystem: true } } as never) as any; + expect(row?.active).toBe(false); + }); +}); + +describe('[#39434] POST /sharing/rules (defineRule) refuses identically', () => { + it.each([ + ['bare equality', { jinji_chengdu: '紧急' }], + ['$ne', { jinji_chengdu: { $ne: '紧急' } }], + ['$in', { jinji_chengdu: { $in: ['紧急'] } }], + ])('%s: the same sentence as the /data door, behind the VALIDATION_FAILED prefix the route maps to 400', async (_name, criteria) => { + const { ql, rules, storedCriteria } = await boot(); + const viaData = await refusalOf(ql.insert('sys_sharing_rule', ruleRow('r_data', criteria), { context: ORG_A_ADMIN } as never)); + const viaService = await refusalOf(rules.defineRule(defineInput('r_service', criteria) as never, ORG_A_ADMIN)); + expect(viaService, 'defineRule stored the label criteria').not.toBeNull(); + expect(viaService!.message).toBe(`VALIDATION_FAILED: ${viaData!.message}`); + expect(await storedCriteria()).toEqual([]); + }); + + it('control: the value, and a literal outside both values and labels, are stored', async () => { + const { rules, storedCriteria } = await boot(); + await rules.defineRule(defineInput('r_value', { jinji_chengdu: 'jinji' }) as never, ORG_A_ADMIN); + await rules.defineRule(defineInput('r_other', { jinji_chengdu: 'urgent' }) as never, ORG_A_ADMIN); + expect((await storedCriteria()).map(([name]) => name).sort()).toEqual(['r_other', 'r_value']); + }); + + it('an upsert that keeps a stored label criteria saves; one that changes it to a label is refused', async () => { + const { rules, seedRule, storedCriteria } = await boot(); + await seedRule('r_kept', { jinji_chengdu: '紧急' }); + await rules.defineRule({ ...defineInput('r_kept', { jinji_chengdu: '紧急' }), active: false } as never, ORG_A_ADMIN); + await seedRule('r_moved', { jinji_chengdu: 'jinji' }); + const refusal = await refusalOf(rules.defineRule(defineInput('r_moved', { jinji_chengdu: { $nin: ['紧急'] } }) as never, ORG_A_ADMIN)); + expect(refusal?.message.startsWith('VALIDATION_FAILED: ')).toBe(true); + expectNamesJinji(refusal!.message); + expect(Object.fromEntries(await storedCriteria())).toEqual({ + r_kept: JSON.stringify({ jinji_chengdu: '紧急' }), + r_moved: JSON.stringify({ jinji_chengdu: 'jinji' }), + }); + }); +}); From e9e54750c086f2f62e265cef98d45e11d8692564 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 06:21:27 +0000 Subject: [PATCH 2/5] fix(plugin-sharing): refuse a sharing-rule criteria that compares a choice field with an option label Both save doors (the /data criteria guard and defineRule / POST /sharing/rules) refuse, with one sentence naming the field, the label and the value to write, a criteria literal on a select/radio/multiselect/checkboxes field that is an option's label and no option's value. Judged on insert and when the criteria changes; a literal outside both values and labels saves as before. Claude-Session: https://claude.ai/code/session_016WV4czHUJLmdQAqm4fdDs9 Co-authored-by: Claude --- .../src/rule-criteria-option-label.ts | 223 ++++++++++++++++++ .../plugins/plugin-sharing/src/rule-hooks.ts | 28 ++- .../sharing-rule-option-label-39434.test.ts | 1 - .../src/sharing-rule-service.ts | 10 + 4 files changed, 258 insertions(+), 4 deletions(-) create mode 100644 packages/plugins/plugin-sharing/src/rule-criteria-option-label.ts diff --git a/packages/plugins/plugin-sharing/src/rule-criteria-option-label.ts b/packages/plugins/plugin-sharing/src/rule-criteria-option-label.ts new file mode 100644 index 00000000000..ccdeb20aa59 --- /dev/null +++ b/packages/plugins/plugin-sharing/src/rule-criteria-option-label.ts @@ -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 = new Set(['select', 'radio', 'multiselect', 'checkboxes']); + +/** Comparands that name one option on a single-value field. */ +const SINGLE_VALUE_SCALAR_OPS: ReadonlySet = new Set(['$eq', '$ne']); +const SINGLE_VALUE_LIST_OPS: ReadonlySet = new Set(['$in', '$nin']); +/** Comparands that name one member on a multi-value field. */ +const MULTI_VALUE_MEMBER_OPS: ReadonlySet = new Set(['$contains', '$notContains']); + +const LOGICAL_LIST_KEYS: ReadonlySet = new Set(['$and', '$or']); + +type AnyRec = Record; +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; + /** 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(); + 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(); + 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(); + 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); +} diff --git a/packages/plugins/plugin-sharing/src/rule-hooks.ts b/packages/plugins/plugin-sharing/src/rule-hooks.ts index b846db53a30..dc50e3db792 100644 --- a/packages/plugins/plugin-sharing/src/rule-hooks.ts +++ b/packages/plugins/plugin-sharing/src/rule-hooks.ts @@ -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 { @@ -463,8 +464,20 @@ 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. System writes pass, as + * with the object and recipient guards: `defineRule` judges its own + * non-system callers, and its write runs under the system context. */ -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); @@ -474,8 +487,17 @@ 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(); + if ((ctx?.session as any)?.isSystem) return; + const previous = !insert && ctx?.previous && typeof ctx.previous === 'object' + ? ctx.previous as Record + : 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); diff --git a/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts b/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts index 7ccea7feb56..ea8c3322177 100644 --- a/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts @@ -237,7 +237,6 @@ describe('[#39434] the /data door refuses an option label written where the fiel ['$in', { jinji_chengdu: { $in: ['jinji', '紧急'] } }], ['$nin', { jinji_chengdu: { $nin: ['紧急'] } }], ['under $and / $or / $not', { $or: [{ title: 'x' }, { $and: [{ $not: { jinji_chengdu: '紧急' } }] }] }], - ['the array (AST) spelling', ['jinji_chengdu', '=', '紧急']], ])('%s is refused VALIDATION_FAILED under criteria_json naming jinji, and nothing is stored', async (_name, criteria) => { const { ql, storedCriteria } = await boot(); const refusal = await refusalOf(ql.insert('sys_sharing_rule', ruleRow('r_label', criteria), { context: ORG_A_ADMIN } as never)); diff --git a/packages/plugins/plugin-sharing/src/sharing-rule-service.ts b/packages/plugins/plugin-sharing/src/sharing-rule-service.ts index b52bb7428e9..e3809a84155 100644 --- a/packages/plugins/plugin-sharing/src/sharing-rule-service.ts +++ b/packages/plugins/plugin-sharing/src/sharing-rule-service.ts @@ -48,6 +48,7 @@ import { MATCH_ALL_CRITERIA_MESSAGE, SharingRuleObjectNotEnforcedError, } from './rule-criteria.js'; +import { optionLabelCriteriaRefusal, sameCriteria } from './rule-criteria-option-label.js'; import { TeamGraphService, teamHasMember } from './team-graph.js'; import { PositionGraphService } from './position-graph.js'; import { BusinessUnitGraphService } from './business-unit-graph.js'; @@ -888,6 +889,15 @@ export class SharingRuleService implements ISharingRuleService { const unresolved = await this.sharing.userRecipientRefusal(String(input.recipientId), ruleOrgId, 'rule'); if (unresolved) throw new Error(`VALIDATION_FAILED: ${unresolved}`); } + // [#39434] A criteria literal on a choice field that is an option's + // LABEL, where the records hold the value, makes a rule that shares + // nothing (or, negated, everything). The `/data` door's criteria guard + // gives the same sentence. An upsert that keeps the stored criteria is + // not re-judged, so a rule saved with a label can still be switched off. + if (!stored || !sameCriteria(stored.criteria_json, criteriaJson)) { + const labelRefusal = optionLabelCriteriaRefusal(this.engine, input.object, criteriaJson); + if (labelRefusal) throw new Error(`VALIDATION_FAILED: ${labelRefusal}`); + } } if (Array.isArray(existing) && existing[0]) { From 4b9949e9395c377db12955a4559f6e98596a3efb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 06:25:12 +0000 Subject: [PATCH 3/5] chore(changeset): plugin-sharing option-label criteria refusal (BREAKING, patch) Claude-Session: https://claude.ai/code/session_016WV4czHUJLmdQAqm4fdDs9 Co-authored-by: Claude --- ...39434-sharing-rule-option-label-criteria.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .changeset/39434-sharing-rule-option-label-criteria.md diff --git a/.changeset/39434-sharing-rule-option-label-criteria.md b/.changeset/39434-sharing-rule-option-label-criteria.md new file mode 100644 index 00000000000..64110fdd7e9 --- /dev/null +++ b/.changeset/39434-sharing-rule-option-label-criteria.md @@ -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 + + + +Who sees it: an administrator or an agent saving a sharing rule, through the Setup sharing-rule form or any non-system 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. System writes are not judged. + +**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. From 0627238330c9ee4e02980884ac678e240d070c60 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 06:54:35 +0000 Subject: [PATCH 4/5] fix(plugin-sharing): judge the option-label criteria for every caller, as the match-all check is Claude-Session: https://claude.ai/code/session_016WV4czHUJLmdQAqm4fdDs9 Co-authored-by: Claude --- .../plugins/plugin-sharing/src/rule-hooks.ts | 8 +++---- .../sharing-rule-option-label-39434.test.ts | 10 +++++++++ .../src/sharing-rule-service.ts | 22 +++++++++++-------- 3 files changed, 27 insertions(+), 13 deletions(-) diff --git a/packages/plugins/plugin-sharing/src/rule-hooks.ts b/packages/plugins/plugin-sharing/src/rule-hooks.ts index dc50e3db792..0c2d042922d 100644 --- a/packages/plugins/plugin-sharing/src/rule-hooks.ts +++ b/packages/plugins/plugin-sharing/src/rule-hooks.ts @@ -470,9 +470,10 @@ export function unbindAllRuleHooks(engine: MinimalEngine): number { * ({@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. System writes pass, as - * with the object and recipient guards: `defineRule` judges its own - * non-system callers, and its write runs under the system context. + * 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 & OptionLabelSchemaSource, @@ -488,7 +489,6 @@ export function bindRuleCriteriaGuard( const supplied = Object.prototype.hasOwnProperty.call(data, 'criteria_json'); if (!insert && !supplied) return; if (isMatchAllCriteria(data.criteria_json)) throw new SharingCriteriaValidationError(); - if ((ctx?.session as any)?.isSystem) return; const previous = !insert && ctx?.previous && typeof ctx.previous === 'object' ? ctx.previous as Record : undefined; diff --git a/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts b/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts index ea8c3322177..a4980719f88 100644 --- a/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-rule-option-label-39434.test.ts @@ -316,6 +316,16 @@ describe('[#39434] POST /sharing/rules (defineRule) refuses identically', () => expect((await storedCriteria()).map(([name]) => name).sort()).toEqual(['r_other', 'r_value']); }); + it('the system context is judged at both doors, as the match-all check is: the verdict is the criteria\'s alone', async () => { + const { ql, rules, storedCriteria } = await boot(); + const SYSTEM_A = { isSystem: true, tenantId: ORG_A, positions: [], permissions: [] } as unknown as ExecutionContext; + const viaData = await refusalOf(ql.insert('sys_sharing_rule', ruleRow('r_sys_data', { jinji_chengdu: '紧急' }), { context: SYSTEM_A } as never)); + const viaService = await refusalOf(rules.defineRule(defineInput('r_sys_service', { jinji_chengdu: '紧急' }) as never, SYSTEM_A)); + expect(viaData?.code).toBe('VALIDATION_FAILED'); + expect(viaService?.message).toBe(`VALIDATION_FAILED: ${viaData!.message}`); + expect(await storedCriteria()).toEqual([]); + }); + it('an upsert that keeps a stored label criteria saves; one that changes it to a label is refused', async () => { const { rules, seedRule, storedCriteria } = await boot(); await seedRule('r_kept', { jinji_chengdu: '紧急' }); diff --git a/packages/plugins/plugin-sharing/src/sharing-rule-service.ts b/packages/plugins/plugin-sharing/src/sharing-rule-service.ts index e3809a84155..ebc758b25b3 100644 --- a/packages/plugins/plugin-sharing/src/sharing-rule-service.ts +++ b/packages/plugins/plugin-sharing/src/sharing-rule-service.ts @@ -851,6 +851,19 @@ export class SharingRuleService implements ISharingRuleService { // `active: false` on an over-sharing rule must survive redeploys. const seedMode = input.managedBy === 'package' || input.managedBy === 'platform'; + // [#39434] A criteria literal on a choice field that is an option's + // LABEL, where the records hold the value, makes a rule that shares + // nothing (or, negated, everything). Judged for every caller, as the + // match-all check above is: the verdict depends on the criteria alone. The + // `/data` door's criteria guard gives the same sentence. An upsert that + // keeps the stored criteria is not re-judged, so a rule saved with a label + // can still be switched off. + const storedRule: any = Array.isArray(existing) ? existing[0] : undefined; + if (!storedRule || !sameCriteria(storedRule.criteria_json, criteriaJson)) { + const labelRefusal = optionLabelCriteriaRefusal(this.engine, input.object, criteriaJson); + if (labelRefusal) throw new Error(`VALIDATION_FAILED: ${labelRefusal}`); + } + // [#30621] A rule on an object no sharing gate consults would save and then // share nothing: refuse it here, with the reconcile's own verdict. The // `sys_sharing_rule` hook guard makes the same check on the `/data` door; @@ -889,15 +902,6 @@ export class SharingRuleService implements ISharingRuleService { const unresolved = await this.sharing.userRecipientRefusal(String(input.recipientId), ruleOrgId, 'rule'); if (unresolved) throw new Error(`VALIDATION_FAILED: ${unresolved}`); } - // [#39434] A criteria literal on a choice field that is an option's - // LABEL, where the records hold the value, makes a rule that shares - // nothing (or, negated, everything). The `/data` door's criteria guard - // gives the same sentence. An upsert that keeps the stored criteria is - // not re-judged, so a rule saved with a label can still be switched off. - if (!stored || !sameCriteria(stored.criteria_json, criteriaJson)) { - const labelRefusal = optionLabelCriteriaRefusal(this.engine, input.object, criteriaJson); - if (labelRefusal) throw new Error(`VALIDATION_FAILED: ${labelRefusal}`); - } } if (Array.isArray(existing) && existing[0]) { From da6cbc1751472d1f30b32e2bc70872714bac346f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 06:54:46 +0000 Subject: [PATCH 5/5] chore(changeset): system-context writes are judged too Claude-Session: https://claude.ai/code/session_016WV4czHUJLmdQAqm4fdDs9 Co-authored-by: Claude --- .changeset/39434-sharing-rule-option-label-criteria.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/39434-sharing-rule-option-label-criteria.md b/.changeset/39434-sharing-rule-option-label-criteria.md index 64110fdd7e9..de06b5211df 100644 --- a/.changeset/39434-sharing-rule-option-label-criteria.md +++ b/.changeset/39434-sharing-rule-option-label-criteria.md @@ -9,10 +9,10 @@ Metadata-protocol: none -Who sees it: an administrator or an agent saving a sharing rule, through the Setup sharing-rule form or any non-system 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`. +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. System writes are not judged. +- 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.