Skip to content

Commit 73011af

Browse files
committed
fix(objectql)!: a non-system lookup or user write names only a record the caller can read
The write's reference check now asks the caller's own read door for every `lookup` and `user` value a non-system caller supplies, exactly as it already did for a `master_detail` header: a target the read door does not return answers `reference_not_found`, the answer of a target that exists nowhere. System writes keep their exemption; a value the row already stores is not judged again. Claude-Session: https://claude.ai/code/session_01ADHkmSZhbvtSoFM7YTkq6B Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2f7977c commit 73011af

4 files changed

Lines changed: 364 additions & 48 deletions

File tree

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

Lines changed: 18 additions & 7 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
*
@@ -62,7 +62,7 @@ import type { ObjectQL } from './engine.js';
6262
export interface ReferentialIntegrityHost {
6363
readonly logger: ObjectQL['logger'];
6464
find: ObjectQL['find'];
65-
masterDetailHeaderExists: ObjectQL['masterDetailHeaderExists'];
65+
callerReadableReferenceExists: ObjectQL['callerReadableReferenceExists'];
6666
referenceExists: ObjectQL['referenceExists'];
6767
}
6868

@@ -79,9 +79,19 @@ function isEmptyReferenceValue(v: unknown): boolean {
7979
return false;
8080
}
8181

