Skip to content

Commit 3392bc4

Browse files
committed
fix(automation): a dry-run update or delete targets exactly the rows the engine dispatch picks
An update_record whose fields carry the row's id, with no filter, is a by-id write to that one row; the stand-in now reads its targets off the dispatch's own answer (by-id, multi, reject) instead of the filter alone. Pins the two unread-grants arms the admission code already covers (an empty answer, no resolver wired). Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5kYk6G1CvandwWbbhe
1 parent 4889de3 commit 3392bc4

2 files changed

Lines changed: 82 additions & 15 deletions

File tree

‎packages/services/service-automation/src/dry-run.test.ts‎

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,14 @@ function harness(opts: {
8282
bundles?: Record<string, Record<string, unknown>>;
8383
/** The grants read fails (the resolver throws). */
8484
grantsFail?: boolean;
85+
/** The grants resolver answers nothing (`null`). */
86+
grantsNone?: boolean;
87+
/** No grants resolver is wired at all. */
88+
noGrantsResolver?: boolean;
89+
/** The live `deal` rows, when not the one default row. */
90+
rows?: Record<string, Record<string, unknown>>;
8591
} = {}): Harness {
86-
const { data, calls } = liveData();
92+
const { data, calls } = liveData(opts.rows);
8793
const writeChecks: Harness['writeChecks'] = [];
8894
const security = opts.canWrite
8995
? {
@@ -123,7 +129,7 @@ function harness(opts: {
123129
} as any),
124130
async execute() { h.approvalCalls++; return { success: true, suspend: true }; },
125131
});
126-
engine.setUserGrantsResolver(async () => opts.grantsFail ? Promise.reject(new Error('grants store unreachable')) : ({
132+
if (!opts.noGrantsResolver) engine.setUserGrantsResolver(async () => opts.grantsFail ? Promise.reject(new Error('grants store unreachable')) : opts.grantsNone ? null as never : ({
127133
positions: [],
128134
permissions: [],
129135
accessible_org_ids: ['org_1'],
@@ -320,8 +326,12 @@ describe('dryRun — admission (the by-name start rules, ruling B for runAs syst
320326
expect(result.steps).toEqual([]);
321327
});
322328

323-
it('refuses a runAs system definition when the named user\'s grants cannot be read (the account rule fails closed)', async () => {
324-
const h = harness({ grantsFail: true });
329+
it.each([
330+
['the read fails (the resolver throws)', { grantsFail: true }],
331+
['the resolver answers nothing', { grantsNone: true }],
332+
['no resolver is wired', { noGrantsResolver: true }],
333+
] as const)('refuses a runAs system definition when the named user\'s grants cannot be read: %s (the account rule fails closed)', async (_arm, unread) => {
334+
const h = harness(unread);
325335
const result = await h.engine.dryRun(gated({ type: 'schedule', runAs: 'system' }), { userId: 'usr_maker' });
326336
expect(result.status).toBe('refused');
327337
expect(result.steps).toEqual([]);
@@ -546,3 +556,41 @@ describe('dryRun — a predicate write the engine refuses without multi', () =>
546556
expect(result.steps.find((s) => s.nodeId === 'up')).toMatchObject({ kind: 'write', operation: 'update', recordIds: ['d1'] });
547557
});
548558
});
559+
560+
describe('dryRun — a write targets exactly the rows the engine dispatch names', () => {
561+
const rows = () => ({ d1: { id: 'd1', stage: 'open', amount: 10 }, d2: { id: 'd2', stage: 'open', amount: 20 } });
562+
const readBoth = [
563+
{ id: 'r1', type: 'get_record', label: 'Read d1', config: { objectName: 'deal', filter: { id: 'd1' }, outputVariable: 'one' } },
564+
{ id: 'r2', type: 'get_record', label: 'Read d2', config: { objectName: 'deal', filter: { id: 'd2' }, outputVariable: 'two' } },
565+
{ id: 'as', type: 'assignment', label: 'Keep', config: { assignments: { seen: { dialect: 'cel', source: 'one.stage + "/" + two.stage' } } } },
566+
];
567+
568+
it('an update whose fields name the id, with no filter, targets that one row and lays its values over it alone', async () => {
569+
const h = harness({ canWrite: () => true, rows: rows() });
570+
const result = await h.engine.dryRun(flow([
571+
{ id: 'start', type: 'start', label: 'Start' },
572+
{ id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', fields: { id: 'd2', stage: 'won' } } },
573+
...readBoth,
574+
{ id: 'end', type: 'end', label: 'End' },
575+
], chain('start', 'up', 'r1', 'r2', 'as', 'end')), { userId: 'usr_maker' });
576+
577+
expect(result.status).toBe('completed');
578+
expect(writes(h)).toEqual([]);
579+
expect(result.steps.find((s) => s.nodeId === 'up')).toMatchObject({ kind: 'write', operation: 'update', recordIds: ['d2'] });
580+
expect(result.steps.find((s) => s.nodeId === 'as')).toMatchObject({ kind: 'assignment', values: { seen: 'open/won' } });
581+
});
582+
583+
it('CONTROL — the same update declaring multi with no filter targets every row the named user can read', async () => {
584+
const h = harness({ canWrite: () => true, rows: rows() });
585+
const result = await h.engine.dryRun(flow([
586+
{ id: 'start', type: 'start', label: 'Start' },
587+
{ id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', fields: { stage: 'won' }, multi: true } },
588+
...readBoth,
589+
{ id: 'end', type: 'end', label: 'End' },
590+
], chain('start', 'up', 'r1', 'r2', 'as', 'end')), { userId: 'usr_maker' });
591+
592+
expect(result.status).toBe('completed');
593+
expect(result.steps.find((s) => s.nodeId === 'up')).toMatchObject({ kind: 'write', operation: 'update', recordIds: ['d1', 'd2'] });
594+
expect(result.steps.find((s) => s.nodeId === 'as')).toMatchObject({ kind: 'assignment', values: { seen: 'won/won' } });
595+
});
596+
});

‎packages/services/service-automation/src/dry-run.ts‎

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,8 @@ type DataEngineLike = Record<string, unknown> & {
233233
*
234234
* - Writes are simulated ("Writes: simulated, never made"): `insert`,
235235
* `update` and `delete` write nothing, record the write on the node's step,
236-
* and lay it over the run's own view of the rows.
236+
* and lay it over the run's own view of the rows. An update or a delete
237+
* targets exactly the rows the engine's own dispatch picks.
237238
* - A read that names an id answers the run's view: a created row holds only
238239
* the fields the flow set, an updated row is the live row with the
239240
* simulated fields laid over it, a deleted row is nothing.
@@ -280,12 +281,27 @@ export function dryRunDataEngine(real: unknown, security: () => unknown): unknow
280281
return patch ? { ...row, ...project(patch, query.fields) } : row;
281282
};
282283

283-
const targets = async (object: string, where: unknown, context: unknown): Promise<string[]> => {
284-
const id = namedId(where);
285-
if (id !== undefined) {
284+
/**
285+
* The rows a write targets: exactly the engine dispatch's own answer
286+
* (`resolveEngineUpdateDispatch` / `resolveEngineDeleteDispatch`), so
287+
* `recordIds` is "the rows the write targets" on every arm. `by-id` is
288+
* the one id the dispatch picked, wherever it came from (`where.id`, or
289+
* an update's `data.id`), when the named user can read it; `multi` is
290+
* the rows the filter matches in the named user's scope; `reject`
291+
* targets no row and reads none.
292+
*/
293+
const targets = async (
294+
object: string,
295+
dispatch: { readonly kind: 'by-id'; readonly id: unknown } | { readonly kind: 'multi' } | { readonly kind: 'reject' },
296+
where: unknown,
297+
context: unknown,
298+
): Promise<string[]> => {
299+
if (dispatch.kind === 'reject') return [];
300+
if (dispatch.kind === 'by-id') {
301+
const id = String(dispatch.id);
286302
if (state.deleted.get(object)?.has(id)) return [];
287303
if (state.created.get(object)?.has(id)) return [id];
288-
const row = live?.findOne ? await live.findOne(object, { where: { id }, fields: ['id'], context }) : null;
304+
const row = live?.findOne ? await live.findOne(object, { where: { id: dispatch.id }, fields: ['id'], context }) : null;
289305
return isPlainObject(row) ? [id] : [];
290306
}
291307
const rows = live?.find ? await live.find(object, { where, fields: ['id'], context }) : [];
@@ -314,11 +330,13 @@ export function dryRunDataEngine(real: unknown, security: () => unknown): unknow
314330
async update(object: string, data: unknown, options?: { where?: unknown; context?: unknown }) {
315331
const values = isPlainObject(data) ? { ...data } : {};
316332
// The engine's own dispatch decision, asked as the live update
317-
// asks it: a call naming neither one row nor `multi` is refused
318-
// with the engine's own error, after the permission gate and
319-
// before any row is read, so it targets no row.
333+
// asks it, and its targets read off that answer: one row by id
334+
// (from `where.id` or the values' own `id`), the filter's rows
335+
// under `multi`, and none on a reject — a call naming neither one
336+
// row nor `multi` is refused with the engine's own error, after
337+
// the permission gate and before any row is read.
320338
const dispatch = resolveEngineUpdateDispatch(data as EngineUpdateDispatchData, options as EngineUpdateDispatchInput | undefined);
321-
const ids = dispatch.kind === 'reject' ? [] : await targets(object, options?.where, options?.context);
339+
const ids = await targets(object, dispatch, options?.where, options?.context);
322340
const permission = await judge('update', object, options?.context, data);
323341
record({ operation: 'update', object, recordIds: ids, values, permission });
324342
if (permission === 'refused') throw writeRefusedError('update', object);
@@ -333,9 +351,10 @@ export function dryRunDataEngine(real: unknown, security: () => unknown): unknow
333351
return ids.length;
334352
},
335353
async delete(object: string, options?: { where?: unknown; context?: unknown }) {
336-
// As `update`: the engine's own dispatch decision, and its own error.
354+
// As `update`: the engine's own dispatch decision, its targets,
355+
// and its own error. A delete's by-id arm reads `where.id` only.
337356
const dispatch = resolveEngineDeleteDispatch(options as EngineDeleteDispatchInput | undefined);
338-
const ids = dispatch.kind === 'reject' ? [] : await targets(object, options?.where, options?.context);
357+
const ids = await targets(object, dispatch, options?.where, options?.context);
339358
record({ operation: 'delete', object, recordIds: ids, permission: 'not_judged' });
340359
if (dispatch.kind === 'reject') throw new Error(dispatch.message);
341360
let gone = state.deleted.get(object);

0 commit comments

Comments
 (0)