Skip to content

Commit 1c9158f

Browse files
committed
test(objectql,plugin-security): the update's reference forgiveness compares only stored values the caller may read
For master_detail, lookup and user, by id and in bulk: a column the caller may edit but not read answers a value the rows store exactly as a value they do not. Controls: a caller who reads the column keeps the forgiveness, the same grant edits another column, and a system write keeps its exemption. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibvynRbCtMndW8EHNGc
1 parent 0ae1bab commit 1c9158f

2 files changed

Lines changed: 330 additions & 0 deletions

File tree

‎packages/objectql/src/engine-unreadable-reference-target.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,3 +437,64 @@ describe('[#29029] which failures of the reference check fail open, and which fa
437437
expect([...storeFor('urt_loose_task').values()].map((r) => r.loose)).toEqual(['x_1']);
438438
});
439439
});
440+
441+
/**
442+
* [#29029, #29062] The update's reference forgiveness compares only stored
443+
* values the caller may read: the stored rows as the caller's own read door
444+
* serves them. A middleware here withholds the task's reference columns from
445+
* Alice's reads of the task, as a field-level read denial does.
446+
*/
447+
describe('[#29029] the update\'s reference forgiveness compares only stored values the caller may read', () => {
448+
const HIDDEN_FROM_ALICE = ['duty', 'assignee'];
449+
let engine: ObjectQL;
450+
let storeFor: (o: string) => Map<string, Record<string, any>>;
451+
452+
const boot = (itemRead: 'hide columns' | 'fail' | 'serve') => {
453+
({ engine, storeFor } = makeEngine());
454+
engine.registerMiddleware(async (ctx: any, next: () => Promise<void>) => {
455+
const own = ctx.object === ITEM && ['find', 'findOne'].includes(ctx.operation) && ctx.context?.userId === 'alice' && !ctx.context?.isSystem;
456+
if (own && itemRead === 'fail') throw new Error('the task read failed');
457+
await next();
458+
if (own && itemRead === 'hide columns') {
459+
const strip = (row: any) => { if (row && typeof row === 'object') for (const f of HIDDEN_FROM_ALICE) delete row[f]; };
460+
if (Array.isArray(ctx.result)) ctx.result.forEach(strip); else strip(ctx.result);
461+
}
462+
});
463+
for (const id of ['k1', 'k2']) storeFor(ITEM).set(id, { id, title: 'stored', duty: UNREADABLE, assignee: UNREADABLE });
464+
};
465+
const write = (door: 'update by id' | 'bulk update', payload: Record<string, unknown>, context: Record<string, unknown> = ALICE) =>
466+
door === 'update by id'
467+
? engine.update(ITEM, payload, { where: { id: 'k1' }, context } as any)
468+
: engine.update(ITEM, payload, { where: { id: { $in: ['k1', 'k2'] } }, multi: true, context } as any);
469+
const answer = (err: unknown, id: string) => JSON.stringify({ ...envelopeOf(err), sentence: sentence(err, id) });
470+
const untouched = () => ['k1', 'k2'].map((id) => ({ id, title: 'stored', duty: UNREADABLE, assignee: UNREADABLE }));
471+
472+
describe.each(FIELDS)('a $kind column', ({ field }) => {
473+
it.each(['update by id', 'bulk update'] as const)('%s — a column the caller cannot read forgives nothing: the stored value answers as another unreadable one', async (door) => {
474+
boot('hide columns');
475+
const storedValue = await refusalOf(() => write(door, { [field]: UNREADABLE }));
476+
expect(envelopeOf(storedValue)).toEqual(notFound(field));
477+
const otherValue = await refusalOf(() => write(door, { [field]: 't_flagged_other' }));
478+
expect(answer(storedValue, UNREADABLE)).toBe(answer(otherValue, 't_flagged_other'));
479+
expect([...storeFor(ITEM).values()]).toEqual(untouched());
480+
});
481+
482+
it('update by id — a read of the stored row that fails forgives nothing', async () => {
483+
boot('fail');
484+
expect(envelopeOf(await refusalOf(() => write('update by id', { [field]: UNREADABLE })))).toEqual(notFound(field));
485+
});
486+
487+
it.each(['update by id', 'bulk update'] as const)('%s — control: a column the caller reads keeps the forgiveness', async (door) => {
488+
boot('serve');
489+
await write(door, { title: 'renamed', [field]: UNREADABLE });
490+
expect(storeFor(ITEM).get('k1')).toEqual({ id: 'k1', title: 'renamed', duty: UNREADABLE, assignee: UNREADABLE });
491+
});
492+
493+
it.each(['update by id', 'bulk update'] as const)('%s — control: a flow run\'s system write compares the rows as stored', async (door) => {
494+
boot('hide columns');
495+
const flowRun = markFlowWriteReferenceCheck({ ...SYSTEM });
496+
await write(door, { title: 'renamed', [field]: UNREADABLE }, flowRun);
497+
expect(storeFor(ITEM).get('k1')?.title).toBe('renamed');
498+
});
499+
});
500+
});
Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29029, #29062] The update's reference forgiveness compares only stored
5+
* values the caller may read.
6+
*
7+
* A non-system write may name, in a `lookup`, `user` or `master_detail`
8+
* field, only a record its caller can read; a value it cannot read answers
9+
* `reference_not_found`. An update that carries back a value the row already
10+
* stores is not judged again (#29062) — and that comparison reads the stored
11+
* row as the caller may read it. A column the caller may edit but not read
12+
* (`{ readable: false, editable: true }`, which the field-write gate admits)
13+
* holds no stored value for it, so it forgives nothing: the value is refused
14+
* like any other unreadable reference, and the answer is the same whatever
15+
* the column holds.
16+
*
17+
* ## The rig
18+
*
19+
* The real engine and the real security plugin, on a store-backed driver.
20+
* The caller may read and edit tasks and holds no read on the target object
21+
* or on `sys_user`, so every target id below is one it cannot read. Two
22+
* grants differ only in the reference columns' `readable` bit.
23+
*
24+
* ## Pins
25+
*
26+
* - for each of the three types, by id and in bulk: a column the caller may
27+
* edit but not read answers a value it already stores exactly as it
28+
* answers a value it does not (status, code, field and sentence), and the
29+
* rows are untouched;
30+
* CONTROLS: the same grant edits another column of the same rows; a caller
31+
* who can read the column keeps the forgiveness (the stored value carried
32+
* back lands) and is refused a new unreadable value; a system write keeps
33+
* its exemption.
34+
*/
35+
36+
import { describe, it, expect, vi } from 'vitest';
37+
import { ObjectQL } from '@objectstack/objectql';
38+
import { resolveThrownHttpError } from '@objectstack/types';
39+
import type { PermissionSet } from '@objectstack/spec/security';
40+
import { SecurityPlugin } from './security-plugin.js';
41+
42+
import '@objectstack/spec';
43+
import '@objectstack/formula';
44+
45+
const TARGET = 'rfc_target';
46+
const ITEM = 'rfc_item';
47+
48+
const ITEM_OBJECT = {
49+
name: ITEM,
50+
fields: {
51+
title: { type: 'text' },
52+
duty: { type: 'lookup', reference: TARGET },
53+
assignee: { type: 'user' },
54+
header: { type: 'master_detail', reference: TARGET },
55+
},
56+
};
57+
58+
const REFERENCE_FIELDS = ['duty', 'assignee', 'header'] as const;
59+
60+
/** Edits tasks, and may edit but not read their reference columns; reads no target. */
61+
const HIDDEN_COLUMNS: PermissionSet = {
62+
name: 'member_default',
63+
label: 'Task editor who may not read the reference columns',
64+
objects: { [ITEM]: { allowRead: true, allowCreate: true, allowEdit: true } },
65+
fields: Object.fromEntries(REFERENCE_FIELDS.map((f) => [`${ITEM}.${f}`, { readable: false, editable: true }])),
66+
} as unknown as PermissionSet;
67+
68+
/** The same grant with the reference columns readable. */
69+
const READABLE_COLUMNS: PermissionSet = {
70+
name: 'member_default',
71+
label: 'Task editor who may read the reference columns',
72+
objects: { [ITEM]: { allowRead: true, allowCreate: true, allowEdit: true } },
73+
fields: Object.fromEntries(REFERENCE_FIELDS.map((f) => [`${ITEM}.${f}`, { readable: true, editable: true }])),
74+
} as unknown as PermissionSet;
75+
76+
const CALLER = { userId: 'u_editor', tenantId: 'org-1', positions: [], permissions: [], posture: 'MEMBER' };
77+
const SYS_CTX = { isSystem: true, userId: 'usr_system' };
78+
79+
/** What the rows store, per field, and a second id of the same object the caller cannot read either. */
80+
const STORED: Record<(typeof REFERENCE_FIELDS)[number], string> = { duty: 't_stored', assignee: 'u_stored', header: 't_stored' };
81+
const OTHER: Record<(typeof REFERENCE_FIELDS)[number], string> = { duty: 't_other', assignee: 'u_other', header: 't_other' };
82+
83+
function makeDriver() {
84+
const stores = new Map<string, Map<string, any>>();
85+
const storeFor = (o: string) => {
86+
let s = stores.get(o);
87+
if (!s) { s = new Map(); stores.set(o, s); }
88+
return s;
89+
};
90+
const matches = (row: any, where: any): boolean => {
91+
if (!where || typeof where !== 'object') return true;
92+
return Object.entries(where).every(([k, v]: [string, any]) => {
93+
if (k === '$and') return (v as any[]).every((w) => matches(row, w));
94+
if (k === '$or') return (v as any[]).some((w) => matches(row, w));
95+
const cond = v as any;
96+
if (cond && typeof cond === 'object' && !Array.isArray(cond)) {
97+
if ('$in' in cond) return Array.isArray(cond.$in) && cond.$in.includes(row?.[k]);
98+
if ('$eq' in cond) return row?.[k] === cond.$eq;
99+
}
100+
return row?.[k] === cond;
101+
});
102+
};
103+
let n = 0;
104+
const driver: any = {
105+
name: 'memory', version: '0.0.0', supports: {},
106+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
107+
async find(object: string, ast: any) {
108+
const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where));
109+
const bounded = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
110+
const fields: string[] | undefined = ast?.fields;
111+
if (!fields) return bounded.map((r) => ({ ...r }));
112+
return bounded.map((r) => {
113+
const out: any = {};
114+
for (const f of fields) if (r[f] !== undefined) out[f] = r[f];
115+
return out;
116+
});
117+
},
118+
async findOne(object: string, ast: any) {
119+
for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r };
120+
return null;
121+
},
122+
async create(object: string, data: Record<string, unknown>) {
123+
n += 1;
124+
const id = (data.id as string) ?? `r_${n}`;
125+
const row = { ...data, id };
126+
storeFor(object).set(id, row);
127+
return { ...row };
128+
},
129+
async update(object: string, id: string, data: Record<string, unknown>) {
130+
const s = storeFor(object);
131+
const row = { ...s.get(id), ...data, id };
132+
s.set(id, row);
133+
return { ...row };
134+
},
135+
async updateMany(object: string, ast: any, data: Record<string, unknown>) {
136+
const hits = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where));
137+
for (const r of hits) storeFor(object).set(r.id, { ...r, ...data, id: r.id });
138+
return hits.length;
139+
},
140+
async delete(object: string, id: string) { return storeFor(object).delete(id); },
141+
async count(object: string, ast: any) {
142+
return Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)).length;
143+
},
144+
async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; },
145+
async commit() {}, async rollback() {},
146+
};
147+
return { driver, storeFor };
148+
}
149+
150+
async function boot(set: PermissionSet) {
151+
const engine = new ObjectQL();
152+
const d = makeDriver();
153+
engine.registerDriver(d.driver, true);
154+
await engine.init();
155+
engine.registry.registerObject({ name: TARGET, fields: { name: { type: 'text' } } } as any, 'test-package');
156+
engine.registry.registerObject({ name: 'sys_user', fields: { name: { type: 'text' }, email: { type: 'text' } } } as any, 'test-package');
157+
engine.registry.registerObject(ITEM_OBJECT as any, 'test-package');
158+
for (const id of ['t_stored', 't_other']) d.storeFor(TARGET).set(id, { id, name: id });
159+
for (const id of ['u_stored', 'u_other']) d.storeFor('sys_user').set(id, { id, name: id, email: `${id}@example.test` });
160+
161+
const services: Record<string, unknown> = {
162+
manifest: { register: vi.fn() },
163+
objectql: engine,
164+
metadata: {
165+
get: async (_type: string, name: string) => engine.getSchema(name) ?? null,
166+
list: async () => [set],
167+
},
168+
};
169+
const ctx = {
170+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
171+
registerService: vi.fn(),
172+
getService: (name: string) => {
173+
if (!(name in services)) throw new Error(`service not registered: ${name}`);
174+
return services[name];
175+
},
176+
};
177+
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
178+
await plugin.init(ctx as any);
179+
await plugin.start(ctx as any);
180+
181+
// Two tasks the caller may edit, each storing the same unreadable ids.
182+
for (const id of ['k1', 'k2']) {
183+
await engine.insert(ITEM, { id, title: 'stored', ...STORED }, { context: SYS_CTX } as any);
184+
}
185+
return { engine, storeFor: d.storeFor };
186+
}
187+
188+
type Door = 'update by id' | 'bulk update';
189+
const DOORS: Door[] = ['update by id', 'bulk update'];
190+
191+
const write = (engine: ObjectQL, door: Door, payload: Record<string, unknown>, context: Record<string, unknown> = CALLER) =>
192+
door === 'update by id'
193+
? engine.update(ITEM, payload, { where: { id: 'k1' }, context } as any)
194+
: engine.update(ITEM, payload, { where: { id: { $in: ['k1', 'k2'] } }, multi: true, context } as any);
195+
196+
async function refusalOf(run: () => Promise<unknown>): Promise<unknown> {
197+
try {
198+
await run();
199+
} catch (e) {
200+
return e;
201+
}
202+
throw new Error('expected the write to be refused, but it succeeded');
203+
}
204+
205+
/**
206+
* The answer as every HTTP door reads it (ADR-0112) — status, code, each field
207+
* finding and the sentence — with the id the caller sent written as `ID`, so
208+
* two answers to two ids compare whole.
209+
*/
210+
function answerOf(err: unknown, sentId: string): string {
211+
const thrown = resolveThrownHttpError(err);
212+
const out = (s: unknown) => String(s ?? '').split(sentId).join('ID');
213+
return JSON.stringify({
214+
status: thrown.status,
215+
code: thrown.code,
216+
message: out((err as Error).message),
217+
fields: ((err as any)?.fields ?? []).map((f: any) => ({ field: f.field, code: f.code, message: out(f.message) })),
218+
});
219+
}
220+
221+
const storedItems = (storeFor: (o: string) => Map<string, any>) =>
222+
[...storeFor(ITEM).values()].map((r) => ({ id: r.id, title: r.title, duty: r.duty, assignee: r.assignee, header: r.header }));
223+
224+
const UNTOUCHED = ['k1', 'k2'].map((id) => ({ id, title: 'stored', ...STORED }));
225+
226+
describe('the update\'s reference forgiveness compares only stored values the caller may read', () => {
227+
describe.each(REFERENCE_FIELDS)('the %s column, which the caller may edit but not read', (field) => {
228+
it.each(DOORS)('%s — a value the rows store answers exactly as a value they do not', async (door) => {
229+
const { engine, storeFor } = await boot(HIDDEN_COLUMNS);
230+
const storedValue = await refusalOf(() => write(engine, door, { [field]: STORED[field] }));
231+
const otherValue = await refusalOf(() => write(engine, door, { [field]: OTHER[field] }));
232+
const answer = JSON.parse(answerOf(storedValue, STORED[field]));
233+
expect(answer.status).toBe(400);
234+
expect(answer.code).toBe('VALIDATION_FAILED');
235+
expect(answer.fields.map((f: any) => ({ field: f.field, code: f.code }))).toEqual([{ field, code: 'reference_not_found' }]);
236+
expect(answerOf(storedValue, STORED[field])).toBe(answerOf(otherValue, OTHER[field]));
237+
expect(storedItems(storeFor)).toEqual(UNTOUCHED);
238+
});
239+
240+
it.each(DOORS)('%s — control: the same grant edits another column of the same rows', async (door) => {
241+
const { engine, storeFor } = await boot(HIDDEN_COLUMNS);
242+
await write(engine, door, { title: 'renamed' });
243+
expect(storedItems(storeFor).find((r) => r.id === 'k1')).toEqual({ id: 'k1', title: 'renamed', ...STORED });
244+
});
245+
});
246+
247+
describe.each(REFERENCE_FIELDS)('control: the %s column, which the caller can read', (field) => {
248+
it.each(DOORS)('%s — the value the rows store, carried back, lands', async (door) => {
249+
const { engine, storeFor } = await boot(READABLE_COLUMNS);
250+
await write(engine, door, { title: 'renamed', [field]: STORED[field] });
251+
expect(storedItems(storeFor).find((r) => r.id === 'k1')).toEqual({ id: 'k1', title: 'renamed', ...STORED });
252+
});
253+
254+
it.each(DOORS)('%s — a value the rows do not store is refused as one the caller cannot read', async (door) => {
255+
const { engine, storeFor } = await boot(READABLE_COLUMNS);
256+
const err = await refusalOf(() => write(engine, door, { [field]: OTHER[field] }));
257+
const answer = JSON.parse(answerOf(err, OTHER[field]));
258+
expect({ status: answer.status, code: answer.code }).toEqual({ status: 400, code: 'VALIDATION_FAILED' });
259+
expect(answer.fields.map((f: any) => ({ field: f.field, code: f.code }))).toEqual([{ field, code: 'reference_not_found' }]);
260+
expect(storedItems(storeFor)).toEqual(UNTOUCHED);
261+
});
262+
});
263+
264+
it.each(DOORS)('%s — control: a system write keeps its exemption', async (door) => {
265+
const { engine, storeFor } = await boot(HIDDEN_COLUMNS);
266+
await write(engine, door, { duty: OTHER.duty }, SYS_CTX);
267+
expect(storedItems(storeFor).find((r) => r.id === 'k1')?.duty).toBe(OTHER.duty);
268+
});
269+
});

0 commit comments

Comments
 (0)