|
| 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