82+
/**
83+
* [#29029] The reference types whose target a non-system write may name only
84+
* when the caller's own read door returns it: `master_detail` (#22519), and
85+
* `lookup` and `user` with it. A target the caller cannot read answers
86+
* `reference_not_found`, exactly as a target that exists nowhere. `tree`, the
87+
* one other reference type, keeps the elevated existence probe: the ruling
88+
* that tightened this set (record 6573561091) names `lookup` and `user` only.
89+
*/
90+
const CALLER_READ_REFERENCE_TYPES: ReadonlySet<string> = new Set(['master_detail', 'lookup', 'user']);
91+
8292
/** The body of `ObjectQL#assertReferencesResolve`; the method's docblock there is its contract. */
8393
export async function assertReferencesResolve(
84-
this: Pick<ReferentialIntegrityHost, 'masterDetailHeaderExists' | 'referenceExists'>,
94+
this: Pick<ReferentialIntegrityHost, 'callerReadableReferenceExists' | 'referenceExists'>,
8595
schema: any,
8696
data: Record<string, unknown> | null | undefined,
8797
supplied: Record<string, unknown> | null | undefined,
@@ -152,9 +162,10 @@ export async function assertReferencesResolve(
152162
for (const v of values) {
153163
if (v === null || v === undefined || v === '') continue;
154164
if (typeof v === 'object') continue;
155-
// [#22519] A master-detail header must also be one the caller can read.
156-
const resolved = def?.type === 'master_detail'
157-
? await this.masterDetailHeaderExists(target, v, context)
165+
// [#22519, #29029] A master-detail header, a lookup target and a user
166+
// must also be one the caller can read.
167+
const resolved = CALLER_READ_REFERENCE_TYPES.has(def?.type)
168+
? await this.callerReadableReferenceExists(target, v, context)
158169
: await this.referenceExists(target, v, context);
159170
if (resolved === false) refused.push({ name, def, value: v, target });
160171
}

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

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,9 @@
4545
* the mechanism: the read door first, then the elevated read;
4646
* CONTROLS: a readable header unchanged (its stored values judged, a masked
4747
* column included); a nonexistent id; a `controlled_by_parent` detail
48-
* unchanged; a system caller unchanged (no read door asked); a plain `lookup`
49-
* to the same object keeps its elevated probe (not this rule's).
48+
* unchanged; a system caller unchanged (no read door asked). [#29029] A plain
49+
* `lookup` to the same object takes the same rule since ruling record
50+
* 6573561091 (its own pins: `engine-unreadable-reference-target.test.ts`).
5051
*/
5152

5253
import { describe, it, expect, beforeEach } from 'vitest';
@@ -119,7 +120,7 @@ const CBP_LINE_OBJECT = {
119120
fields: { ...REQ_LINE_OBJECT.fields, invoice: { ...invoiceField, required: true } },
120121
};
121122

122-
/** A plain `lookup` to the same object: its probe is not this rule's. */
123+
/** [#29029] A plain `lookup` to the same object: the same rule since ruling record 6573561091. */
123124
const LOOKUP_NOTE_OBJECT = {
124125
name: LOOKUP_NOTE,
125126
label: 'Lookup note',
@@ -338,13 +339,14 @@ describe('[#22519] an unreadable master-detail header answers what a nonexistent
338339
expect([...storeFor(PLAIN_LINE).values()].some((r) => r.invoice === 'h_mine_locked')).toBe(true);
339340
});
340341

341-
it('control: a plain lookup to the same object keeps its elevated probe — not this rule\'s', async () => {
342-
await engine.insert(LOOKUP_NOTE, { invoice_ref: 'h_other_open' }, { context: ALICE } as any);
343-
expect([...storeFor(LOOKUP_NOTE).values()].map((r) => r.invoice_ref)).toEqual(['h_other_open']);
342+
it('[#29029] a plain lookup to the same object takes the same rule: an unreadable target is refused as a nonexistent one is', async () => {
344343
const nowhere = await refusalOf(() => engine.insert(LOOKUP_NOTE, { invoice_ref: NOWHERE }, { context: ALICE } as any));
345344
expect(envelopeOf(nowhere)).toEqual({ ...NOT_FOUND, fields: [{ field: 'invoice_ref', code: 'reference_not_found' }] });
346-
// No read door was asked for it.
347-
expect(headerReads.filter((r) => !r.elevated)).toEqual([]);
345+
const unreadable = await refusalOf(() => engine.insert(LOOKUP_NOTE, { invoice_ref: 'h_other_open' }, { context: ALICE } as any));
346+
expect(envelopeOf(unreadable)).toEqual(envelopeOf(nowhere));
347+
expect(storeFor(LOOKUP_NOTE).size).toBe(0);
348+
// The caller's read door was asked for it.
349+
expect(headerReads.some((r) => !r.elevated)).toBe(true);
348350
});
349351
});
350352

Lines changed: 296 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,296 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29029] A non-system write may name, in a `lookup` or `user` field, only a
5+
* record the caller's own read door returns — the rule #22519 (ruling A) set
6+
* for a `master_detail` header, made the default for `lookup` and `user` by
7+
* ruling record 6573561091, with no field-level opt-out. A target the caller
8+
* cannot read answers `reference_not_found`, exactly what a target that exists
9+
* nowhere answers. A system write keeps its exemption.
10+
*
11+
* ## The rig
12+
*
13+
* A store-backed driver, and a synthetic read scope shaped like the
14+
* security/sharing middlewares (the one the #22519 pins use): a non-system
15+
* caller reads only the target rows it owns, on both target objects (a plain
16+
* object and `sys_user`). A second caller's read of either target object is
17+
* refused outright, as an object-level denial is.
18+
*
19+
* ## Pins
20+
*
21+
* - a `lookup` and a `user` value: insert, batch insert, update by id and
22+
* bulk update — a target the caller cannot read answers what a target that
23+
* exists nowhere answers (`code`, `status`, field code and the sentence);
24+
* - a refused read of the target object answers the same;
25+
* - a multi-valued field: one unreadable member refuses the whole write;
26+
* - the mechanism: the caller's read door first, then the elevated probe;
27+
* CONTROLS: a readable target lands; a system write naming an unreadable
28+
* target lands and asks no read door; an update that carries a stored value
29+
* back is not judged again (#29062), as for a `master_detail` header.
30+
*/
31+
32+
import { describe, it, expect, beforeEach } from 'vitest';
33+
import { resolveThrownHttpError } from '@objectstack/types';
34+
import { ObjectQL } from './engine.js';
35+
import { ValidationError } from './validation/record-validator.js';
36+
37+
const TARGET = 'urt_duty';
38+
const USER = 'sys_user';
39+
const ITEM = 'urt_task';
40+
41+
const ownedTarget = (name: string, label: string) => ({
42+
name,
43+
label,
44+
fields: {
45+
name: { name: 'name', label: 'Name', type: 'text' },
46+
owner_name: { name: 'owner_name', label: 'Owner', type: 'text' },
47+
},
48+
});
49+
50+
const ITEM_OBJECT = {
51+
name: ITEM,
52+
label: 'Task',
53+
fields: {
54+
title: { name: 'title', label: 'Title', type: 'text' },
55+
duty: { name: 'duty', label: 'Duty', type: 'lookup', reference: TARGET },
56+
duties: { name: 'duties', label: 'Duties', type: 'lookup', reference: TARGET, multiple: true },
57+
assignee: { name: 'assignee', label: 'Assignee', type: 'user' },
58+
watchers: { name: 'watchers', label: 'Watchers', type: 'user', multiple: true },
59+
},
60+
};
61+
62+
/** A store-backed driver: what is stored is what a later read answers. */
63+
function makeStoreDriver() {
64+
const stores = new Map<string, Map<string, Record<string, any>>>();
65+
const storeFor = (o: string) => {
66+
let s = stores.get(o);
67+
if (!s) { s = new Map(); stores.set(o, s); }
68+
return s;
69+
};
70+
const matches = (row: any, where: any): boolean => {
71+
if (!where || typeof where !== 'object') return true;
72+
return Object.entries(where).every(([k, v]: [string, any]) => {
73+
if (k === '$and') return (v as any[]).every((w) => matches(row, w));
74+
if (k.startsWith('$')) throw new Error(`store driver: unsupported combinator ${k}`);
75+
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
76+
return Object.entries(v).every(([op, target]) => {
77+
if (op === '$eq') return row?.[k] === target;
78+
if (op === '$in') return Array.isArray(target) && target.includes(row?.[k]);
79+
throw new Error(`store driver: unsupported operator ${op}`);
80+
});
81+
}
82+
return row?.[k] === v;
83+
});
84+
};
85+
let n = 0;
86+
const driver: any = {
87+
name: 'urt-store', version: '0.0.0', supports: {},
88+
async connect() {}, async disconnect() {}, async checkHealth() { return true; },
89+
async syncSchema() {},
90+
async find(o: string, ast: any) {
91+
const hits = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where));
92+
return (typeof ast?.limit === 'number' ? hits.slice(0, ast.limit) : hits).map((r) => ({ ...r }));
93+
},
94+
async findOne(o: string, ast: any) {
95+
for (const r of storeFor(o).values()) if (matches(r, ast?.where)) return { ...r };
96+
return null;
97+
},
98+
async create(o: string, data: Record<string, unknown>) {
99+
n += 1;
100+
const id = (data.id as string) ?? `rec_${n}`;
101+
const row = { ...data, id };
102+
storeFor(o).set(id, row);
103+
return { ...row };
104+
},
105+
async update(o: string, id: string, data: Record<string, unknown>) {
106+
const row = { ...storeFor(o).get(id), ...data, id };
107+
storeFor(o).set(id, row);
108+
return { ...row };
109+
},
110+
async updateMany(o: string, ast: any, data: Record<string, unknown>) {
111+
const hits = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where));
112+
for (const r of hits) storeFor(o).set(r.id, { ...r, ...data, id: r.id });
113+
return hits.length;
114+
},
115+
async delete(o: string, id: string) { return storeFor(o).delete(id); },
116+
async count(o: string, ast: any) {
117+
return Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)).length;
118+
},
119+
};
120+
return { driver, storeFor };
121+
}
122+
123+
/** The refusal an object-level read denial throws — `PermissionDeniedError`'s declared envelope. */
124+
const readRefusal = () => Object.assign(new Error('[Security] Access denied: read on the target object'), {
125+
name: 'PermissionDeniedError', code: 'PERMISSION_DENIED', status: 403, statusCode: 403,
126+
});
127+
128+
/** Every target read, with whether it ran under the caller's own context or elevated. */
129+
type TargetRead = { object: string; operation: string; elevated: boolean };
130+
131+
function makeEngine() {
132+
const store = makeStoreDriver();
133+
const engine = new ObjectQL();
134+
engine.registerDriver(store.driver, true);
135+
engine.registerApp({
136+
id: 'urt',
137+
name: 'Unreadable reference target',
138+
objects: [ownedTarget(TARGET, 'Duty'), ownedTarget(USER, 'User'), ITEM_OBJECT],
139+
} as any);
140+
const targetReads: TargetRead[] = [];
141+
engine.registerMiddleware(async (ctx: any, next: () => Promise<void>) => {
142+
if ([TARGET, USER].includes(ctx.object) && ['find', 'findOne'].includes(ctx.operation)) {
143+
const elevated = ctx.context?.isSystem === true;
144+
targetReads.push({ object: ctx.object, operation: ctx.operation, elevated });
145+
const userId = ctx.context?.userId;
146+
if (!elevated && userId === 'carol') throw readRefusal();
147+
// Read scope shaped like the security/sharing middlewares: a non-system
148+
// caller reads only the target rows it owns.
149+
if (!elevated && userId) {
150+
const scoped = { owner_name: userId };
151+
const ast: any = ctx.ast ?? { object: ctx.object };
152+
ast.where = ast.where ? { $and: [ast.where, scoped] } : scoped;
153+
ctx.ast = ast;
154+
}
155+
}
156+
await next();
157+
});
158+
for (const object of [TARGET, USER]) {
159+
const rows = store.storeFor(object);
160+
rows.set('t_mine', { id: 't_mine', name: 'mine', owner_name: 'alice' });
161+
rows.set('t_mine_2', { id: 't_mine_2', name: 'mine too', owner_name: 'alice' });
162+
rows.set('t_other', { id: 't_other', name: 'other', owner_name: 'bob' });
163+
}
164+
return { engine, targetReads, ...store };
165+
}
166+
167+
/** Alice may write every task and reads only the target rows she owns. */
168+
const ALICE = { userId: 'alice' };
169+
/** Carol's read of either target object is refused outright. */
170+
const CAROL = { userId: 'carol' };
171+
/** Seed replay / boot. */
172+
const SYSTEM = { isSystem: true, userId: 'alice' };
173+
174+
const NOWHERE = 't_nowhere';
175+
const UNREADABLE = 't_other';
176+
177+
type Envelope = { status: number; code: string; fields: Array<{ field: string; code: string }> };
178+
179+
/** The refusal as every HTTP door reads it (ADR-0112), plus its field codes. */
180+
function envelopeOf(err: unknown): Envelope {
181+
const thrown = resolveThrownHttpError(err);
182+
const fields = ((err as any)?.fields ?? []).map((f: any) => ({ field: f.field, code: f.code }));
183+
return { status: thrown.status, code: thrown.code, fields };
184+
}
185+
186+
async function refusalOf(run: () => Promise<unknown>): Promise<unknown> {
187+
try {
188+
await run();
189+
} catch (e) {
190+
return e;
191+
}
192+
throw new Error('expected the write to be refused, but it succeeded');
193+
}
194+
195+
/** The message with the target id taken out: what else a caller could compare. */
196+
const sentence = (err: unknown, id: string) => String((err as Error).message).split(id).join('ID');
197+
198+
const notFound = (field: string): Envelope => ({
199+
status: 400, code: 'VALIDATION_FAILED', fields: [{ field, code: 'reference_not_found' }],
200+
});
201+
202+
type Door = 'insert' | 'batch insert' | 'update by id' | 'bulk update';
203+
const DOORS: Door[] = ['insert', 'batch insert', 'update by id', 'bulk update'];
204+
const FIELDS = [
205+
{ field: 'duty', kind: 'lookup', target: TARGET },
206+
{ field: 'assignee', kind: 'user', target: USER },
207+
] as const;
208+
209+
describe('[#29029] a non-system lookup or user write may name only a record the caller can read', () => {
210+
let engine: ObjectQL;
211+
let targetReads: TargetRead[];
212+
let storeFor: (o: string) => Map<string, Record<string, any>>;
213+
214+
beforeEach(() => {
215+
({ engine, targetReads, storeFor } = makeEngine());
216+
storeFor(ITEM).set('k1', { id: 'k1', title: 'stored' });
217+
});
218+
219+
const write = (door: Door, payload: Record<string, unknown>, context: Record<string, unknown> = ALICE) => {
220+
if (door === 'insert') return engine.insert(ITEM, { title: 'new', ...payload }, { context } as any);
221+
if (door === 'batch insert') {
222+
return engine.insert(ITEM, [{ title: 'first' }, { title: 'second', ...payload }], { context } as any);
223+
}
224+
if (door === 'update by id') return engine.update(ITEM, payload, { where: { id: 'k1' }, context } as any);
225+
return engine.update(ITEM, payload, { where: { id: { $in: ['k1'] } }, multi: true, context } as any);
226+
};
227+
228+
const storedItems = () => [...storeFor(ITEM).values()];
229+
230+
describe.each(FIELDS)('a $kind field', ({ field }) => {
231+
it.each(DOORS)('%s — a target the caller cannot read is refused as a target that exists nowhere is', async (door) => {
232+
const nowhere = await refusalOf(() => write(door, { [field]: NOWHERE }));
233+
expect(nowhere).toBeInstanceOf(ValidationError);
234+
expect(envelopeOf(nowhere)).toEqual(notFound(field));
235+
const unreadable = await refusalOf(() => write(door, { [field]: UNREADABLE }));
236+
expect(envelopeOf(unreadable)).toEqual(notFound(field));
237+
expect(sentence(unreadable, UNREADABLE)).toBe(sentence(nowhere, NOWHERE));
238+
// Nothing written: the stored task is untouched, and no task was added.
239+
expect(storedItems()).toEqual([{ id: 'k1', title: 'stored' }]);
240+
});
241+
242+
it.each(DOORS)('%s — a refused read of the target object answers as a target that exists nowhere', async (door) => {
243+
const nowhere = envelopeOf(await refusalOf(() => write(door, { [field]: NOWHERE }, CAROL)));
244+
expect(nowhere).toEqual(notFound(field));
245+
expect(envelopeOf(await refusalOf(() => write(door, { [field]: 't_mine' }, CAROL)))).toEqual(nowhere);
246+
});
247+
248+
it.each(DOORS)('%s — control: a target the caller can read lands', async (door) => {
249+
await write(door, { [field]: 't_mine' });
250+
expect(storedItems().some((r) => r[field] === 't_mine')).toBe(true);
251+
});
252+
253+
it.each(DOORS)('%s — control: a system write naming a target the caller cannot read lands, and asks no read door', async (door) => {
254+
await write(door, { [field]: UNREADABLE }, SYSTEM);
255+
expect(storedItems().some((r) => r[field] === UNREADABLE)).toBe(true);
256+
expect(targetReads.length).toBeGreaterThan(0);
257+
expect(targetReads.filter((r) => !r.elevated)).toEqual([]);
258+
});
259+
260+
it.each(['update by id', 'bulk update'] as const)('%s — control: a stored value carried back is not judged again', async (door) => {
261+
storeFor(ITEM).set('k1', { id: 'k1', title: 'stored', [field]: UNREADABLE });
262+
await write(door, { title: 'renamed', [field]: UNREADABLE });
263+
expect(storedItems()).toEqual([{ id: 'k1', title: 'renamed', [field]: UNREADABLE }]);
264+
});
265+
266+
it('the mechanism: the caller\'s read door first, then the elevated probe', async () => {
267+
await write('insert', { [field]: 't_mine' });
268+
expect(targetReads.map(({ operation, elevated }) => ({ operation, elevated }))).toEqual([
269+
{ operation: 'find', elevated: false },
270+
{ operation: 'findOne', elevated: true },
271+
]);
272+
});
273+
});
274+
275+
describe.each([
276+
{ field: 'duties', kind: 'lookup' },
277+
{ field: 'watchers', kind: 'user' },
278+
] as const)('a multi-valued $kind field', ({ field }) => {
279+
it.each(['insert', 'update by id'] as const)('%s — one member the caller cannot read refuses the whole write', async (door) => {
280+
const err = await refusalOf(() => write(door, { [field]: ['t_mine', UNREADABLE, 't_mine_2'] }));
281+
expect(envelopeOf(err)).toEqual(notFound(field));
282+
expect(storedItems()).toEqual([{ id: 'k1', title: 'stored' }]);
283+
});
284+
285+
it.each(['insert', 'update by id'] as const)('%s — control: every member readable lands', async (door) => {
286+
await write(door, { [field]: ['t_mine', 't_mine_2'] });
287+
expect(storedItems().some((r) => Array.isArray(r[field]) && r[field].length === 2)).toBe(true);
288+
});
289+
290+
it('update — control: a stored member carried back beside a new readable one is not judged again', async () => {
291+
storeFor(ITEM).set('k1', { id: 'k1', title: 'stored', [field]: [UNREADABLE] });
292+
await write('update by id', { [field]: [UNREADABLE, 't_mine'] });
293+
expect(storeFor(ITEM).get('k1')?.[field]).toEqual([UNREADABLE, 't_mine']);
294+
});
295+
});
296+
});

0 commit comments

Comments
 (0)