Skip to content

Commit 68b89e6

Browse files
committed
fix(runtime): every flow start door loads the record keys it hands a run in the caller's scope before the run exists
WIP: the shared check (refuseUnreadableFlowStartRecords) beside the action door's subject load, called by the trigger routes, a declared flow endpoint and the action door's flow branch. Claude-Session: https://claude.ai/code/session_01ADHkmT7iCiGQkgXGQAo4Fo Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2af0ae2 commit 68b89e6

4 files changed

Lines changed: 257 additions & 7 deletions

File tree

‎packages/runtime/src/action-execution.ts‎

Lines changed: 141 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,8 @@ import {
6565
// Who may START a flow by name — the one rule the trigger door, this door and
6666
// the declared endpoint share (the maintainer's rulings, letters B and A, and
6767
// the flow's own `requiredPermissions`).
68-
import { flowStartRefusal } from './flow-start-admission.js';
68+
import { flowRunsElevated, flowStartRefusal } from './flow-start-admission.js';
69+
import { validationFailure } from './validation-failure.js';
6970
// [ADR-0066 D4] The capability arithmetic the action gate and the flow start
7071
// gate share.
7172
import { missingCapabilities } from './required-capabilities.js';
@@ -2278,6 +2279,41 @@ function flowActionCallerParamKeys(action: any, objectName: string, params: Reco
22782279
return Object.keys(params).filter((key) => !rowIdKeys.has(key));
22792280
}
22802281

2282+
/**
2283+
* The row slots the CALLER's own `params` fill at this door, as flow start
2284+
* admission's third question reads them ({@link refuseUnreadableFlowStartRecords}):
2285+
* each row-id key ({@link flowActionRowIdKeys}) the caller's bag names, whose
2286+
* value reaches the run over the seeded id because the caller's params win
2287+
* ({@link seedFlowActionParams}). Two cases name none:
2288+
*
2289+
* - an action whose `recordIdField` names a field other than `id`: the door
2290+
* seeds every row slot with that field's VALUE, never an id of this
2291+
* object, so there is no row of this object to load a slot's value as;
2292+
* - a value equal to the routed `recordId` this door's subject load already
2293+
* delivered (an object-bound action): that row was judged by that load.
2294+
*/
2295+
function flowActionCallerRecordKeys(
2296+
action: any,
2297+
objectName: string,
2298+
params: Record<string, unknown>,
2299+
recordId: string | undefined,
2300+
subject: ActionSubjectRecordLoad,
2301+
): Array<readonly [string, unknown]> {
2302+
const idField: string = typeof action?.recordIdField === 'string' && action.recordIdField ? action.recordIdField : 'id';
2303+
if (idField !== 'id') return [];
2304+
const judged = recordId !== undefined && recordId !== '' && !isObjectLessActionKey(objectName) && !subject.recordLoadDenied
2305+
? recordId
2306+
: undefined;
2307+
const keys: Array<readonly [string, unknown]> = [];
2308+
for (const key of flowActionRowIdKeys(action, objectName)) {
2309+
if (!Object.prototype.hasOwnProperty.call(params, key)) continue;
2310+
const value = params[key];
2311+
if (judged !== undefined && (typeof value === 'string' || typeof value === 'number') && String(value) === judged) continue;
2312+
keys.push([key, value]);
2313+
}
2314+
return keys;
2315+
}
2316+
22812317
/**
22822318
* Brand for {@link FlowActionRefusal} — `Symbol.for`, so recognition keeps
22832319
* working even if two module instances of this file ever coexist (src vs
@@ -2494,6 +2530,21 @@ export async function dispatchFlowAction(deps: ActionExecutionDeps,
24942530
code: startRefusal.code,
24952531
});
24962532
}
2533+
// Flow start admission's third question, the row the start addresses
2534+
// (`flow-start-admission.ts`): the routed row was judged by this door's
2535+
// subject load upstream, so what is asked here is every row slot the
2536+
// CALLER's own params fill, whose value reaches the run over that row's id.
2537+
// Each is loaded in the caller's scope by the read the subject load makes
2538+
// (the request's own driver, environment and identity, as both entrances
2539+
// load the routed row), and refused with that load's 404 before the run
2540+
// exists. Thrown with `code` + `status`, like the refusals above.
2541+
await refuseUnreadableFlowStartRecords(
2542+
automation,
2543+
action.target,
2544+
{ objectName, recordKeys: flowActionCallerRecordKeys(action, objectName, params, recordId, subject) },
2545+
ec,
2546+
(object, id) => callData(deps, requestContext, 'get', { object, id }, requestContext?.dataDriver, envId, ec),
2547+
);
24972548
// Pass a proper AutomationContext (the engine never read the former
24982549
// `triggerData` envelope).
24992550
const result: any = await automation.execute(action.target, {
@@ -3568,6 +3619,95 @@ export function apiForwardSubjectRecord(
35683619
return recordId ? { id: recordId } : {};
35693620
}
35703621

3622+
/**
3623+
* The row-slot keys a start hands a run, each with the value the run will
3624+
* receive under it — what {@link refuseUnreadableFlowStartRecords} loads.
3625+
*/
3626+
export type FlowStartRecordKeys = ReadonlyArray<readonly [key: string, value: unknown]>;
3627+
3628+
/**
3629+
* Flow start admission's THIRD question, the row a start addresses
3630+
* (`flow-start-admission.ts`), as the ONE function every door that starts a
3631+
* flow by name calls after `flowStartRefusal` and before `execute()`.
3632+
*
3633+
* ## The rule
3634+
*
3635+
* Every record key a door hands the run in a row slot the door defines
3636+
* (`recordId`, the `<object>Id` alias, an action's declared `recordIdParam`)
3637+
* is loaded first, in the CALLER's own scope, through
3638+
* {@link loadActionSubjectRecord}, and a key that scope does not deliver is
3639+
* refused by {@link refuseDeniedSubjectLoad}: the action door's own
3640+
* `404 RECORD_NOT_FOUND`, one envelope for a row the caller cannot read and an
3641+
* id that names nothing, so no door is an existence oracle the action door
3642+
* declines to be. Before `execute()`, so a refused start persists no run.
3643+
*
3644+
* It holds for every run, as the action door's load does: a persisted run is
3645+
* built only on a row the caller has shown it can read. A `runAs: 'system'`
3646+
* run is where the rule bites, because its nodes read and write past the
3647+
* caller's own access.
3648+
*
3649+
* ## The object a key is loaded from
3650+
*
3651+
* `objectName` is the object the start names: the action's own object at the
3652+
* action door, the request's `objectName` (or `object`) at the trigger routes
3653+
* and a declared endpoint, the object the door hands the run as `object` and
3654+
* derives the `<object>Id` alias from. A start whose keys come with no object
3655+
* to load them from (none named, or an object-less action key) cannot be
3656+
* judged:
3657+
*
3658+
* - an ELEVATED run ({@link flowRunsElevated}) is refused
3659+
* `400 VALIDATION_FAILED` naming `objectName`, the one thing the caller
3660+
* adds to be judged;
3661+
* - a user run starts as before: it reads in the caller's own scope.
3662+
*
3663+
* A key whose value is not one record id (a string or a number) is never
3664+
* loaded and is refused `400 VALIDATION_FAILED` naming the key: only an id
3665+
* names one row.
3666+
*
3667+
* ## What stays as it was
3668+
*
3669+
* - **The system principal** (`isSystem`, never set on inbound HTTP) starts
3670+
* every flow on every row, as the two admission rules let it.
3671+
* - **A start that names no record key** loads nothing.
3672+
* - **A key the door already loaded** is not passed here: the action door's
3673+
* subject load judged the routed id, and its tests stay as they are.
3674+
*
3675+
* `readRecord` is the door's own caller-scope read, the `callData('get', …)`
3676+
* its subject load uses, so there is no second loader.
3677+
*/
3678+
export async function refuseUnreadableFlowStartRecords(
3679+
automation: unknown,
3680+
flowName: string,
3681+
start: { objectName: unknown; recordKeys: FlowStartRecordKeys },
3682+
executionContext: { isSystem?: boolean } | null | undefined,
3683+
readRecord: (objectName: string, recordId: string) => Promise<unknown>,
3684+
): Promise<void> {
3685+
if (executionContext?.isSystem === true) return;
3686+
const named = start.recordKeys.filter(([, value]) => value !== undefined && value !== null && value !== '');
3687+
if (named.length === 0) return;
3688+
const objectName = typeof start.objectName === 'string' && start.objectName !== '' && !isObjectLessActionKey(start.objectName)
3689+
? start.objectName
3690+
: undefined;
3691+
if (objectName === undefined) {
3692+
if (!(await flowRunsElevated(automation, flowName))) return;
3693+
const message = 'A start that names a record must also name the record\'s object (`objectName`), '
3694+
+ 'so the caller\'s access to that record can be checked before the flow starts.';
3695+
throw validationFailure(message, [{ field: 'objectName', code: 'required', message }]);
3696+
}
3697+
const loaded = new Set<string>();
3698+
for (const [key, value] of named) {
3699+
if (typeof value !== 'string' && typeof value !== 'number') {
3700+
const message = `The record key \`${key}\` must name one record by its id.`;
3701+
throw validationFailure(message, [{ field: key, code: 'invalid_type', message }]);
3702+
}
3703+
const recordId = String(value);
3704+
if (loaded.has(recordId)) continue;
3705+
const subject = await loadActionSubjectRecord(objectName, recordId, () => readRecord(objectName, recordId));
3706+
refuseDeniedSubjectLoad(objectName, recordId, subject);
3707+
loaded.add(recordId);
3708+
}
3709+
}
3710+
35713711
/**
35723712
* [#15079] The prior/next value pair a successful declarative update hands back
35733713
* when the action declares `undoable: true` — the anchor that key never had.

‎packages/runtime/src/domains/automation.ts‎

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,16 @@ import {
6161
import { flowStartRefusal } from '../flow-start-admission.js';
6262
// ADR-0143 D5 · ruling A (record 6548764795) — which credential admitted the
6363
// caller, read the way the api-action forward table reads it.
64-
import { apiForwardCredentialKind } from '../action-execution.js';
64+
//
65+
// Flow start admission's third question, the row a start addresses: the action
66+
// door's caller-scope read and refusal, asked by every door that starts a flow
67+
// by name (`../flow-start-admission.ts`).
68+
import {
69+
apiForwardCredentialKind,
70+
callData,
71+
refuseUnreadableFlowStartRecords,
72+
type FlowStartRecordKeys,
73+
} from '../action-execution.js';
6574
// [#12156] ADR-0126 §7.1 clone — the whole-definition copy, the keys it must
6675
// not carry forward, the same-name refusal and the references notice.
6776
import {
@@ -188,9 +197,7 @@ export function buildAutomationContext(body: any, context: HttpProtocolContext):
188197
// `<objectName>Id` alias) stay out even when the caller's own bag names
189198
// them: the console mirrors the launched row's id into `params.recordId`,
190199
// and that is the row being addressed, not a screen being answered.
191-
const alias = objectName
192-
? `${String(objectName).replace(/_([a-z])/g, (_: string, c: string) => c.toUpperCase())}Id`
193-
: undefined;
200+
const alias = recordIdAlias(objectName);
194201
const callerParamKeys = Object.keys(baseParams).filter((k) => k !== 'recordId' && k !== alias);
195202
if (recordId !== undefined && baseParams.recordId === undefined) {
196203
baseParams.recordId = recordId;
@@ -225,6 +232,39 @@ export function buildAutomationContext(body: any, context: HttpProtocolContext):
225232
return automationContext;
226233
}
227234

235+
/**
236+
* The camelCase `<objectName>Id` alias {@link buildAutomationContext} seeds the
237+
* row id under (`crm_lead` → `crmLeadId`), or `undefined` when the start names
238+
* no object. ONE spelling, read by the builder to seed it and by
239+
* {@link flowStartRecordKeys} to judge what it carries.
240+
*/
241+
function recordIdAlias(objectName: unknown): string | undefined {
242+
return objectName
243+
? `${String(objectName).replace(/_([a-z])/g, (_: string, c: string) => c.toUpperCase())}Id`
244+
: undefined;
245+
}
246+
247+
/**
248+
* What a context {@link buildAutomationContext} built hands the run as the row
249+
* it addresses: the object the start names (`object`) and the value under each
250+
* row slot this builder defines, `params.recordId` and the `<object>Id` alias,
251+
* read off the BUILT bag, so a caller's own `params` value in a slot is the one
252+
* judged, exactly as the run receives it. Read by the trigger routes and a
253+
* declared `type: 'flow'` endpoint, which share the builder, for flow start
254+
* admission's third question (`refuseUnreadableFlowStartRecords`).
255+
*/
256+
export function flowStartRecordKeys(automationContext: Record<string, unknown>): {
257+
objectName: unknown;
258+
recordKeys: FlowStartRecordKeys;
259+
} {
260+
const params = (automationContext.params ?? {}) as Record<string, unknown>;
261+
const objectName = automationContext.object;
262+
const alias = recordIdAlias(objectName);
263+
const recordKeys: Array<readonly [string, unknown]> = [['recordId', params.recordId]];
264+
if (alias !== undefined) recordKeys.push([alias, params[alias]]);
265+
return { objectName, recordKeys };
266+
}
267+
228268
export function createAutomationDomain(deps: DomainHandlerDeps): DomainRoute {
229269
return {
230270
prefix: '/automation',
@@ -2680,7 +2720,21 @@ async function respondToFlowTrigger(
26802720
}),
26812721
};
26822722
}
2683-
const result = await automationService.execute(flowName, buildAutomationContext(body, context));
2723+
const automationContext = buildAutomationContext(body, context);
2724+
// Flow start admission's third question, the row this start addresses:
2725+
// every row slot the built context carries is loaded in the caller's own
2726+
// scope, by the read the action door's subject load makes, and refused with
2727+
// its `404 RECORD_NOT_FOUND` BEFORE `execute()`, so a refused start has no
2728+
// run. Thrown, like the builder's own refusal above, and answered by the
2729+
// dispatcher with its code and status.
2730+
await refuseUnreadableFlowStartRecords(
2731+
automationService,
2732+
flowName,
2733+
flowStartRecordKeys(automationContext),
2734+
context?.executionContext,
2735+
(object, id) => callData(deps, context, 'get', { object, id }, context?.dataDriver, context?.environmentId, context?.executionContext),
2736+
);
2737+
const result = await automationService.execute(flowName, automationContext);
26842738
const refusal = classifyFlowRefusal(flowName, result);
26852739
if (refusal) {
26862740
// The run's own artefacts ride the 400 arm ONLY — they describe a run

‎packages/runtime/src/endpoint-executor.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,10 @@ import { INTERNAL_ERROR_MESSAGE, looksLikeInternalErrorLeak, resolveThrownHttpEr
5353
import { apiErrorResponse } from './error-envelope.js';
5454
import { isServiceServeable } from './service-serveable.js';
5555
import { validationFailure } from './validation-failure.js';
56-
import { buildAutomationContext } from './domains/automation.js';
56+
import { buildAutomationContext, flowStartRecordKeys } from './domains/automation.js';
57+
// The row a start addresses — flow start admission's third question, the action
58+
// door's caller-scope load and refusal, asked by every door that starts a flow.
59+
import { refuseUnreadableFlowStartRecords } from './action-execution.js';
5760
import {
5861
classifyFlowRefusal,
5962
flowFailureDetails,
@@ -577,6 +580,20 @@ async function executeFlow(
577580
}
578581

579582
const automationContext = buildAutomationContext(ctx.body, ctx.protocolContext) as AutomationContext;
583+
// The third question every door that starts a flow by name asks, after the
584+
// two above and before `execute()`: each row slot the built context carries
585+
// (the same builder, so the same slots the trigger route judges) is loaded
586+
// in the caller's own scope through this endpoint's own data seam, and
587+
// refused with the action door's `404 RECORD_NOT_FOUND`, so a refused start
588+
// has no run. Thrown, and mapped by `executeEndpointTarget`'s one error path
589+
// like the builder's own refusal.
590+
await refuseUnreadableFlowStartRecords(
591+
service,
592+
plan.flow,
593+
flowStartRecordKeys(automationContext as Record<string, unknown>),
594+
ctx.executionContext,
595+
(object, id) => deps.callData('get', { object, id }, ctx.dataDriver, ctx.environmentId, ctx.executionContext),
596+
);
580597
const result = await automation.execute(plan.flow, automationContext);
581598

582599
// [#9462] Rows 2-4, read off the PRODUCER's classification through the one

‎packages/runtime/src/flow-start-admission.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,26 @@
3838
* gate, which answers first (`actionPermissionError`), so a caller at that
3939
* door needs both lists.
4040
*
41+
* ## The third question: the row a start addresses
42+
*
43+
* The two rules above judge the caller against the FLOW. A start that names a
44+
* record also hands the run a row, and a `runAs: 'system'` run reads and
45+
* writes that row past the caller's own access. So every door asks a third
46+
* question after them, through ONE function,
47+
* `refuseUnreadableFlowStartRecords` (`action-execution.ts`): every record key
48+
* the door hands the run in a row slot it defines (`recordId`, the
49+
* `<object>Id` alias, an action's declared `recordIdParam`) is first loaded in
50+
* the CALLER's own scope, and a key that scope does not deliver is refused
51+
* with the action door's own `404 RECORD_NOT_FOUND`, before `execute()`, so a
52+
* refused start persists no run. It is the action door's subject load
53+
* (`loadActionSubjectRecord`) and its refusal (`refuseDeniedSubjectLoad`),
54+
* asked of the keys the action door did not load itself, and asked at the
55+
* trigger routes and a declared endpoint too: a door that hands a run a row
56+
* the caller has not shown it can read is the gap this module exists to close.
57+
* It lives beside the load it reuses, so this module imports nothing from
58+
* `action-execution.ts` and the two stay a one-way edge; the declaration it
59+
* reads is this module's ({@link flowRunsElevated}).
60+
*
4161
* ## Why a module, and why every door asks it
4262
*
4363
* The same reason `flow-dispatch-status.ts` is one: a rule each door spells
@@ -135,6 +155,25 @@ export function isElevatedSelfTriggered(flow: { type?: FlowParsed['type']; runAs
135155
return flow.runAs === 'system' && flow.type !== undefined && SELF_TRIGGERED_FLOW_TYPES.has(flow.type);
136156
}
137157

158+
/**
159+
* Whether `flowName` is declared `runAs: 'system'`, read through the
160+
* automation service's own `getFlow`, the probe {@link flowStartRefusal} reads.
161+
* `false` when the service cannot be asked (no `getFlow`) or serves no such
162+
* flow: an undeclared run is the parsed default, `user`, and a door that
163+
* cannot read the declaration dispatches as before.
164+
*
165+
* The third question's one reading of the declaration
166+
* (`refuseUnreadableFlowStartRecords`): a start that names a record key but
167+
* no object to load it from cannot be judged, which is refused for an
168+
* elevated run only. A user run reads in the caller's own scope.
169+
*/
170+
export async function flowRunsElevated(automation: unknown, flowName: string): Promise<boolean> {
171+
const svc = automation as { getFlow?: (name: string) => Promise<unknown> } | null | undefined;
172+
if (typeof svc?.getFlow !== 'function') return false;
173+
const flow = (await svc.getFlow(flowName)) as { runAs?: unknown } | null | undefined;
174+
return flow?.runAs === 'system';
175+
}
176+
138177
/**
139178
* THE CHECK every door that starts a flow by name asks: the refusal it
140179
* answers for this caller starting `flowName`, or `null` when the start is

0 commit comments

Comments
 (0)