Skip to content

Commit 129000b

Browse files
committed
fix(objectql): a system write keeps its validation rules before the reference check
A write that is not a system write has its references checked before the record's validation rules; a system write keeps the order it had, so its answer is unchanged. One predicate, referencesCheckedBeforeRules, is read by insert, update by id, bulk update and the validate preview. Pins: each door answers reference_not_found for an unreadable reference a rule would trip on, and for one that exists nowhere, while a readable one still answers the rule; a system write and a flow run's system write keep the rule's answer; a read of the target that fails is refused, and a reference to an unregistered object is admitted. Claude-Session: https://claude.ai/code/session_01Utp6CYQjMkN514R78sCrTT Co-authored-by: Claude <noreply@anthropic.com>
1 parent c9cb46a commit 129000b

4 files changed

Lines changed: 189 additions & 12 deletions

File tree

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,20 @@ function isEmptyReferenceValue(v: unknown): boolean {
9595
*/
9696
const CALLER_READ_REFERENCE_TYPES: ReadonlySet<string> = new Set(['master_detail', 'lookup', 'user']);
9797

98+
/**
99+
* [#29029] Whether this write's reference check ({@link assertReferencesResolve})
100+
* runs BEFORE the record's validation rules. A write that is not a system
101+
* write: yes — a reference its caller cannot read answers
102+
* `reference_not_found`, whatever a rule would answer. A system write keeps
103+
* the order it had, the rules first and then the check, so its answer is the
104+
* one it gave before (ruling of record 6663849489). The one predicate every
105+
* write door and the validate preview read, so the order cannot differ
106+
* between them.
107+
*/
108+
export function referencesCheckedBeforeRules(context: unknown): boolean {
109+
return !(context as { isSystem?: unknown } | null | undefined)?.isSystem;
110+
}
111+
98112
/**
99113
* [#4441] Referential integrity on the WRITE path: a `lookup` (or any
100114
* reference-typed field) may not be given an id that exists in no row of the

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

Lines changed: 144 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131

3232
import { describe, it, expect, beforeEach } from 'vitest';
3333
import { resolveThrownHttpError } from '@objectstack/types';
34+
import { markFlowWriteReferenceCheck } from '@objectstack/core';
3435
import { ObjectQL } from './engine.js';
3536
import { ValidationError } from './validation/record-validator.js';
3637

@@ -59,6 +60,32 @@ const ITEM_OBJECT = {
5960
},
6061
};
6162

63+
/**
64+
* [#29029] A task whose validation rules read each reference one hop: each
65+
* trips on a target named `tripping`. The reference check runs BEFORE them.
66+
*/
67+
const RULED = 'urt_ruled_task';
68+
const TRIPPED = 'URT29029: the named target trips the rule';
69+
const TITLE_TRIPPED = 'URT29029: the title trips the rule';
70+
const RULED_OBJECT = {
71+
name: RULED,
72+
label: 'Ruled task',
73+
fields: {
74+
title: { name: 'title', label: 'Title', type: 'text' },
75+
duty: { name: 'duty', label: 'Duty', type: 'lookup', reference: TARGET },
76+
assignee: { name: 'assignee', label: 'Assignee', type: 'user' },
77+
header: { name: 'header', label: 'Header', type: 'master_detail', reference: TARGET },
78+
},
79+
validations: (['duty', 'assignee', 'header'] as const).map((field) => ({
80+
// Checked only while the reference is set, as an author guards a traversal.
81+
name: `urt_${field}_when_set`, type: 'conditional', severity: 'error', message: 'unused',
82+
when: `record.${field} != null`,
83+
then: { name: `urt_${field}_trips`, type: 'script', severity: 'error', message: TRIPPED, condition: `record.${field}.name == 'tripping'` },
84+
})).concat([
85+
{ name: 'urt_title_trips', type: 'script', severity: 'error', message: TITLE_TRIPPED, condition: "record.title == 'trip'" } as any,
86+
]),
87+
};
88+
6289
/** A store-backed driver: what is stored is what a later read answers. */
6390
function makeStoreDriver() {
6491
const stores = new Map<string, Map<string, Record<string, any>>>();
@@ -135,7 +162,7 @@ function makeEngine() {
135162
engine.registerApp({
136163
id: 'urt',
137164
name: 'Unreadable reference target',
138-
objects: [ownedTarget(TARGET, 'Duty'), ownedTarget(USER, 'User'), ITEM_OBJECT],
165+
objects: [ownedTarget(TARGET, 'Duty'), ownedTarget(USER, 'User'), ITEM_OBJECT, RULED_OBJECT],
139166
} as any);
140167
const targetReads: TargetRead[] = [];
141168
engine.registerMiddleware(async (ctx: any, next: () => Promise<void>) => {
@@ -160,6 +187,9 @@ function makeEngine() {
160187
rows.set('t_mine', { id: 't_mine', name: 'mine', owner_name: 'alice' });
161188
rows.set('t_mine_2', { id: 't_mine_2', name: 'mine too', owner_name: 'alice' });
162189
rows.set('t_other', { id: 't_other', name: 'other', owner_name: 'bob' });
190+
// [#29029] A readable and an unreadable target that trip the ruled task's rules.
191+
rows.set('t_trip_mine', { id: 't_trip_mine', name: 'tripping', owner_name: 'alice' });
192+
rows.set('t_trip_other', { id: 't_trip_other', name: 'tripping', owner_name: 'bob' });
163193
}
164194
return { engine, targetReads, ...store };
165195
}
@@ -293,4 +323,117 @@ describe('[#29029] a non-system lookup or user write may name only a record the
293323
expect(storeFor(ITEM).get('k1')?.[field]).toEqual([UNREADABLE, 't_mine']);
294324
});
295325
});
326+
327+
it.each(DOORS)('%s — control: a flow run\'s system write keeps its reference check: a target that exists nowhere is refused', async (door) => {
328+
const flowRun = markFlowWriteReferenceCheck({ ...SYSTEM });
329+
expect(envelopeOf(await refusalOf(() => write(door, { duty: NOWHERE }, flowRun)))).toEqual(notFound('duty'));
330+
expect(storedItems()).toEqual([{ id: 'k1', title: 'stored' }]);
331+
});
332+
});
333+
334+
describe('[#29029] an unreadable reference answers reference_not_found before the record\'s validation rules', () => {
335+
let engine: ObjectQL;
336+
let storeFor: (o: string) => Map<string, Record<string, any>>;
337+
338+
beforeEach(() => {
339+
({ engine, storeFor } = makeEngine());
340+
storeFor(RULED).set('r1', { id: 'r1', title: 'stored' });
341+
});
342+
343+
const write = (door: Door, payload: Record<string, unknown>, context: Record<string, unknown> = ALICE) => {
344+
if (door === 'insert') return engine.insert(RULED, { title: 'new', ...payload }, { context } as any);
345+
if (door === 'batch insert') {
346+
return engine.insert(RULED, [{ title: 'first' }, { title: 'second', ...payload }], { context } as any);
347+
}
348+
if (door === 'update by id') return engine.update(RULED, payload, { where: { id: 'r1' }, context } as any);
349+
return engine.update(RULED, payload, { where: { id: { $in: ['r1'] } }, multi: true, context } as any);
350+
};
351+
352+
const storedRuled = () => [...storeFor(RULED).values()];
353+
const ruleRefusal = (err: unknown) => ({
354+
code: resolveThrownHttpError(err).code,
355+
messages: ((err as any)?.fields ?? []).map((f: any) => String(f.message ?? '')),
356+
});
357+
358+
describe.each([
359+
{ field: 'duty', kind: 'lookup' },
360+
{ field: 'assignee', kind: 'user' },
361+
{ field: 'header', kind: 'master_detail' },
362+
] as const)('a $kind field', ({ field }) => {
363+
it.each(DOORS)('%s — a target the caller cannot read that a rule would trip on answers reference_not_found, not the rule', async (door) => {
364+
const err = await refusalOf(() => write(door, { [field]: 't_trip_other' }));
365+
expect(envelopeOf(err)).toEqual(notFound(field));
366+
expect(String((err as Error).message)).not.toContain(TRIPPED);
367+
expect(storedRuled()).toEqual([{ id: 'r1', title: 'stored' }]);
368+
});
369+
370+
it.each(DOORS)('%s — control: a readable target the rule trips on answers the rule', async (door) => {
371+
const err = await refusalOf(() => write(door, { [field]: 't_trip_mine' }));
372+
expect(ruleRefusal(err).code).toBe('VALIDATION_FAILED');
373+
expect(ruleRefusal(err).messages.some((m: string) => m.includes(TRIPPED))).toBe(true);
374+
expect(storedRuled()).toEqual([{ id: 'r1', title: 'stored' }]);
375+
});
376+
377+
it.each(DOORS)('%s — control: a system write naming that target answers the rule, as before', async (door) => {
378+
const err = await refusalOf(() => write(door, { [field]: 't_trip_other' }, SYSTEM));
379+
expect(ruleRefusal(err).messages.some((m: string) => m.includes(TRIPPED))).toBe(true);
380+
expect(envelopeOf(err).fields.map((f) => f.code)).not.toContain('reference_not_found');
381+
});
382+
});
383+
384+
it.each(DOORS)('%s — a reference to a record that exists nowhere answers reference_not_found before a rule the record trips', async (door) => {
385+
const err = await refusalOf(() => write(door, { title: 'trip', duty: 't_missing' }));
386+
expect(envelopeOf(err)).toEqual(notFound('duty'));
387+
expect(String((err as Error).message)).not.toContain(TITLE_TRIPPED);
388+
});
389+
390+
it.each(DOORS)('%s — control: a flow run\'s system write keeps the rules first — the rule its record trips answers, not the reference check', async (door) => {
391+
const flowRun = markFlowWriteReferenceCheck({ ...SYSTEM });
392+
const err = await refusalOf(() => write(door, { title: 'trip', duty: 't_missing' }, flowRun));
393+
expect(ruleRefusal(err).messages.some((m: string) => m.includes(TITLE_TRIPPED))).toBe(true);
394+
expect(envelopeOf(err).fields.map((f) => f.code)).not.toContain('reference_not_found');
395+
});
396+
397+
it('the validate preview answers as the insert does: reference_not_found for the unreadable target, the rule for the readable one', async () => {
398+
const unreadable = (await engine.validate(RULED, { title: 'preview', duty: 't_trip_other' }, { mode: 'insert', context: ALICE } as any)).results?.[0];
399+
expect(unreadable?.valid).toBe(false);
400+
expect((unreadable?.errors ?? []).map((e: any) => ({ field: e.field, code: e.code }))).toEqual([{ field: 'duty', code: 'reference_not_found' }]);
401+
expect(JSON.stringify(unreadable?.errors ?? [])).not.toContain(TRIPPED);
402+
const readable = (await engine.validate(RULED, { title: 'preview', duty: 't_trip_mine' }, { mode: 'insert', context: ALICE } as any)).results?.[0];
403+
expect(readable?.valid).toBe(false);
404+
expect((readable?.errors ?? []).some((e: any) => String(e.message).includes(TRIPPED))).toBe(true);
405+
});
406+
});
407+
408+
describe('[#29029] which failures of the reference check fail open, and which fail closed', () => {
409+
it('a read door that fails for a reason other than access fails CLOSED: the target is not one the caller read', async () => {
410+
const { engine, storeFor } = makeEngine();
411+
engine.registerMiddleware(async (ctx: any, next: () => Promise<void>) => {
412+
if (ctx.object === TARGET && ctx.operation === 'find' && !ctx.context?.isSystem) {
413+
throw new Error('no such table: urt_duty');
414+
}
415+
await next();
416+
});
417+
const err = await refusalOf(() => engine.insert(ITEM, { title: 'new', duty: 't_mine' }, { context: ALICE } as any));
418+
expect(envelopeOf(err)).toEqual(notFound('duty'));
419+
expect([...storeFor(ITEM).values()]).toEqual([]);
420+
});
421+
422+
it('a reference to an object the registry does not hold fails OPEN: there is no read door to ask, as the existence probe already answered', async () => {
423+
const { engine, storeFor } = makeEngine();
424+
engine.registerApp({
425+
id: 'urt_unregistered',
426+
name: 'A reference to an unregistered object',
427+
objects: [{
428+
name: 'urt_loose_task',
429+
label: 'Loose task',
430+
fields: {
431+
title: { name: 'title', label: 'Title', type: 'text' },
432+
loose: { name: 'loose', label: 'Loose', type: 'lookup', reference: 'urt_not_registered' },
433+
},
434+
}],
435+
} as any);
436+
await engine.insert('urt_loose_task', { title: 'new', loose: 'x_1' }, { context: ALICE } as any);
437+
expect([...storeFor('urt_loose_task').values()].map((r) => r.loose)).toEqual(['x_1']);
438+
});
296439
});

