Skip to content

Commit 6177223

Browse files
committed
Merge the parked caller-read reference work (60e4002) onto fresh main
The parked implementation edited engine.ts bodies that main has since moved into facets: the reference-check docblock now lives in engine-referential-integrity.ts and the caller-readable reference helper in engine-references-and-master-detail.ts. The resolution keeps main's layout and applies the parked change where the code now lives. Claude-Session: https://claude.ai/code/session_01Utp6CYQjMkN514R78sCrTT Co-authored-by: Claude <noreply@anthropic.com>
2 parents 2ffdb64 + 60e4002 commit 6177223

8 files changed

Lines changed: 418 additions & 59 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql)!: a non-system write may name, in a `lookup` or `user` field, only a record the caller can read (#29029)
6+
7+
Clause-②: yes (narrowing) — a non-system write whose `lookup` or `user` value names a record the caller's own read door does not return is refused with `reference_not_found`, which it admitted before. Nothing is widened.
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export or type changes: the reference check the write already runs for a master_detail header now runs for lookup and user values too. The refusal is the engine's own localized reference_not_found, so there is nothing for a migration to rewrite and no tombstone. -->
11+
12+
**BREAKING** accept-set narrowing at the write's reference check (`@objectstack/objectql`), served by every write door (REST, MCP, flows run as the user, `ctx.api` in hooks).
13+
14+
After the upgrade, an insert or update that carries no `isSystem` is refused when a `lookup` or `user` value it supplies names a record the caller cannot read: the answer is `400 VALIDATION_FAILED` with the field's `reference_not_found`, localized, exactly the answer for a record that exists nowhere. This is the rule `master_detail` already follows.
15+
16+
- **Each value is judged.** A multi-valued `lookup` or `user` field is refused when any one of its values names a record the caller cannot read.
17+
- **Unchanged.** System writes (`isSystem`: seed replay, boot, package install) stay exempt, as before; a flow run's elevated write keeps its existence check. An update that carries back a value the row already stores is not judged again. An empty value is not a reference. A `readonly` field is not the caller's to answer for. A `tree` parent keeps the existence check alone.
18+
- **Who sees it.** An app whose users write a reference to a record their own access does not return. A user can still reference every record they can read.
19+
20+
**The remedy.** None for an app that meant its read access as the boundary. An app that wrote its own `beforeInsert` / `beforeUpdate` hook to refuse a reference to an unreadable record can delete it: the engine now refuses it, localized. A flow that must link records the acting user cannot read runs with `runAs: 'system'`.

‎packages/objectql/src/engine-predicate-related-master-detail-header.test.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ const LOOKUP_LINE_OBJECT = {
8787
label: 'Lookup line',
8888
fields: {
8989
invoice_ref: { name: 'invoice_ref', label: 'Invoice', type: 'lookup', reference: HEADER },
90+
memo: { name: 'memo', label: 'Memo', type: 'text' },
9091
},
9192
validations: [{
9293
name: 'no_refs_to_locked', type: 'script', severity: 'error',
@@ -368,10 +369,15 @@ describe('[#22892] a predicate rule reading its master through the master-detail
368369
});
369370

370371
it('a plain lookup traversal to the same object is unchanged: the header\'s stored state is judged, and no read door is asked', async () => {
371-
const err = await refusalOf(() => engine.insert(LOOKUP_LINE, { invoice_ref: 'h_other_locked' }, { context: ALICE } as any));
372+
// [#29029] A non-system write may no longer NAME a header the caller
373+
// cannot read through a lookup either, so the rows that already store
374+
// one are seeded and the write edits another column of them.
375+
storeFor(LOOKUP_LINE).set('ll_locked', { id: 'll_locked', invoice_ref: 'h_other_locked', memo: 'a' });
376+
storeFor(LOOKUP_LINE).set('ll_open', { id: 'll_open', invoice_ref: 'h_other_open', memo: 'a' });
377+
const err = await refusalOf(() => engine.update(LOOKUP_LINE, { memo: 'b' }, { where: { id: 'll_locked' }, context: ALICE } as any));
372378
expectRuleVerdict(answerOf(err, 'h_other_locked'));
373-
await engine.insert(LOOKUP_LINE, { invoice_ref: 'h_other_open' }, { context: ALICE } as any);
374-
expect([...storeFor(LOOKUP_LINE).values()].map((r) => r.invoice_ref)).toEqual(['h_other_open']);
379+
await engine.update(LOOKUP_LINE, { memo: 'b' }, { where: { id: 'll_open' }, context: ALICE } as any);
380+
expect([...storeFor(LOOKUP_LINE).values()].map((r) => [r.invoice_ref, r.memo])).toEqual([['h_other_locked', 'a'], ['h_other_open', 'b']]);
375381
expect(headerReads.length).toBeGreaterThan(0);
376382
expect(headerReads.filter((r) => !r.elevated)).toEqual([]);
377383
});

‎packages/objectql/src/engine-predicate-relationship.test.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,14 @@ describe('#18682 — engine-produced relationship bindings', () => {
138138
d.storeFor('crm_account').set('acc_empty', { id: 'acc_empty', name: 'E', secret: 's' });
139139
});
140140

141-
const relatedReads = () => d.calls.filter((c) => c.object === 'crm_account');
141+
// [#29029] The write's reference check asks the caller's read door for each
142+
// lookup value it names, projected to `id` alone: that read is the
143+
// reference check's, not a rule's related read, so it is not counted here.
144+
const isReferenceCheckRead = (c: { ast: any }) => {
145+
const fields = c.ast?.fields;
146+
return Array.isArray(fields) && fields.length === 1 && fields[0] === 'id';
147+
};
148+
const relatedReads = () => d.calls.filter((c) => c.object === 'crm_account' && !isReferenceCheckRead(c));
142149

143150
it('projects id plus only the fields the rules name — not the whole row', async () => {
144151
await engine.insert('crm_opportunity', { name: 'A', amount: 10, account: 'acc_d' }, { context: ACTING } as any);
@@ -488,7 +495,7 @@ describe('#18682 — engine-produced relationship bindings', () => {
488495
} as any, 'test-package');
489496
d.calls.length = 0;
490497
await engine.insert('plain', { name: 'A', account: 'acc_p' }, { context: ACTING } as any);
491-
expect(d.calls.filter((c) => c.object === 'crm_account')).toHaveLength(0);
498+
expect(relatedReads()).toHaveLength(0);
492499
});
493500
});
494501

‎packages/objectql/src/engine-references-and-master-detail.ts‎

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* section of `ObjectQL`: the bodies of `setRealtimeService`, `setI18nService`,
77
* `setHomeLocalizationResolver`, `homeAmountOrganizationOf`,
88
* `previewHomeAmounts`, `projectHomeAmountsOntoPatch`, `referenceExists`,
9-
* `masterDetailHeaderExists`, `resolveMasterDetailParent`,
9+
* `callerReadableReferenceExists`, `resolveMasterDetailParent`,
1010
* `resolveMasterDetailParents`, `materializeParentHeader`,
1111
* `masterDeclaredFields`, `inspectDanglingReferences`, `inspectCascadeDelete`,
1212
* `getCascadeDeleteObjects` moved out of `engine.ts` whole by
@@ -204,25 +204,33 @@ export class ReferencesAndMasterDetailFacet {
204204
}
205205

206206
/**
207-
* [#22519] The write's reference check for a `master_detail` field: does `id`
208-
* name a header THIS CALLER can read? The write's two header reads, as
209-
* {@link resolveMasterDetailParent} reads them: the caller's read door
210-
* ({@link masterDetailHeadersCallerReads}), then the elevated, tenant-kept
211-
* {@link referenceExists} for a header it returned. A header the read door
212-
* does not return is `false` — `reference_not_found`, exactly as a header
213-
* that exists nowhere.
207+
* [#22519, #29029] The write's reference check for a `master_detail`,
208+
* `lookup` or `user` field: does `id` name a row THIS CALLER can read? The
209+
* two reads {@link resolveMasterDetailParent} reads a header with: the
210+
* caller's read door ({@link masterDetailHeadersCallerReads}), then the
211+
* elevated, tenant-kept {@link referenceExists} for a row it returned. A row
212+
* the read door does not return is `false` — `reference_not_found`, exactly
213+
* as a row that exists nowhere.
214214
*
215215
* `null` (fail-open) only where {@link referenceExists} answers it, and for
216-
* an unregistered master, which has no read door to ask either. A SYSTEM
217-
* caller reaches it only as a flow run's elevated write, or a write that
218-
* write sets off (#28881): its read door returns every header
219-
* ({@link masterDetailHeadersCallerReads}), so the header's existence in the
216+
* an unresolvable or unregistered target, which has no read door to ask
217+
* either. A SYSTEM caller reaches it only as a flow run's elevated write, or
218+
* a write that write sets off (#28881): its read door returns every row
219+
* ({@link masterDetailHeadersCallerReads}), so the row's existence in the
220220
* caller's tenant is what is asked.
221221
*
222-
* ⛔ `master_detail` only — the plain `lookup` probe is not this rule's.
222+
* ⛔ Not `tree` — its value keeps the elevated existence probe alone.
223223
*/
224-
static async masterDetailHeaderExists(this: Pick<ReferencesAndMasterDetailHost, '_registry' | 'masterDetailHeadersCallerReads' | 'referenceExists' | 'resolveObjectName'>, target: string, id: unknown, context: ExecutionContext | undefined): Promise<boolean | null> {
225-
const master = this.resolveObjectName(target);
224+
static async callerReadableReferenceExists(this: Pick<ReferencesAndMasterDetailHost, '_registry' | 'masterDetailHeadersCallerReads' | 'referenceExists' | 'resolveObjectName'>, target: string, id: unknown, context: ExecutionContext | undefined): Promise<boolean | null> {
225+
// [#29029] An unresolvable target fails open here exactly as it does in
226+
// {@link referenceExists}: an integrity check that cannot run invents no
227+
// rejection.
228+
let master: string;
229+
try {
230+
master = this.resolveObjectName(target);
231+
} catch {
232+
return null;
233+
}
226234
if (!this._registry.getObject(master)) return null;
227235
const readable = await this.masterDetailHeadersCallerReads(master, [id], context);
228236
if (!readable.has(String(id))) return false;
@@ -261,7 +269,7 @@ export class ReferencesAndMasterDetailFacet {
261269
* not return binds as a missing header binds: `null`, so a parent-scoped
262270
* `requiredWhen` / `readonlyWhen` meets an unbound `parent`, and the
263271
* reference check answers `reference_not_found` for it
264-
* ({@link masterDetailHeaderExists}).
272+
* ({@link callerReadableReferenceExists}).
265273
* 2. WHAT THE HEADER HOLDS — the write's own ELEVATED read below, for a
266274
* header read 1 returned only. The lock is a data-integrity property of
267275
* the header's state, so a header the caller can read is judged on its

‎packages/objectql/src/engine-referential-integrity.ts‎

Lines changed: 47 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
* that call a module helper `engine.ts` still needs elsewhere
2525
* (`settleMasterDetailLanding`, `resolvePreviewParents`,
2626
* `resolvePredicateRelated`, `resolveOneHopRelated`); and
27-
* `masterDetailHeaderExists`, `materializeParentHeader` and
27+
* `callerReadableReferenceExists`, `materializeParentHeader` and
2828
* `masterDeclaredFields`, whose bodies are no longer than the host literal
2929
* moving them would cost.
3030
*
@@ -36,7 +36,7 @@
3636
* literal of exactly the {@link ReferentialIntegrityHost} members that method
3737
* reads, plus a `.call`. The one field a body reads (`logger`) goes as a
3838
* GETTER, so the read happens when the body makes it, as it did. The methods
39-
* they call (`find`, `masterDetailHeaderExists`, `referenceExists`) go as
39+
* they call (`find`, `callerReadableReferenceExists`, `referenceExists`) go as
4040
* late-bound closures over the instance, so a double or spy set on the engine
4141
* is still the one a call reaches.
4242
*
@@ -67,7 +67,7 @@ import type { ObjectQL } from './engine.js';
6767
export interface ReferentialIntegrityHost {
6868
readonly logger: ObjectQL['logger'];
6969
find: ObjectQL['find'];
70-
masterDetailHeaderExists: ObjectQL['masterDetailHeaderExists'];
70+
callerReadableReferenceExists: ObjectQL['callerReadableReferenceExists'];
7171
referenceExists: ObjectQL['referenceExists'];
7272
}
7373

@@ -84,6 +84,17 @@ function isEmptyReferenceValue(v: unknown): boolean {
8484
return false;
8585
}
8686

87+
/**
88+
* [#29029] The reference types whose target a non-system write may name only
89+
* when the caller's own read door returns it: `master_detail` (#22519), and
90+
* `lookup` and `user` with it. A target the caller cannot read answers
91+
* `reference_not_found`, exactly as a target that exists nowhere. `tree`, the
92+
* one other reference type, keeps the elevated existence probe: the rulings
93+
* that tightened this set (records 6573561091 and 6663849489) name `lookup`
94+
* and `user` only.
95+
*/
96+
const CALLER_READ_REFERENCE_TYPES: ReadonlySet<string> = new Set(['master_detail', 'lookup', 'user']);
97+
8798
/**
8899
* [#4441] Referential integrity on the WRITE path: a `lookup` (or any
89100
* reference-typed field) may not be given an id that exists in no row of the
@@ -140,15 +151,14 @@ function isEmptyReferenceValue(v: unknown): boolean {
140151
* to answer for. A value new to any of the rows is refused as before, and
141152
* an insert has no stored rows, so every value it supplies is judged.
142153
*
143-
* ## Why the probe bypasses RLS — and why it keeps the tenant wall
154+
* ## Why the existence probe bypasses RLS — and why it keeps the tenant wall
144155
*
145156
* Existence is a fact about the database, not about the caller's ROW-LEVEL
146-
* visibility — the same distinction the #4435 existence probe turns on. A
147-
* probe under the caller's own context would refuse a link to a permission
148-
* set the caller cannot READ, which is ordinary in an RLS-scoped deployment
149-
* and would make the platform's own admin flows fail. Whether the caller may
150-
* create the binding at all is the RBAC/RLS layer's decision, made where it
151-
* already is. So the probe is elevated: `isSystem` bypasses RBAC, RLS and FLS.
157+
* visibility — the same distinction the #4435 existence probe turns on. So
158+
* the existence probe ({@link referenceExists}) is elevated: `isSystem`
159+
* bypasses RBAC, RLS and FLS. Whether a NON-system caller may name the row is
160+
* the separate question the next section answers, and it is asked first, of
161+
* the caller's own read door, for every reference type but `tree`.
152162
*
153163
* That argument is about visibility, never about TENANCY, and the elevation
154164
* is therefore `sudo()`-shaped — `{ ...context, isSystem: true }`, see
@@ -167,28 +177,37 @@ function isEmptyReferenceValue(v: unknown): boolean {
167177
* tenant's (ADR-0131 D1): the driver's scope is the organization equality,
168178
* with no `IS NULL` arm, so an org-bound caller's probe does not find one.
169179
*
170-
* ## …except a master-detail header, which the caller must be able to read (#22519)
180+
* ## A non-system caller may name only a row its own read door returns (#22519, #29029)
171181
*
172-
* A `master_detail` field names the detail's HEADER, and a write of a detail
173-
* whose header the caller cannot read answers exactly what a write naming a
174-
* header that exists nowhere answers. Nothing upstream of this check settles
175-
* that: ADR-0055 §3 gates a detail write on its header (master edit) only for
176-
* a `controlled_by_parent` detail, so an elevated probe alone would tell such
177-
* a caller "exists" apart from "exists nowhere". So for a `master_detail`
178-
* field the caller's read door is asked first ({@link masterDetailHeaderExists}),
179-
* and a header it does not return is `reference_not_found`. ⛔ A plain
180-
* `lookup` keeps the elevated probe above, unchanged.
182+
* A `master_detail`, `lookup` or `user` value a non-system caller supplies
183+
* must name a row the caller's own read door returns; a write naming a row
184+
* the caller cannot read answers exactly what a write naming a row that
185+
* exists nowhere answers: `reference_not_found`. So for those three types the
186+
* caller's read door is asked first ({@link callerReadableReferenceExists}),
187+
* then the elevated, tenant-kept existence probe for a row it returned. A
188+
* multi-valued field is judged per member: one unreadable member refuses the
189+
* write. Nothing upstream of this check settles it: ADR-0055 §3 gates a
190+
* detail write on its header (master edit) only for a `controlled_by_parent`
191+
* detail, and nothing gates a lookup on its target, so an elevated probe
192+
* alone would let a caller bind its row to a row it has no access to, and
193+
* tell "exists" apart from "exists nowhere". #22519 (ruling A) set the rule
194+
* for `master_detail`; ruling records 6573561091 and 6663849489 extended it
195+
* to `lookup` and `user` as the default, with no field-level opt-out. A
196+
* system caller keeps the exemption above (its read door returns every row),
197+
* and a value the row already stores is not judged again (#29062). `tree`
198+
* keeps the elevated probe alone.
181199
*
182200
* Fails OPEN when the target cannot be checked (unregistered object, no
183201
* driver, a probe that throws): an integrity check that cannot run must not
184202
* invent a rejection, and the alternative — refusing every write to an object
185203
* whose target lives on an unreachable datasource — converts a connectivity
186-
* problem into data loss. A master-detail header's read door that fails is
187-
* the exception: it did not return the header, so the header is missing
204+
* problem into data loss. A caller's read door that fails is the exception:
205+
* it did not return the row, so the row is missing for that caller, for a
206+
* `master_detail`, `lookup` or `user` value alike
188207
* (see {@link masterDetailHeadersCallerReads}).
189208
*/
190209
export async function assertReferencesResolve(
191-
this: Pick<ReferentialIntegrityHost, 'masterDetailHeaderExists' | 'referenceExists'>,
210+
this: Pick<ReferentialIntegrityHost, 'callerReadableReferenceExists' | 'referenceExists'>,
192211
schema: any,
193212
data: Record<string, unknown> | null | undefined,
194213
supplied: Record<string, unknown> | null | undefined,
@@ -259,9 +278,10 @@ export async function assertReferencesResolve(
259278
for (const v of values) {
260279
if (v === null || v === undefined || v === '') continue;
261280
if (typeof v === 'object') continue;
262-
// [#22519] A master-detail header must also be one the caller can read.
263-
const resolved = def?.type === 'master_detail'
264-
? await this.masterDetailHeaderExists(target, v, context)
281+
// [#22519, #29029] A master-detail header, a lookup target and a user
282+
// must also be one the caller can read.
283+
const resolved = CALLER_READ_REFERENCE_TYPES.has(def?.type)
284+
? await this.callerReadableReferenceExists(target, v, context)
265285
: await this.referenceExists(target, v, context);
266286
if (resolved === false) refused.push({ name, def, value: v, target });
267287
}
@@ -316,7 +336,7 @@ function storedReferenceIds(value: unknown): ReadonlySet<string> {
316336
*
317337
* A header it does not return binds as a header that exists nowhere binds:
318338
* the reference check answers `reference_not_found` for it
319-
* ({@link masterDetailHeaderExists}), and the write's header resolution
339+
* ({@link callerReadableReferenceExists}), and the write's header resolution
320340
* leaves `parent` unbound for it ({@link resolveMasterDetailParent},
321341
* {@link resolveMasterDetailParents}). A read that fails — a refusal of the
322342
* read itself included — returned no header, so every header binds as

0 commit comments

Comments
 (0)