diff --git a/.changeset/flow-action-record-load-signal.md b/.changeset/flow-action-record-load-signal.md new file mode 100644 index 00000000000..3fad8859425 --- /dev/null +++ b/.changeset/flow-action-record-load-signal.md @@ -0,0 +1,43 @@ +--- +"@objectstack/runtime": minor +"@objectstack/spec": patch +--- + +feat(runtime): a flow action's run context now carries `recordLoadDenied` (#15168) + +The previous release declared `AutomationContext.recordLoadDenied?: true` and +said so plainly: **declared, not yet populated on the flow face.** The +script/body face of both action doors emitted the signal, but +`dispatchFlowAction` handed `automation.execute` a context without it, so a +`runAs: 'system'` flow that guarded on the documented key was inert — never +`true`, never wrong, and indistinguishable from a flow whose caller could read +the row. + +**This release populates it, on both doors in one stroke** — REST +`POST /api/v1/actions/...` and the MCP `run_action` bridge: + +```js +// a runAs:'system' flow, guarding before it acts on the subject row +if (context.recordLoadDenied === true) { /* the invoker cannot read this row */ } +``` + +- **The exact producer shape, unchanged.** The one shared producer + (`loadActionSubjectRecord` → `actionRecordLoadSignal`) already returns + `{ recordLoadDenied?: true }`, and the flow door now spreads it as a + **sibling of `record`** — never a key on the record, and **absent**, never + `false`, when nothing was refused. So a flow reads it exactly as a handler + does, `recordLoadDenied === true`. +- **Both doors, structurally.** `dispatchFlowAction`'s wiring now takes the + load OUTCOME (`subject`) instead of a bare `record`, and derives both the + record and the signal from it. A caller can no longer forward the row while + dropping the verdict that says the caller could not read it — the omission is + a compile error rather than a guard silently inert one door over, which is + the defect the handler-face signal was filed for. +- **Purely additive.** Nothing is refused that was not refused before, no + existing key changes value, and the `recordId` stamp is deliberately kept: + `record.id` still arrives exactly as it did, which is why the flag — and not + `record.id` — is the authorization predicate. Whether the automation engine + *acts* on the key (a flow-level refusal, a step condition) is a separate + decision and is deliberately not part of this change. +- **`@objectstack/spec` (docs only).** The contract's "not yet populated on the + flow face" sentence is retired; no type changes. diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 13d66a752c3..f3b123f7a39 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -787,20 +787,32 @@ export function isFlowActionRefusal(e: unknown): e is FlowActionRefusal { * flow ACTION and triggering its flow directly must land the same run, or * "the actions endpoint dispatches flows for you" is a claim the runtime * doesn't keep. + * + * [#15168] **The wiring takes the subject LOAD, not a bare record.** The flow + * face of #14143's signal (`AutomationContext.recordLoadDenied`, declared by + * #14244) is derived here, once, from {@link loadActionSubjectRecord}'s + * outcome — so a caller cannot hand this door a record while dropping the + * verdict that says the caller could not read it. Both call sites already held + * that outcome and were passing `subject.record` out of it; taking the whole + * `subject` removes the second de-facto source rather than adding a key beside + * it, and makes the omission a compile error instead of a silent inertness one + * door over (the shape #14143 was filed for). */ export async function dispatchFlowAction(deps: ActionExecutionDeps, requestContext: HttpProtocolContext, action: any, wiring: { objectName: string; - record: Record; + /** The caller-scope load outcome — `record` AND its verdict, from ONE producer. */ + subject: ActionSubjectRecordLoad; params: Record; recordId?: string; ec: any; envId?: string; }, ): Promise { - const { objectName, record, params, recordId, ec, envId } = wiring; + const { objectName, subject, params, recordId, ec, envId } = wiring; + const record = subject.record; const automation = await resolveAutomationService(deps, requestContext, envId); if (!automation) { throw new Error(flowActionUnavailableError(action)); @@ -819,6 +831,15 @@ export async function dispatchFlowAction(deps: ActionExecutionDeps, // `triggerData` envelope). const result: any = await automation.execute(action.target, { record, + // [#15168] The caller-scope load's verdict, a SIBLING of `record` — + // never a key on it, and spread so it is ABSENT rather than `false` + // when nothing was refused (`AutomationContext.recordLoadDenied` is + // `true | undefined`; a flow reads `recordLoadDenied === true`). The + // same producer, the same spelling and the same absence convention the + // handler face already carries at the two script-body call sites — the + // flow face is where the declared key had no populator at all, so a + // `runAs: 'system'` flow guarding on it was inert, never wrong. + ...actionRecordLoadSignal(subject), ...(isObjectLessActionKey(objectName) ? {} : { object: objectName }), userId: ec?.userId, ...(Array.isArray(ec?.positions) && ec.positions.length ? { positions: ec.positions } : {}), @@ -1404,7 +1425,10 @@ export async function invokeBusinessAction(deps: ActionExecutionDeps, // ── flow dispatch ── (shared with the REST /actions route, #3915) if (action.type === 'flow') { - const result = await dispatchFlowAction(deps, requestContext, action, { objectName, record, params, recordId, ec, envId }); + // [#15168] `subject`, not `record`: the shared door derives the flow + // context's `record` AND its `recordLoadDenied` sibling from the one + // load outcome, so this door cannot forward the row without the verdict. + const result = await dispatchFlowAction(deps, requestContext, action, { objectName, subject, params, recordId, ec, envId }); return { ok: true, action: action.name, objectName, ...(recordId ? { recordId } : {}), result }; } diff --git a/packages/runtime/src/action-record-load-denied.test.ts b/packages/runtime/src/action-record-load-denied.test.ts index 98714a023cf..0f1738b8e5a 100644 --- a/packages/runtime/src/action-record-load-denied.test.ts +++ b/packages/runtime/src/action-record-load-denied.test.ts @@ -44,6 +44,14 @@ * dispatcher sets but the sandbox never marshals would read as `undefined` * inside every body, re-manufacturing the always-false guard. Pinned by * running a real QuickJS body. + * 5. **[#15168] The FLOW face carries it too, on both doors.** #14244 declared + * `AutomationContext.recordLoadDenied` and nothing populated it: a + * `type: 'flow'` action reached `automation.execute` with the stamped + * `record.id` and no verdict, so a `runAs: 'system'` flow guarding on the + * declared key was inert — never `true`, never wrong, and indistinguishable + * from a flow whose caller could read the row. The last describe blocks + * read the context the automation service is actually handed, through BOTH + * doors, and pin that the two agree. * * ## The RLS double is faithful on the one point that matters * @@ -82,7 +90,23 @@ const ACTION = { target: 'close_case', ai: { exposed: true, description: 'Close a case.' }, }; -const OBJECT_DEF = { name: 'crm_case', actions: [ACTION] }; +/** + * [#15168] The same subject row, reached through a `type: 'flow'` action — the + * FLOW face of the signal. Declared on the same object as the script action so + * both faces run against the ONE row-scoped engine double below: a rig that + * gave the flow tests their own, more permissive read path could report a + * populated key that production never populates. + */ +const FLOW_NAME = 'crm_case_escalate_wizard'; +const FLOW_ACTION = { + name: 'escalate_case', + label: 'Escalate', + objectName: 'crm_case', + type: 'flow', + target: FLOW_NAME, + ai: { exposed: true, description: 'Escalate a case.' }, +}; +const OBJECT_DEF = { name: 'crm_case', actions: [ACTION, FLOW_ACTION] }; /** The acting principal, as `resolveExecutionContext` builds one. */ function ec(userId: string) { @@ -311,3 +335,177 @@ describe('#14143 — the signal crosses into a sandboxed action body', () => { expect(out.id).toBe(RECORD_ID); }); }); + +/** + * [#15168] An automation service double that RECORDS the context it is handed. + * `getFlow` resolves the one held flow so the #9378 not-found row (404) never + * fires; `execute` succeeds, because what is under test is the context that + * reaches the engine, not the engine's verdict. + */ +function makeAutomation() { + const execute = vi.fn(async (_flow: string, _context?: any) => ({ success: true, output: {} })); + const getFlow = vi.fn(async (name: string) => (name === FLOW_NAME ? { name } : null)); + return { execute, getFlow }; +} + +/** The context `automation.execute` was handed on its first (only) call. */ +function flowContextOf(automation: { execute: any }) { + return automation.execute.mock.calls[0]?.[1]; +} + +/** REST — `POST /actions/crm_case/escalate_case/case_1` with a flow action. */ +async function dispatchRestFlow(userId: string, ql: any, path = `/crm_case/escalate_case/${RECORD_ID}`) { + const automation = makeAutomation(); + const metadata: any = { + load: vi.fn(async () => null), + loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })), + listObjects: vi.fn(async () => [OBJECT_DEF]), + getObject: vi.fn(async (n: string) => (n === OBJECT_DEF.name ? OBJECT_DEF : undefined)), + }; + const resolve = (n: string) => + n === 'objectql' || n === 'data' ? ql + : n === 'metadata' ? metadata + : n === 'automation' ? automation + : null; + const kernel: any = { getService: resolve, getServiceAsync: async (n: string) => resolve(n), context: { getService: resolve } }; + const context: any = { request: {}, environmentId: 'platform', executionContext: ec(userId) }; + const res: any = await (new HttpDispatcher(kernel) as any).handleActions(path, 'POST', {}, context); + return { response: res.response, automation, flowCtx: flowContextOf(automation) }; +} + +/** MCP — `run_action` on the same flow action, through the REAL `callData`. */ +async function dispatchMcpFlow(userId: string, ql: any, input: Record = { recordId: RECORD_ID }) { + const automation = makeAutomation(); + const deps: any = { + resolveService: async (_ctx: any, name: string) => (name === 'automation' ? automation : undefined), + getObjectQL: async () => ql, + }; + const requestContext: any = { request: {}, environmentId: 'platform' }; + const caller = ec(userId); + await invokeBusinessAction(deps, requestContext, FLOW_ACTION.name, input as any, { + driver: undefined, + envId: 'platform', + ec: caller, + getMeta: () => ({ listObjects: async () => [OBJECT_DEF] }), + callData: (action, params, dataDriver, scopeId, execCtx) => + callData(deps, requestContext, action, params, dataDriver, scopeId, execCtx), + }); + return { automation, flowCtx: flowContextOf(automation) }; +} + +describe('[#15168] the FLOW face receives the signal — REST /actions', () => { + it('a caller who CANNOT read the row starts the flow with ctx.recordLoadDenied === true', async () => { + const ql = makeQl(); + const { automation, flowCtx } = await dispatchRestFlow(STRANGER, ql); + + expect(automation.execute).toHaveBeenCalledTimes(1); + expect(automation.execute.mock.calls[0][0]).toBe(FLOW_NAME); + expect(flowCtx).toBeDefined(); + // The contract's own predicate, verbatim (`AutomationContext`): a flow + // reads `recordLoadDenied === true`, never a truthiness of `false`. + expect(flowCtx.recordLoadDenied).toBe(true); + + // ⛔ Sibling of `record`, never a key ON it — a flow node reading + // `{{record.recordLoadDenied}}` must find nothing, or the signal would + // arrive as a phantom field of the subject row. + expect('recordLoadDenied' in flowCtx.record).toBe(false); + + // The stamp survives here exactly as it does on the handler face — it + // is why `record.id` cannot be the authorization predicate. + expect(flowCtx.record.id).toBe(RECORD_ID); + expect(flowCtx.record.status).toBeUndefined(); + expect(flowCtx.record.owner_id).toBeUndefined(); + // The rest of the envelope is untouched by this card. + expect(flowCtx.object).toBe(OBJECT_DEF.name); + expect(flowCtx.userId).toBe(STRANGER); + }); + + it('the row OWNER starts the flow with the key ABSENT — not `false`', async () => { + const ql = makeQl(); + const { flowCtx } = await dispatchRestFlow(OWNER, ql); + + expect(flowCtx.record).toMatchObject({ id: RECORD_ID, status: 'open', owner_id: OWNER }); + // The assertion that catches the most likely wrong implementation — + // spreading `{ recordLoadDenied: false }`. Its firing positive control + // is the case above: same rig, same expectation shape, reports `true`. + expect('recordLoadDenied' in flowCtx).toBe(false); + expect(flowCtx.recordLoadDenied).toBeUndefined(); + }); + + it('a record-less flow invocation attempts no load and carries no flag', async () => { + const ql = makeQl(); + const { flowCtx } = await dispatchRestFlow(STRANGER, ql, '/crm_case/escalate_case'); + + expect(flowCtx.record).toEqual({}); + expect('recordLoadDenied' in flowCtx).toBe(false); + expect(ql.find.mock.calls.filter((c: any[]) => c[0] === OBJECT_DEF.name)).toHaveLength(0); + }); +}); + +describe('[#15168] the FLOW face receives the signal — MCP run_action', () => { + it('a caller who CANNOT read the row starts the flow with ctx.recordLoadDenied === true', async () => { + const ql = makeQl(); + const { automation, flowCtx } = await dispatchMcpFlow(STRANGER, ql); + + expect(automation.execute).toHaveBeenCalledTimes(1); + expect(flowCtx.recordLoadDenied).toBe(true); + expect('recordLoadDenied' in flowCtx.record).toBe(false); + expect(flowCtx.record.id).toBe(RECORD_ID); // stamp preserved + expect(flowCtx.record.status).toBeUndefined(); + }); + + it('the row OWNER starts the flow with the key ABSENT — not `false`', async () => { + const ql = makeQl(); + const { flowCtx } = await dispatchMcpFlow(OWNER, ql); + + expect(flowCtx.record).toMatchObject({ id: RECORD_ID, status: 'open' }); + expect('recordLoadDenied' in flowCtx).toBe(false); + expect(flowCtx.recordLoadDenied).toBeUndefined(); + }); + + it('a record-less flow invocation attempts no load and carries no flag', async () => { + const ql = makeQl(); + const { flowCtx } = await dispatchMcpFlow(STRANGER, ql, {}); + + expect(flowCtx.record).toEqual({}); + expect('recordLoadDenied' in flowCtx).toBe(false); + }); +}); + +/** + * [#15168] The convergence itself. A per-door assertion is satisfied by two + * copies of a rule, and two copies drifting apart is the defect #14143 was + * filed for and the reason this card had to move both doors in one stroke — so + * the SAME caller against the SAME row is driven through both doors and the + * signal is compared as a set. + */ +describe('[#15168] the two flow doors agree — the same caller, the same row, the same signal', () => { + it('both doors deny for the stranger and both stay silent for the owner', async () => { + const deniedRest = (await dispatchRestFlow(STRANGER, makeQl())).flowCtx; + const deniedMcp = (await dispatchMcpFlow(STRANGER, makeQl())).flowCtx; + const okRest = (await dispatchRestFlow(OWNER, makeQl())).flowCtx; + const okMcp = (await dispatchMcpFlow(OWNER, makeQl())).flowCtx; + + // Read as a SET: a collapse to one answer on both doors reddens here + // whatever that one answer is. + expect([ + deniedRest.recordLoadDenied, + deniedMcp.recordLoadDenied, + okRest.recordLoadDenied, + okMcp.recordLoadDenied, + ]).toEqual([true, true, undefined, undefined]); + + expect([ + 'recordLoadDenied' in deniedRest, + 'recordLoadDenied' in deniedMcp, + 'recordLoadDenied' in okRest, + 'recordLoadDenied' in okMcp, + ]).toEqual([true, true, false, false]); + + // And the stamp is present on all four, which is what makes the flag — + // not `record.id` — the only usable predicate on either door. + expect([ + deniedRest.record.id, deniedMcp.record.id, okRest.record.id, okMcp.record.id, + ]).toEqual([RECORD_ID, RECORD_ID, RECORD_ID, RECORD_ID]); + }); +}); diff --git a/packages/runtime/src/actions-flow-dispatch-status.test.ts b/packages/runtime/src/actions-flow-dispatch-status.test.ts index 54e8c449d48..921eaf2b3a3 100644 --- a/packages/runtime/src/actions-flow-dispatch-status.test.ts +++ b/packages/runtime/src/actions-flow-dispatch-status.test.ts @@ -456,7 +456,11 @@ describe("#9585 — the failed run's artefacts ride BOTH doors' 400 details", () let thrown: unknown; try { await dispatchFlowAction(deps, {} as any, flowAction, { - objectName: 'crm_lead', record: {}, params: {}, ec: {}, envId: 'platform', + // [#15168] The wiring takes the subject LOAD outcome, not a bare + // record — a record-less dispatch is `recordLoadDenied: false`, + // which is the same run this assertion always made. + objectName: 'crm_lead', subject: { record: {}, recordLoadDenied: false }, + params: {}, ec: {}, envId: 'platform', }); } catch (e) { thrown = e; diff --git a/packages/runtime/src/domains/actions.ts b/packages/runtime/src/domains/actions.ts index a8670a18ce9..09cc10600c0 100644 --- a/packages/runtime/src/domains/actions.ts +++ b/packages/runtime/src/domains/actions.ts @@ -684,7 +684,12 @@ export async function handleActionsRequest(deps: DomainHandlerDeps, path: string try { result = await actionExec.dispatchFlowAction(deps, _context, actionDef, { objectName, - record, + // [#15168] `subject`, not `record` — the shared door derives + // the flow context's `record` AND its `recordLoadDenied` + // sibling from the same load outcome, so this door and the + // MCP one cannot diverge on the signal the way the two + // doors diverged before #14143. + subject, params: reqParams, recordId, ec, diff --git a/packages/spec/src/contracts/automation-context-record-load-denied.pin.test.ts b/packages/spec/src/contracts/automation-context-record-load-denied.pin.test.ts index 89cc9e23a65..086e1bfe8c0 100644 --- a/packages/spec/src/contracts/automation-context-record-load-denied.pin.test.ts +++ b/packages/spec/src/contracts/automation-context-record-load-denied.pin.test.ts @@ -23,15 +23,21 @@ * unless this file is compiled — and it is: `tsconfig.test.json` includes * `src/**`, and its ledger (`test-typecheck-debt.json`) lists this file * nowhere, so the file must compile with exactly zero errors. - * 4. **The JSDoc says who sets it and that the flow face does not yet - * populate it.** Prose is unassertable except by reading it; the contract - * source is read and the doc block above the key is required to name the - * producer and the not-yet-populated state, so the day the runtime half - * lands, this test tells its author which sentence to retire. + * 4. **The JSDoc says who sets it, and that the flow face now populates it.** + * Prose is unassertable except by reading it; the contract source is read + * and the doc block above the key is required to name the producer and the + * populated state. [#15168] This assertion used to require the opposite — + * a "NOT YET POPULATED" sentence — precisely so that the day the runtime + * half landed, this test would tell its author which sentence to retire. + * It did; the sentence is retired, and the pin now refuses its return. * - * ⛔ Not pinned, deliberately: that any flow run actually RECEIVES the key. - * That is the runtime half (`dispatchFlowAction` / the REST `/actions` door - * passing the producer's signal into the run's context), a separate card. + * ⛔ Not pinned HERE, deliberately: that any flow run actually RECEIVES the + * key. That is the runtime half's own pin — `packages/runtime`'s + * `action-record-load-denied.test.ts` drives both doors (`dispatchFlowAction` + * via REST `/actions` and via the MCP `run_action` bridge) against a + * row-scoped engine and reads the context the automation service is handed. + * A type-level contract test cannot assert a runtime wiring, and a copy of + * that assertion here would be a second, weaker one. */ import { readFileSync } from 'node:fs'; @@ -86,7 +92,7 @@ describe('[#14244] AutomationContext.recordLoadDenied mirrors the producer signa expect(seen).toEqual([true, undefined]); }); - it('the contract JSDoc names the producer, both doors, and the not-yet-populated flow face', () => { + it('the contract JSDoc names the producer, both doors, and the now-populated flow face', () => { const source = readFileSync(fileURLToPath(new URL('./automation-service.ts', import.meta.url)), 'utf8'); const declaration = 'recordLoadDenied?: true;'; const at = source.indexOf(declaration); @@ -103,8 +109,14 @@ describe('[#14244] AutomationContext.recordLoadDenied mirrors the producer signa expect(doc).toMatch(/both doors/i); expect(doc).toMatch(/run_action/); expect(doc).toMatch(/runAs: 'system'/); - // The honesty clause: declared, not yet populated on the flow face. - expect(doc).toMatch(/NOT YET POPULATED/); + // [#15168] The honesty clause, now the other way round: the runtime half + // landed, so the doc must say the flow face IS populated and must no longer + // carry the retired sentence. Both directions are asserted — the positive + // alone would survive a doc that says both things at once, and the negative + // alone is satisfied by deleting the paragraph altogether, which is how a + // contract loses the record of who populates a key. + expect(doc).toMatch(/Populated on the flow face/); + expect(doc).not.toMatch(/NOT YET POPULATED/); expect(doc).toContain('dispatchFlowAction'); // Absence semantics, in the handler face's own words. expect(doc).toMatch(/never\s+\*?\s*`false`/); diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 1bb555b762f..79fc24b72a4 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -53,12 +53,11 @@ export interface AutomationContext { * nothing both arrive as `RECORD_NOT_FOUND`, deliberately, and the key does * not pretend to separate them. * - * Declared, NOT YET POPULATED on the flow face: the handler face carries it - * today, but `dispatchFlowAction` still hands `automation.execute` a context - * without it, so until the runtime half lands a flow run never sees this key - * and a guard on it is inert (never `true`), never wrong. Additive — no - * existing key changes value. Callers other than the action dispatcher do - * NOT set this. + * Populated on the flow face since #15168: `dispatchFlowAction` takes the + * producer's load outcome and spreads the signal into the context it hands + * `automation.execute`, on both doors, so a flow run receives this key + * exactly when a handler would. Additive — no existing key changes value. + * Callers other than the action dispatcher do NOT set this. */ recordLoadDenied?: true; /**