|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * Sharing-rule criteria normalisation + the ADR-0049 match-all guard (#3896). |
| 5 | + * |
| 6 | + * A sharing rule's `criteria` is the ONLY thing standing between a recipient |
| 7 | + * and every row of the target object: the evaluator feeds it straight to |
| 8 | + * `engine.find(object, { filter, context: SYSTEM_CTX })`. An absent or empty |
| 9 | + * predicate is therefore not "no constraint" — it is **share everything**, |
| 10 | + * which is exactly the shape `SharingRuleSchema` forbids: |
| 11 | + * |
| 12 | + * > A `condition` the compiler cannot lower … is skipped and logged — never |
| 13 | + * > seeded as a permissive match-all (ADR-0049). |
| 14 | + * |
| 15 | + * The seed path honoured that; `defineRule` (and through it |
| 16 | + * `POST {basePath}/sharing/rules`) and direct `sys_sharing_rule` writes did |
| 17 | + * not — a missing, `null`, or misspelled (`criterias`) key was stored as |
| 18 | + * `criteria_json: null` and evaluated as `{}`. These helpers are the single |
| 19 | + * definition of "this predicate constrains nothing", used by every authoring |
| 20 | + * entry (reject) and by the evaluator itself (match nothing, log) so rows |
| 21 | + * written before the gate existed cannot over-share either. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * Normalise a stored / submitted criteria value into an engine |
| 26 | + * `FilterCondition`, or `undefined` when it carries no usable predicate. |
| 27 | + * |
| 28 | + * A string is JSON-parsed; an unparsable one (most likely a CEL source typed |
| 29 | + * into the Setup textarea, which the v1 evaluator does not lower) yields |
| 30 | + * `undefined` rather than being passed through — the engine would ignore it |
| 31 | + * and match every row. |
| 32 | + */ |
| 33 | +export function parseCriteria(raw: unknown): unknown | undefined { |
| 34 | + if (raw == null || raw === '') return undefined; |
| 35 | + if (typeof raw === 'string') { |
| 36 | + const trimmed = raw.trim(); |
| 37 | + if (!trimmed) return undefined; |
| 38 | + try { |
| 39 | + return JSON.parse(trimmed); |
| 40 | + } catch { |
| 41 | + // Treat unparsable strings as opaque — most likely a CEL source |
| 42 | + // that v1's evaluator doesn't grok yet; rule will match nothing. |
| 43 | + return undefined; |
| 44 | + } |
| 45 | + } |
| 46 | + return raw; |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Does this criteria select EVERY record of its object? |
| 51 | + * |
| 52 | + * True for the shapes that reach the engine as an unconstrained filter: |
| 53 | + * missing / `null` / `''` / unparsable JSON / `{}` / `[]` / a non-object |
| 54 | + * scalar, and the empty or vacuous boolean combinators (`{ $and: [] }`, |
| 55 | + * `{ $or: [ {} ] }`). Any concrete field predicate makes it false. |
| 56 | + * |
| 57 | + * Conservative by design: it answers "could this fail open?", so an |
| 58 | + * ambiguous shape counts as match-all. Both consequences of a false positive |
| 59 | + * are safe — an authoring call is rejected with a message naming the field, |
| 60 | + * and an already-stored rule under-shares instead of over-sharing. |
| 61 | + */ |
| 62 | +export function isMatchAllCriteria(raw: unknown): boolean { |
| 63 | + const parsed = parseCriteria(raw); |
| 64 | + if (parsed == null) return true; |
| 65 | + // An array is the implicit-AND condition list: empty (or all-vacuous) |
| 66 | + // constrains nothing. |
| 67 | + if (Array.isArray(parsed)) return parsed.every((c) => isMatchAllCriteria(c)); |
| 68 | + // A scalar (`true`, a number, …) is not a predicate the engine narrows on. |
| 69 | + if (typeof parsed !== 'object') return true; |
| 70 | + |
| 71 | + const entries = Object.entries(parsed as Record<string, unknown>); |
| 72 | + if (entries.length === 0) return true; |
| 73 | + for (const [key, value] of entries) { |
| 74 | + if (key === '$and') { |
| 75 | + // AND of nothing / of vacuous branches ⇒ still everything. |
| 76 | + if (!Array.isArray(value) || value.every((c) => isMatchAllCriteria(c))) continue; |
| 77 | + return false; |
| 78 | + } |
| 79 | + if (key === '$or') { |
| 80 | + // OR is match-all as soon as ONE branch is; an empty OR has no |
| 81 | + // portable meaning, so treat it as unconstrained too. |
| 82 | + if (!Array.isArray(value) || value.length === 0 || value.some((c) => isMatchAllCriteria(c))) continue; |
| 83 | + return false; |
| 84 | + } |
| 85 | + // A named field predicate — this narrows the result set. |
| 86 | + return false; |
| 87 | + } |
| 88 | + return true; |
| 89 | +} |
| 90 | + |
| 91 | +/** |
| 92 | + * The authoring rejection message. Names the offending shape rather than just |
| 93 | + * "required": the reported trigger (#3896) was a typo — `criterias` instead of |
| 94 | + * `criteria` — which a bare "field missing" would not explain. |
| 95 | + */ |
| 96 | +export const MATCH_ALL_CRITERIA_MESSAGE = |
| 97 | + 'criteria is required and must narrow the records it shares — missing, empty, ' + |
| 98 | + 'or unparsable criteria would share every record of the object, which a sharing ' + |
| 99 | + 'rule must never do (ADR-0049). Check for a misspelled key (e.g. `criterias`).'; |
| 100 | + |
| 101 | +/** |
| 102 | + * Field-level rejection for the data-API path. |
| 103 | + * |
| 104 | + * Structurally what `@objectstack/objectql`'s `ValidationError` is — REST maps |
| 105 | + * on `code === 'VALIDATION_FAILED' || name === 'ValidationError'` and forwards |
| 106 | + * `fields[]` — but declared locally so a security guard in a plugin never |
| 107 | + * depends on another package's build output at runtime. |
| 108 | + */ |
| 109 | +export class SharingCriteriaValidationError extends Error { |
| 110 | + readonly code = 'VALIDATION_FAILED'; |
| 111 | + readonly fields: Array<{ field: string; code: string; message: string }>; |
| 112 | + constructor(field = 'criteria_json', message = MATCH_ALL_CRITERIA_MESSAGE) { |
| 113 | + super(message); |
| 114 | + this.name = 'ValidationError'; |
| 115 | + this.fields = [{ field, code: 'required', message }]; |
| 116 | + } |
| 117 | +} |
0 commit comments