‎packages/objectql/src/engine-validate.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import { evaluateValidationRules, hasParentScopedRequiredWhen, stripReadonlyFiel
5252
import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js';
5353
import { assertRecordCurrencyCodes, RecordCurrencyCodeRequiredError } from './validation/record-currency-code.js';
5454
import { isHomeAmountRefusal } from './home-amount-projection.js';
55+
import { referencesCheckedBeforeRules } from './engine-referential-integrity.js';
5556
import { resolveEngineUpdateDispatch, type EngineUpdateDispatchData } from './engine-update-dispatch.js';
5657
import {
5758
droppedFieldEvents,
@@ -575,14 +576,17 @@ export async function validate(
575576
);
576577
}
577578
// [#26684] The insert's admit step, run as `insert()` runs it: before
578-
// the rules (#29029), the reference check on the ids the caller supplied
579+
// the rules unless this is a system write (#29029,
580+
// `referencesCheckedBeforeRules`), the reference check on the ids the caller supplied
579581
// (`rawRows`, before the defaults — the write's `suppliedPerRow`), so
580582
// a row the write refuses on a dangling or unreadable reference is
581583
// refused here with the same finding, and is not counted toward a later
582584
// row's parent summary. ⛔ Behind the same write-gate probe as the
583585
// related read above: a caller the probe refuses learns nothing about
584586
// which ids exist.
585-
if (mode === 'insert' && mayWrite) {
587+
const previewReferences = mode === 'insert' && mayWrite;
588+
const referencesFirst = referencesCheckedBeforeRules(options?.context);
589+
if (previewReferences && referencesFirst) {
586590
await this.assertReferencesResolve(schemaForValidation, row, rawRows[i], options?.context, messages);
587591
}
588592
warnings.push(...evaluateValidationRules(schemaForValidation as any, row, mode, {
@@ -598,6 +602,9 @@ export async function validate(
598602
related: batchSummaries ? batchSummaries.overlay(previewRelatedForRow(judgedViews[i])) : previewRelatedForRow(judgedViews[i]),
599603
permissions: previewPermissionsFor(row),
600604
}));
605+
if (previewReferences && !referencesFirst) {
606+
await this.assertReferencesResolve(schemaForValidation, row, rawRows[i], options?.context, messages);
607+
}
601608
} catch (e) {
602609
if (e instanceof ValidationError) {
603610
return { valid: false, errors: e.fields.map((f) => ({ ...f })), warnings };

‎packages/objectql/src/engine.ts‎

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ import { buildEvalUser, buildProvenance, buildSession, buildUser } from './engin
101101
// [#25522 cut 10] The write path's reference check and the caller's read of a
102102
// master-detail header; the methods of the same names below hand each body the
103103
// members it reads (`ReferentialIntegrityHost`).
104-
import { assertReferencesResolve, masterDetailHeadersCallerReads, type StoredReferenceRows } from './engine-referential-integrity.js';
104+
import { assertReferencesResolve, masterDetailHeadersCallerReads, referencesCheckedBeforeRules, type StoredReferenceRows } from './engine-referential-integrity.js';
105105
// [#25522 cut 11] File-field hydration on read; the methods of the same names
106106
// below hand each body the members it reads (`FileReferenceHydrationHost`).
107107
import { callerMayReadSysFile, readParentDerivedFiles, resolveFileReferences, servableFileRows, serveRefusedFileHydration } from './engine-file-reference-hydration.js';
@@ -6492,13 +6492,18 @@ export class ObjectQL implements IObjectQLEngine {
64926492
// [ADR-0144 D8 rule 4] A `record`-mode amount is stored with its
64936493
// currency code, or the row is refused (`ERR_CURRENCY_CODE_REQUIRED`).
64946494
assertRecordCurrencyCodes(object, (schemaForValidation as { fields?: unknown } | undefined)?.fields, rows[i], 'insert');
6495-
// [#29029] The reference check runs BEFORE the record's validation
6496-
// rules: a reference the caller cannot read answers
6497-
// `reference_not_found`, whatever a rule would answer.
6498-
await this.assertReferencesResolve(
6495+
// [#29029] A write that is not a system write has its references
6496+
// checked BEFORE the record's validation rules: a reference the
6497+
// caller cannot read answers `reference_not_found`, whatever a rule
6498+
// would answer. A system write keeps the rules first
6499+
// (`referencesCheckedBeforeRules`).
6500+
const referencesFirst = referencesCheckedBeforeRules(opCtx.context);
6501+
const checkReferences = () => this.assertReferencesResolve(
64996502
schemaForValidation, rows[i], suppliedPerRow[i], opCtx.context, msgCtx,
65006503
);
6504+
if (referencesFirst) await checkReferences();
65016505
emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(schemaForValidation as any, rows[i], 'insert', { logger: this.logger, currentUser: this.buildEvalUser(opCtx.context), skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: msgCtx, parent: insertParentForRow?.(rows[i]), related: batchSummaries ? batchSummaries.overlay(insertRelatedForRow(rows[i])) : insertRelatedForRow(rows[i]), permissions: insertPermissionsFor(rows[i]) }), this.logger, object);
6506+
if (!referencesFirst) await checkReferences();
65026507
// [#25579] Admitted: a later row of this batch reads it in the summary.
65036508
batchSummaries?.accept(rows[i]);
65046509
} catch (e) {
@@ -8328,13 +8333,17 @@ export class ObjectQL implements IObjectQLEngine {
83288333
// [#4441] A repoint is as capable of dangling as an initial link.
83298334
// [#29062] …but a value the row already stores is not a repoint:
83308335
// the prior row is what the check forgives a refused value against.
8331-
// [#29029] Before the record's validation rules, as on insert.
8332-
await this.assertReferencesResolve(
8336+
// [#29029] Before the record's validation rules unless this is a
8337+
// system write, as on insert (`referencesCheckedBeforeRules`).
8338+
const referencesFirst = referencesCheckedBeforeRules(opCtx.context);
8339+
const checkReferences = () => this.assertReferencesResolve(
83338340
updateSchema, hookContext.input.data as Record<string, unknown>,
83348341
opCtx.data as Record<string, unknown>, opCtx.context, updateMsgCtx,
83358342
async () => [priorRecord],
83368343
);
8344+
if (referencesFirst) await checkReferences();
83378345
emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(updateSchema as any, hookContext.input.data as Record<string, unknown>, 'update', { previous: priorRecord, logger: this.logger, currentUser: this.buildEvalUser(opCtx.context), skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: updateMsgCtx, parent: roWhenParent, previousParent: roWhenPreviousParent, related: relatedForUpdate, permissions: permissionsForUpdate }), this.logger, object);
8346+
if (!referencesFirst) await checkReferences();
83388347
// [commit 9d7f7259f] The by-id driver exit — where a driver's refusal
83398348
// leaves this door, and where a recognised unique violation
83408349
// stops being the driver's error. `envelopeUniqueViolation`
@@ -8745,12 +8754,15 @@ export class ObjectQL implements IObjectQLEngine {
87458754
// [#29062] A refused value is forgiven only when EVERY matched row
87468755
// already stores it (the `readPriorRows` memo, read only then);
87478756
// a row it is new to makes it this write's reference.
8748-
// [#29029] Before the record's validation rules, as on insert.
8749-
await this.assertReferencesResolve(
8757+
// [#29029] Before the record's validation rules unless this is a
8758+
// system write, as on insert (`referencesCheckedBeforeRules`).
8759+
const referencesFirst = referencesCheckedBeforeRules(opCtx.context);
8760+
const checkReferences = () => this.assertReferencesResolve(
87508761
updateSchema, hookContext.input.data as Record<string, unknown>,
87518762
opCtx.data as Record<string, unknown>, opCtx.context, updateMsgCtx,
87528763
readPriorRows,
87538764
);
8765+
if (referencesFirst) await checkReferences();
87548766
if (rulesNeedRows) {
87558767
for (const row of priorRows ?? []) {
87568768
try {
@@ -8772,6 +8784,7 @@ export class ObjectQL implements IObjectQLEngine {
87728784
// rule families that never read a header.
87738785
emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(updateSchema as any, hookContext.input.data as Record<string, unknown>, 'update', { previous: null, logger: this.logger, currentUser: bulkEvalUser, skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: updateMsgCtx, permissions: bulkPermissions }), this.logger, object);
87748786
}
8787+
if (!referencesFirst) await checkReferences();
87758788
// `updateMany` presence is part of the ladder verdict resolved above.
87768789
// [commit 9d7f7259f] The predicate driver exit, enveloped on the same
87778790
// terms as the by-id exit above. A multi-row write names no

0 commit comments

Comments
 (0)