From c116ccb5847801127785a29dc0b0b7a591421819 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 9 Oct 2026 04:46:36 +0000 Subject: [PATCH 1/5] test(runtime): measure the action door, run_action and the declared flow endpoint against elevated flows The before-table, measured on a real kernel before either door asks anything of the caller. A signed-in member with no grant on the target object starts a runAs-system flow of each self-triggered type (autolaunched, record_change, schedule) through an action of type flow (REST and the MCP run_action tool) and through a declared endpoint of type flow (authRequired true): every row answers 200 and the elevated write lands, while the member's own create is refused 403. screen and api flows, a runAs-user control and a screen parent calling the elevated child as a subflow are measured alongside. The assertions are the readings; the fix commit flips the refused rows. Claude-Session: https://claude.ai/code/session_01BmsuLyUeuG5CNpZFMH1jzS Co-authored-by: Claude --- .../flow-door-elevated-start.dogfood.test.ts | 349 ++++++++++++++++++ .../src/action-flow-elevated-door.test.ts | 290 +++++++++++++++ 2 files changed, 639 insertions(+) create mode 100644 packages/qa/dogfood/test/flow-door-elevated-start.dogfood.test.ts create mode 100644 packages/verify/src/action-flow-elevated-door.test.ts diff --git a/packages/qa/dogfood/test/flow-door-elevated-start.dogfood.test.ts b/packages/qa/dogfood/test/flow-door-elevated-start.dogfood.test.ts new file mode 100644 index 00000000000..460708a2736 --- /dev/null +++ b/packages/qa/dogfood/test/flow-door-elevated-start.dogfood.test.ts @@ -0,0 +1,349 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// The two other doors that start a flow by name × a flow declared +// `runAs: 'system'`, per flow type, on a real boot: an action of +// `type: 'flow'` (REST `POST /api/v1/actions/:object/:action`, and the MCP +// `run_action` tool that reaches the same dispatch) and a declared endpoint of +// `type: 'flow'` (`authRequired: true`). +// +// The defect class: the trigger door refuses a non-system caller a +// `runAs: 'system'` flow whose type is self-triggered (`autolaunched`, +// `record_change`, `schedule`), but these two doors asked nothing of the kind, +// so the same signed-in member who is refused at the trigger door started the +// same elevated flow here, and its elevated write landed. +// +// Why dogfood and not `@objectstack/verify`: the verify harness composes no +// `MetadataPlugin`, and `matchEndpoint` (the declared endpoint's only door) +// is `NodeMetadataManager`'s member, so a declared endpoint cannot be reached +// there; nor does verify depend on `@objectstack/mcp`, which serves +// `run_action`. This package depends on both. The action door's system +// principal row, which needs the runtime's in-process dispatcher, is pinned +// in `@objectstack/verify`'s `action-flow-elevated-door.test.ts`. +// +// The fixture is neutral and throwaway: one object no fresh member is granted +// (a member's direct create on it is refused, which the first case pins as the +// control that makes every elevated write below meaningful), and one writer +// flow per type, each creating a ledger row named after itself. A row +// appearing is the elevated run's side effect; the run log is the other +// witness. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { MetadataPlugin } from '@objectstack/metadata'; +import { MCPServerPlugin } from '@objectstack/mcp'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import type { ApiEndpoint } from '@objectstack/spec/api'; +import type { Flow } from '@objectstack/spec/automation'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const BOOT_TIMEOUT = 120_000; + +const LEDGER = 'fdp_ledger'; +const WATCH = 'fdp_watch'; + +/** Granted to nobody but the platform admin: a member's direct create is refused. */ +const Ledger = ObjectSchema.create({ + name: LEDGER, + sharingModel: 'public_read_write', + label: 'Ledger', + pluralLabel: 'Ledgers', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +/** The object the flow actions hang on, and the one the record-change writer watches. Nothing writes it. */ +const Watch = ObjectSchema.create({ + name: WATCH, + sharingModel: 'public_read_write', + label: 'Watch', + pluralLabel: 'Watches', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +/** start → create_record(fdp_ledger, { name: }) → end. */ +function writer( + name: string, + type: Flow['type'], + runAs: 'system' | 'user', + startConfig?: Record, +): Flow { + return { + name, + label: name, + type, + status: 'active', + runAs, + nodes: [ + { id: 'start', type: 'start', label: 'Start', ...(startConfig ? { config: startConfig } : {}) }, + { id: 'write', type: 'create_record', label: 'Write', config: { objectName: LEDGER, fields: { name } } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'write' }, + { id: 'e2', source: 'write', target: 'end' }, + ], + } as Flow; +} + +const AUTO_SYS = 'fdp_auto_sys'; +const CHANGE_SYS = 'fdp_change_sys'; +const SCHED_SYS = 'fdp_sched_sys'; +const SCREEN_SYS = 'fdp_screen_sys'; +const API_SYS = 'fdp_api_sys'; +const AUTO_USER = 'fdp_auto_user'; +const PARENT_SCREEN = 'fdp_parent_screen'; + +const FLOWS: Flow[] = [ + writer(AUTO_SYS, 'autolaunched', 'system'), + // A watched object nobody writes and a cadence nobody reaches during a run: + // each of these two runs only when a door starts it. + writer(CHANGE_SYS, 'record_change', 'system', { objectName: WATCH, triggerType: 'record-after-update' }), + writer(SCHED_SYS, 'schedule', 'system', { schedule: { cron: '0 3 1 1 *' } }), + writer(SCREEN_SYS, 'screen', 'system'), + // ADR-0041: an `api` flow registers only with its per-flow secret. + writer(API_SYS, 'api', 'system', { secret: 'fdp-fixture-secret' }), + writer(AUTO_USER, 'autolaunched', 'user'), + // The route the ruling names for an author who wants members to start + // elevated logic: a declared entry (`screen`) that is not elevated itself, + // whose `subflow` node calls the elevated self-triggered child. + { + name: PARENT_SCREEN, + label: PARENT_SCREEN, + type: 'screen', + status: 'active', + runAs: 'user', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'sub', type: 'subflow', label: 'Elevated child', config: { flowName: AUTO_SYS } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'sub' }, + { id: 'e2', source: 'sub', target: 'end' }, + ], + } as Flow, +]; + +/** Every flow above, each reachable by one action and one declared endpoint. */ +const TARGETS = [AUTO_SYS, CHANGE_SYS, SCHED_SYS, SCREEN_SYS, API_SYS, AUTO_USER, PARENT_SCREEN] as const; +type Target = (typeof TARGETS)[number]; + +const actionOf = (flow: Target) => `run_${flow}`; +const endpointPathOf = (flow: Target) => `/apps/fdp/${flow.replace(/_/g, '-')}`; + +const ACTIONS = TARGETS.map((flow) => ({ + name: actionOf(flow), + label: `Run ${flow}`, + objectName: WATCH, + type: 'flow' as const, + target: flow, + ai: { exposed: true, description: `Starts the ${flow} fixture flow, which writes one ledger row named after itself.` }, +})); + +const ENDPOINTS: ApiEndpoint[] = TARGETS.map((flow) => ({ + name: `${flow}_api`, + path: `/api/v1${endpointPathOf(flow)}`, + method: 'POST', + summary: `Start ${flow}`, + description: `Starts ${flow} over HTTP.`, + type: 'flow', + target: flow, + authRequired: true, +})); + +const fixtureStack = defineStack({ + manifest: { + id: 'com.dogfood.flow-door-elevated-start', + namespace: 'fdp', + version: '0.0.0', + type: 'app', + name: 'Flow Door Elevated Start Fixture', + description: 'One ungranted object, one elevated writer flow per flow type, and an action and an endpoint naming each.', + }, + // ADR-0097: the record-change start node needs both capabilities. + requires: ['automation', 'triggers'], + objects: [Ledger, Watch], + flows: FLOWS, + actions: ACTIONS, + apis: ENDPOINTS, +} as never); + +let stack: VerifyStack; +let tempDir: string; +let admin: string; +let member: string; + +beforeAll(async () => { + tempDir = mkdtempSync(join(tmpdir(), 'os-fdp-')); + const artifactPath = join(tempDir, 'objectstack.json'); + writeFileSync(artifactPath, JSON.stringify(fixtureStack)); + stack = await bootStack(fixtureStack as never, { + automation: true, + extraPlugins: [ + // A declared endpoint is served only through `matchEndpoint`, which the + // metadata manager owns: the same artifact boot a deployment runs. + new MetadataPlugin({ + rootDir: tempDir, + watch: false, + artifactWatch: false, + registerSystemObjects: false, + artifactSource: { mode: 'local-file', path: artifactPath }, + }), + // The `'mcp'` service the `/mcp` route serves `run_action` through. + new MCPServerPlugin(), + ], + }); + admin = await stack.signIn(); + // The first user is the seeded dev admin, so this sign-up is a plain member: + // no permission set of the app's, only the platform's fallback baseline. + member = await stack.signUp('fdp-member@dogfood.test'); +}, BOOT_TIMEOUT); + +afterAll(async () => { + await stack?.stop().catch(() => undefined); + if (tempDir) rmSync(tempDir, { recursive: true, force: true }); +}); + +/** Ledger rows a writer flow named `flow` has created so far. */ +async function ledgerRows(flow: string): Promise { + return (await stack.rows(LEDGER, { name: flow })).length; +} + +/** Run-log entries the engine holds for `flow`. */ +async function runCount(flow: string): Promise { + const automation = stack.kernel.getService('automation') as { listRuns(name: string): Promise }; + return (await automation.listRuns(flow)).length; +} + +type Door = 'action' | 'run_action' | 'endpoint'; +type Caller = 'member' | 'admin'; + +interface Outcome { + /** The door's answer: the HTTP status, or for `run_action` the tool error's status (200 when it ran). */ + answer: number; + /** The ADR-0112 `error.code` on a refusal. */ + code?: string; + /** Ledger rows the request caused (the writer's side effect). */ + rows: number; + /** Run-log entries the request caused for the flow it named. */ + runs: number; +} + +/** A JSON-RPC MCP request over Streamable-HTTP (JSON response mode). */ +function mcpBody(method: string, params?: unknown, id = 1) { + return { jsonrpc: '2.0', id, method, ...(params !== undefined ? { params } : {}) }; +} + +/** Knock on `door` once as `token` for `flow`, and read the answer. */ +async function knock(door: Door, token: string, flow: Target): Promise<{ answer: number; code?: string }> { + if (door === 'action') { + const res = await stack.apiAs(token, 'POST', `/actions/${WATCH}/${actionOf(flow)}`, { params: {} }); + const body = (await res.json().catch(() => ({}))) as { error?: { code?: string } }; + return { answer: res.status, ...(res.status >= 400 && body.error?.code ? { code: body.error.code } : {}) }; + } + if (door === 'endpoint') { + const res = await stack.apiAs(token, 'POST', endpointPathOf(flow), {}); + const body = (await res.json().catch(() => ({}))) as { error?: { code?: string } }; + return { answer: res.status, ...(res.status >= 400 && body.error?.code ? { code: body.error.code } : {}) }; + } + const res = await stack.api('/mcp', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify( + mcpBody('tools/call', { name: 'run_action', arguments: { actionName: actionOf(flow), objectName: WATCH } }), + ), + }); + expect(res.status, `the MCP transport itself answered ${res.status}: ${await res.clone().text()}`).toBe(200); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rpc: any = await res.json(); + expect(rpc.error, `run_action JSON-RPC error: ${JSON.stringify(rpc.error)}`).toBeUndefined(); + if (rpc.result?.isError !== true) return { answer: 200 }; + const text = String(rpc.result?.content?.[0]?.text ?? ''); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let parsed: any; + try { + parsed = JSON.parse(text); + } catch { + parsed = undefined; + } + return { + answer: typeof parsed?.error?.status === 'number' ? parsed.error.status : 0, + ...(typeof parsed?.error?.code === 'string' ? { code: parsed.error.code } : {}), + }; +} + +/** Start `flow` through `door` as `caller` and measure what happened. */ +async function startAs(door: Door, caller: Caller, flow: Target, rowsOf: string = flow): Promise { + const rowsBefore = await ledgerRows(rowsOf); + const runsBefore = await runCount(flow); + const answer = await knock(door, caller === 'admin' ? admin : member, flow); + return { + ...answer, + rows: (await ledgerRows(rowsOf)) - rowsBefore, + runs: (await runCount(flow)) - runsBefore, + }; +} + +describe('control: the member cannot write the ledger directly', () => { + it('a direct create is refused PERMISSION_DENIED / 403', async () => { + let err: unknown; + try { + await stack.hooks.run(LEDGER, 'insert', { name: 'direct' }, { as: member }); + } catch (e) { + err = e; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const refusal = err as any; + expect(refusal?.code).toBe('PERMISSION_DENIED'); + expect(refusal?.statusCode ?? refusal?.status).toBe(403); + expect(await ledgerRows('direct')).toBe(0); + }); + + it('the declared endpoint still refuses an anonymous caller 401 before anything runs', async () => { + const runsBefore = await runCount(AUTO_SYS); + const res = await stack.api(endpointPathOf(AUTO_SYS), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: '{}', + }); + expect(res.status).toBe(401); + expect(await runCount(AUTO_SYS)).toBe(runsBefore); + }); +}); + +const RAN = { answer: 200, rows: 1, runs: 1 } as const; +/** A non-elevated writer: the member's own identity is refused the write, so the run fails. */ +const USER_FLOW_FAILED = { answer: 400, code: 'FLOW_FAILED', rows: 0, runs: 1 } as const; + +/** + * Door × caller × flow → what the door answers and what the request caused. + * MEASURED BEFORE the doors asked anything of the caller (this branch's first + * commit carries these readings as the assertions). + */ +const TABLE: Array<{ door: Door; caller: Caller; flow: Target; rowsOf?: string; outcome: Outcome }> = []; +for (const door of ['action', 'run_action', 'endpoint'] as const) { + TABLE.push( + { door, caller: 'member', flow: AUTO_SYS, outcome: RAN }, + { door, caller: 'member', flow: CHANGE_SYS, outcome: RAN }, + { door, caller: 'member', flow: SCHED_SYS, outcome: RAN }, + { door, caller: 'admin', flow: AUTO_SYS, outcome: RAN }, + { door, caller: 'member', flow: SCREEN_SYS, outcome: RAN }, + { door, caller: 'member', flow: API_SYS, outcome: RAN }, + { door, caller: 'member', flow: AUTO_USER, outcome: USER_FLOW_FAILED }, + { door, caller: 'member', flow: PARENT_SCREEN, rowsOf: AUTO_SYS, outcome: RAN }, + ); +} + +describe('the action door, run_action and the declared endpoint × runAs: system, per type and caller', () => { + for (const row of TABLE) { + it(`${row.door}: ${row.caller} starts ${row.flow} → ${row.outcome.answer}`, async () => { + expect(await startAs(row.door, row.caller, row.flow, row.rowsOf)).toEqual(row.outcome); + }); + } +}); diff --git a/packages/verify/src/action-flow-elevated-door.test.ts b/packages/verify/src/action-flow-elevated-door.test.ts new file mode 100644 index 00000000000..9d20e356e1c --- /dev/null +++ b/packages/verify/src/action-flow-elevated-door.test.ts @@ -0,0 +1,290 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The action door × a flow declared `runAs: 'system'`, per flow type and per + * caller, through `actions.run` — the in-process twin of + * `POST /api/v1/actions/:object/:action` (`handle.ts` drives the runtime's + * `HttpDispatcher`, so it answers through the same `dispatchFlowAction` the + * MCP `run_action` bridge reaches). + * + * The defect class: the trigger door refuses a non-system caller a + * `runAs: 'system'` flow whose type is self-triggered (`autolaunched`, + * `record_change`, `schedule`), but an action of `type: 'flow'` naming the + * same flow asked nothing of the kind, so any signed-in member started it and + * its elevated write landed. + * + * This is the wire half, on the real kernel — auth, security middleware, the + * real automation engine — so every row is a measurement: the door's answer, + * the elevated write that did or did not land, and the run log. It carries the + * row the dogfood half cannot: the system principal, an in-process caller only + * the runtime's dispatcher can stand in for. The dogfood half + * (`packages/qa/dogfood/test/flow-door-elevated-start.dogfood.test.ts`) adds + * the MCP `run_action` tool and the declared endpoint on a real boot. + * + * The fixture is neutral: one object no fresh member is granted (`fda_ledger`; + * a member's direct create on it is refused, which the first case pins as the + * control that makes every elevated write below meaningful), and one writer + * flow per type, each creating a ledger row named after itself, each named by + * one flow action. + * + * ⚠️ This suite resolves `@objectstack/runtime` and + * `@objectstack/service-automation` through their BUILT `dist/`. Rebuild both + * before trusting a run of this file — and especially an ablated one. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; + +import { HttpDispatcher } from '@objectstack/runtime'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import type { Flow } from '@objectstack/spec/automation'; + +import { bootStack, type VerifyStack } from './harness.js'; + +// Booting the full in-process stack runs well past vitest's 5s default. +const BOOT_TIMEOUT = 120_000; + +const LEDGER = 'fda_ledger'; +const WATCH = 'fda_watch'; + +/** Granted to nobody but the platform admin: a member's direct create is refused. */ +const Ledger = ObjectSchema.create({ + name: LEDGER, + sharingModel: 'public_read_write', + label: 'Ledger', + pluralLabel: 'Ledgers', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +/** The object the flow actions hang on, and the one the record-change writer watches. Nothing writes it. */ +const Watch = ObjectSchema.create({ + name: WATCH, + sharingModel: 'public_read_write', + label: 'Watch', + pluralLabel: 'Watches', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +/** start → create_record(fda_ledger, { name: }) → end. */ +function writer( + name: string, + type: Flow['type'], + runAs: 'system' | 'user', + startConfig?: Record, +): Flow { + return { + name, + label: name, + type, + status: 'active', + runAs, + nodes: [ + { id: 'start', type: 'start', label: 'Start', ...(startConfig ? { config: startConfig } : {}) }, + { id: 'write', type: 'create_record', label: 'Write', config: { objectName: LEDGER, fields: { name } } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'write' }, + { id: 'e2', source: 'write', target: 'end' }, + ], + } as Flow; +} + +const AUTO_SYS = 'fda_auto_sys'; +const CHANGE_SYS = 'fda_change_sys'; +const SCHED_SYS = 'fda_sched_sys'; +const SCREEN_SYS = 'fda_screen_sys'; +const API_SYS = 'fda_api_sys'; +const AUTO_USER = 'fda_auto_user'; +const PARENT_SCREEN = 'fda_parent_screen'; + +const FLOWS: Flow[] = [ + writer(AUTO_SYS, 'autolaunched', 'system'), + // A watched object nobody writes and a cadence nobody reaches during a run: + // each of these two runs only when a door starts it. + writer(CHANGE_SYS, 'record_change', 'system', { objectName: WATCH, triggerType: 'record-after-update' }), + writer(SCHED_SYS, 'schedule', 'system', { schedule: { cron: '0 3 1 1 *' } }), + writer(SCREEN_SYS, 'screen', 'system'), + // ADR-0041: an `api` flow registers only with its per-flow secret. + writer(API_SYS, 'api', 'system', { secret: 'fda-fixture-secret' }), + writer(AUTO_USER, 'autolaunched', 'user'), + // The route an author takes to let members start elevated logic: a declared + // entry (`screen`) that is not elevated itself, whose `subflow` node calls + // the elevated self-triggered child. The child writes its own name. + { + name: PARENT_SCREEN, + label: PARENT_SCREEN, + type: 'screen', + status: 'active', + runAs: 'user', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'sub', type: 'subflow', label: 'Elevated child', config: { flowName: AUTO_SYS } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'sub' }, + { id: 'e2', source: 'sub', target: 'end' }, + ], + } as Flow, +]; + +const TARGETS = [AUTO_SYS, CHANGE_SYS, SCHED_SYS, SCREEN_SYS, API_SYS, AUTO_USER, PARENT_SCREEN] as const; +type Target = (typeof TARGETS)[number]; +const actionOf = (flow: Target) => `run_${flow}`; + +const fixtureStack = defineStack({ + manifest: { + id: 'com.objectstack.verify.action-flow-elevated-door', + namespace: 'fda', + version: '0.0.0', + type: 'app', + name: 'Action Flow Elevated Door Fixture', + description: 'One ungranted object, one elevated writer flow per flow type, and a flow action naming each.', + }, + // ADR-0097: the record-change start node needs both capabilities. + requires: ['automation', 'triggers'], + objects: [Ledger, Watch], + flows: FLOWS, + actions: TARGETS.map((flow) => ({ + name: actionOf(flow), + label: `Run ${flow}`, + objectName: WATCH, + type: 'flow', + target: flow, + })), +} as never); + +let stack: VerifyStack; +let admin: string; +let member: string; + +beforeAll(async () => { + stack = await bootStack(fixtureStack as never, { automation: true }); + admin = await stack.signIn(); + // The first user is the seeded dev admin, so this sign-up is a plain member: + // no permission set of the app's, only the platform's fallback baseline. + member = await stack.signUp('fda-member@verify.test'); +}, BOOT_TIMEOUT); + +afterAll(async () => { + await stack?.stop().catch(() => undefined); +}); + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const codeOf = (e: unknown): string | undefined => (e as any)?.code; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const statusOf = (e: unknown): number | undefined => (e as any)?.statusCode ?? (e as any)?.status; + +/** Ledger rows a writer flow named `flow` has created so far. */ +async function ledgerRows(flow: string): Promise { + return (await stack.rows(LEDGER, { name: flow })).length; +} + +/** Run-log entries the engine holds for `flow`. */ +async function runCount(flow: string): Promise { + const automation = stack.kernel.getService('automation') as { listRuns(name: string): Promise }; + return (await automation.listRuns(flow)).length; +} + +type Caller = 'member' | 'admin' | 'system'; + +interface Outcome { + /** The door's HTTP answer. */ + answer: number; + /** The ADR-0112 `error.code` on a refusal. */ + code?: string; + /** Ledger rows the request caused (the writer's side effect). */ + rows: number; + /** Run-log entries the request caused for the flow it named. */ + runs: number; +} + +/** + * Start `flow` through its action as `caller` and measure what happened. + * + * `member` and `admin` go through `actions.run` with a bearer token, exactly + * as a console or SDK reaches the door. The system principal has no token: it + * is the in-process caller a job or an internal dispatch is, so its row drives + * the SAME route (`handleActions` → `dispatchFlowAction`) with the system + * execution context. + */ +async function startAs(caller: Caller, flow: Target, rowsOf: string = flow): Promise { + const rowsBefore = await ledgerRows(rowsOf); + const runsBefore = await runCount(flow); + let answer: number; + let code: string | undefined; + if (caller === 'system') { + const dispatcher = new HttpDispatcher(stack.kernel); + const res = await dispatcher.handleActions(`/${WATCH}/${actionOf(flow)}`, 'POST', { params: {} }, { + request: {}, + executionContext: { isSystem: true }, + } as never); + answer = res.response?.status ?? 0; + code = res.response?.body?.error?.code; + } else { + try { + await stack.actions.run(WATCH, actionOf(flow), { as: caller === 'admin' ? admin : member }); + answer = 200; + } catch (e) { + answer = statusOf(e) ?? 0; + code = codeOf(e); + } + } + return { + answer, + ...(code !== undefined ? { code } : {}), + rows: (await ledgerRows(rowsOf)) - rowsBefore, + runs: (await runCount(flow)) - runsBefore, + }; +} + +describe('control: the member cannot write the ledger directly', () => { + it('a direct create is refused PERMISSION_DENIED / 403', async () => { + let err: unknown; + try { + await stack.hooks.run(LEDGER, 'insert', { name: 'direct' }, { as: member }); + } catch (e) { + err = e; + } + expect(codeOf(err)).toBe('PERMISSION_DENIED'); + expect(statusOf(err)).toBe(403); + expect(await ledgerRows('direct')).toBe(0); + }); + + it('the member is not the system principal', async () => { + const ec = await stack.contextFor(member); + expect(ec.isSystem).not.toBe(true); + }); +}); + +const RAN = { answer: 200, rows: 1, runs: 1 } as const; + +/** + * Caller × flow → what the action door answers and what the request caused, + * MEASURED BEFORE the door asked anything of the caller (this branch's first + * commit carries these readings as the assertions). + */ +const TABLE: Array<{ caller: Caller; flow: Target; rowsOf?: string; outcome: Outcome }> = [ + { caller: 'member', flow: AUTO_SYS, outcome: RAN }, + { caller: 'member', flow: CHANGE_SYS, outcome: RAN }, + { caller: 'member', flow: SCHED_SYS, outcome: RAN }, + { caller: 'admin', flow: AUTO_SYS, outcome: RAN }, + { caller: 'admin', flow: CHANGE_SYS, outcome: RAN }, + { caller: 'admin', flow: SCHED_SYS, outcome: RAN }, + { caller: 'system', flow: AUTO_SYS, outcome: RAN }, + { caller: 'system', flow: CHANGE_SYS, outcome: RAN }, + { caller: 'system', flow: SCHED_SYS, outcome: RAN }, + { caller: 'member', flow: SCREEN_SYS, outcome: RAN }, + { caller: 'member', flow: API_SYS, outcome: RAN }, + { caller: 'member', flow: AUTO_USER, outcome: { answer: 400, code: 'FLOW_FAILED', rows: 0, runs: 1 } }, + { caller: 'member', flow: PARENT_SCREEN, rowsOf: AUTO_SYS, outcome: RAN }, +]; + +describe('the action door × runAs: system, per type and caller', () => { + for (const row of TABLE) { + it(`${row.caller} starts ${row.flow} through its action → ${row.outcome.answer}`, async () => { + expect(await startAs(row.caller, row.flow, row.rowsOf)).toEqual(row.outcome); + }); + } +}); From 75802e86d2fb6ebb2c2c501851520ee6ba528ead Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 9 Oct 2026 04:49:00 +0000 Subject: [PATCH 2/5] fix(example-showcase): declare the flow endpoint's elevated target an entry The example application's authenticated flow endpoint starts an elevated janitor flow on demand. Under the type x caller rule that every door starting a flow by name now applies, an elevated flow of a self-triggered type is refused to any caller but the system principal, so the endpoint's target is declared type screen: the explicit, reviewable statement that signed-in callers may start this elevated work. Its nodes, run-as declaration and the endpoint's declaration are unchanged. Claude-Session: https://claude.ai/code/session_01BmsuLyUeuG5CNpZFMH1jzS Co-authored-by: Claude --- .../app-showcase/src/automation/flows/index.ts | 16 ++++++++++++---- examples/app-showcase/src/system/apis/index.ts | 9 ++++++++- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/examples/app-showcase/src/automation/flows/index.ts b/examples/app-showcase/src/automation/flows/index.ts index be08d64ff11..7281115c5ee 100644 --- a/examples/app-showcase/src/automation/flows/index.ts +++ b/examples/app-showcase/src/automation/flows/index.ts @@ -1634,15 +1634,23 @@ export const InboundTaskWebhookFlow = defineFlow({ * by the same filter, and report. Config keys follow the executor contract * exactly — `objectName` + `filter` + the declared bulk intent `multi` * (Prime Directive #12: no `object`/`filters` aliases). `runAs: 'system'` - * because a janitor acts - * across owners; autolaunched with no record trigger — invoke it on demand - * (API/subflow) rather than on every write. + * because a janitor acts across owners. + * + * `type: 'screen'` because it IS an entry: a signed-in caller starts it on + * demand through `InquiryPurgeEndpoint` (`src/system/apis/index.ts`), with no + * record trigger and no cadence. An elevated flow of a self-triggered type + * (`autolaunched`, `record_change`, `schedule`) runs on its own trigger or as a + * `subflow` from a parent, and every door that starts a flow by name — the + * trigger route, a `type: 'flow'` action, a declared `type: 'flow'` endpoint — + * refuses it to any caller but the system principal (`403 PERMISSION_DENIED`). + * Declaring the type an entry is the explicit, reviewable statement that + * signed-in callers may start this elevated work. */ export const InquiryPurgeFlow = defineFlow({ name: 'showcase_inquiry_purge', label: 'Purge Closed Inquiries', description: 'Deletes inquiries already marked closed — demonstrates get_record + delete_record.', - type: 'autolaunched', + type: 'screen', runAs: 'system', nodes: [ { id: 'start', type: 'start', label: 'Start' }, diff --git a/examples/app-showcase/src/system/apis/index.ts b/examples/app-showcase/src/system/apis/index.ts index afb47a89d9e..4f0847c083c 100644 --- a/examples/app-showcase/src/system/apis/index.ts +++ b/examples/app-showcase/src/system/apis/index.ts @@ -95,7 +95,14 @@ export const TaskFeedEndpoint: ApiEndpoint = { cacheTtlSeconds: 30, }; -/** Flow-typed endpoint: POST triggers the janitor flow (get+delete demo). */ +/** + * Flow-typed endpoint: POST triggers the janitor flow (get+delete demo). + * + * The target runs `runAs: 'system'`, so it is declared `type: 'screen'` — an + * entry. A `type: 'flow'` endpoint refuses a signed-in caller an elevated flow + * of a self-triggered type (`autolaunched`, `record_change`, `schedule`) with + * `403 PERMISSION_DENIED`, exactly as the trigger route and a flow action do. + */ export const InquiryPurgeEndpoint: ApiEndpoint = { name: 'showcase_inquiry_purge_api', path: '/api/v1/apps/showcase/inquiries/purge', From 85a0bcded1aa93008f89508c1587439363557e4d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 9 Oct 2026 04:53:05 +0000 Subject: [PATCH 3/5] fix(runtime): the action door and the declared flow endpoint refuse a self-triggered system flow to a non-system caller The trigger door's type x caller rule now binds every door that starts a flow by name. An action of type flow (REST /actions and the MCP run_action bridge, which share one dispatch) and a declared endpoint of type flow refuse a caller that is not the system principal a flow declared runAs system whose type is autolaunched, record_change or schedule: 403 PERMISSION_DENIED, nothing dispatched. screen and api flows, flows not declared runAs system, a parent's subflow node and the system principal are unchanged. The predicate, the type set and the refusal move out of the trigger domain into one module all three doors call, so they cannot drift. The refusal's words lose the door's name so they read true at every door. Claude-Session: https://claude.ai/code/session_01BmsuLyUeuG5CNpZFMH1jzS Co-authored-by: Claude --- .../flow-door-elevated-start.dogfood.test.ts | 61 +++- packages/runtime/src/action-execution.ts | 24 ++ .../src/action-flow-elevated-door.test.ts | 293 ++++++++++++++++++ packages/runtime/src/domains/automation.ts | 100 +----- packages/runtime/src/endpoint-executor.ts | 24 ++ .../src/endpoint-flow-elevated-door.test.ts | 182 +++++++++++ packages/runtime/src/flow-start-admission.ts | 120 +++++++ .../src/action-flow-elevated-door.test.ts | 84 +++-- 8 files changed, 771 insertions(+), 117 deletions(-) create mode 100644 packages/runtime/src/action-flow-elevated-door.test.ts create mode 100644 packages/runtime/src/endpoint-flow-elevated-door.test.ts create mode 100644 packages/runtime/src/flow-start-admission.ts diff --git a/packages/qa/dogfood/test/flow-door-elevated-start.dogfood.test.ts b/packages/qa/dogfood/test/flow-door-elevated-start.dogfood.test.ts index 460708a2736..f7c6884e308 100644 --- a/packages/qa/dogfood/test/flow-door-elevated-start.dogfood.test.ts +++ b/packages/qa/dogfood/test/flow-door-elevated-start.dogfood.test.ts @@ -26,6 +26,10 @@ // flow per type, each creating a ledger row named after itself. A row // appearing is the elevated run's side effect; the run log is the other // witness. +// +// The table was MEASURED FIRST, before either door asked anything of the +// caller (this branch's first commit carries it as the assertion); each row's +// `before` comment is that reading. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; @@ -317,33 +321,66 @@ describe('control: the member cannot write the ledger directly', () => { }); }); +const REFUSED = { answer: 403, code: 'PERMISSION_DENIED', rows: 0, runs: 0 } as const; const RAN = { answer: 200, rows: 1, runs: 1 } as const; /** A non-elevated writer: the member's own identity is refused the write, so the run fails. */ const USER_FLOW_FAILED = { answer: 400, code: 'FLOW_FAILED', rows: 0, runs: 1 } as const; /** * Door × caller × flow → what the door answers and what the request caused. - * MEASURED BEFORE the doors asked anything of the caller (this branch's first - * commit carries these readings as the assertions). + * `before` is the reading this branch's first commit took before either door + * asked anything of the caller (the same for all three doors), so the change + * the check makes is visible row by row. */ -const TABLE: Array<{ door: Door; caller: Caller; flow: Target; rowsOf?: string; outcome: Outcome }> = []; +const TABLE: Array<{ door: Door; caller: Caller; flow: Target; rowsOf?: string; outcome: Outcome; before: string }> = []; for (const door of ['action', 'run_action', 'endpoint'] as const) { TABLE.push( - { door, caller: 'member', flow: AUTO_SYS, outcome: RAN }, - { door, caller: 'member', flow: CHANGE_SYS, outcome: RAN }, - { door, caller: 'member', flow: SCHED_SYS, outcome: RAN }, - { door, caller: 'admin', flow: AUTO_SYS, outcome: RAN }, - { door, caller: 'member', flow: SCREEN_SYS, outcome: RAN }, - { door, caller: 'member', flow: API_SYS, outcome: RAN }, - { door, caller: 'member', flow: AUTO_USER, outcome: USER_FLOW_FAILED }, - { door, caller: 'member', flow: PARENT_SCREEN, rowsOf: AUTO_SYS, outcome: RAN }, + // REFUSED — a signed-in member, the three self-triggered types. + { door, caller: 'member', flow: AUTO_SYS, outcome: REFUSED, before: '200, elevated row written' }, + { door, caller: 'member', flow: CHANGE_SYS, outcome: REFUSED, before: '200, elevated row written' }, + { door, caller: 'member', flow: SCHED_SYS, outcome: REFUSED, before: '200, elevated row written' }, + // REFUSED — the platform admin is a signed-in user too, not the system principal. + { door, caller: 'admin', flow: AUTO_SYS, outcome: REFUSED, before: '200, row written' }, + // UNCHANGED — `screen` and `api`: entries the author designed. + { door, caller: 'member', flow: SCREEN_SYS, outcome: RAN, before: '200, elevated row written' }, + { door, caller: 'member', flow: API_SYS, outcome: RAN, before: '200, elevated row written' }, + // UNCHANGED — a non-elevated flow. + { door, caller: 'member', flow: AUTO_USER, outcome: USER_FLOW_FAILED, before: '400 FLOW_FAILED, nothing written' }, + // UNCHANGED — the route the ruling names: a `screen` entry that is not + // elevated, whose `subflow` node runs the elevated child the door now + // refuses to start directly. The child writes its own name. + { door, caller: 'member', flow: PARENT_SCREEN, rowsOf: AUTO_SYS, outcome: RAN, before: '200, elevated child row written' }, ); } describe('the action door, run_action and the declared endpoint × runAs: system, per type and caller', () => { for (const row of TABLE) { - it(`${row.door}: ${row.caller} starts ${row.flow} → ${row.outcome.answer}`, async () => { + const verdict = row.outcome.answer === 403 ? 'refused 403 PERMISSION_DENIED, nothing ran' : `answers ${row.outcome.answer}`; + it(`${row.door}: ${row.caller} starts ${row.flow}: ${verdict} (before: ${row.before})`, async () => { expect(await startAs(row.door, row.caller, row.flow, row.rowsOf)).toEqual(row.outcome); }); } }); + +describe('one rule at every door that starts a flow by name', () => { + it('the action door, run_action and the declared endpoint answer the trigger door\'s refusal, word for word', async () => { + const trigger = await stack.apiAs(member, 'POST', `/automation/${SCHED_SYS}/trigger`, { params: {} }); + const triggerBody = (await trigger.json()) as { error?: { code?: string; message?: string } }; + expect(trigger.status).toBe(403); + expect(triggerBody.error?.code).toBe('PERMISSION_DENIED'); + + const action = await stack.apiAs(member, 'POST', `/actions/${WATCH}/${actionOf(SCHED_SYS)}`, { params: {} }); + const endpoint = await stack.apiAs(member, 'POST', endpointPathOf(SCHED_SYS), {}); + for (const res of [action, endpoint]) { + const body = (await res.json()) as { success?: boolean; data?: unknown; error?: { code?: string; message?: string } }; + expect(res.status).toBe(403); + expect(body.success).toBe(false); + expect(body).not.toHaveProperty('data'); + expect(body.error?.code).toBe('PERMISSION_DENIED'); + expect(body.error?.message).toBe(triggerBody.error?.message); + // Nothing of the flow: not its name, its type or its run-as declaration. + expect(body.error?.message).not.toContain(SCHED_SYS); + expect(body.error?.message).not.toMatch(/schedule|runAs|'system'/); + } + }); +}); diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 518ca427121..e241e514d0b 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -41,6 +41,9 @@ import { FLOW_NOT_FOUND_STATUS, type FlowRefusalCode, } from './flow-dispatch-status.js'; +// Who may START a flow by name — the one rule the trigger door, this door and +// the declared endpoint share (the maintainer's ruling, letters B and A). +import { ELEVATED_START_REFUSAL, refusesElevatedSelfTriggeredStart } from './flow-start-admission.js'; import type { FlowRunSummary } from '@objectstack/spec/automation'; // [#5138] The ONE 404 envelope a single-record path answers. Imported rather // than re-spelled so `callData`'s ObjectQL fallback and the protocol service it @@ -998,6 +1001,27 @@ export async function dispatchFlowAction(deps: ActionExecutionDeps, err.status = FLOW_NOT_FOUND_STATUS; throw err; } + // The caller × flow check (the maintainer's ruling, letter A: the trigger + // door's type × caller rule binds every door that starts a flow by name). + // A caller that is not the system principal may not start a flow declared + // `runAs: 'system'` whose type is self-triggered (`autolaunched`, + // `record_change`, `schedule`) — those run on their own trigger or as a + // sub-flow, so an action that names one is wiring, not an entry. AFTER + // existence (an unknown target keeps its 404) and BEFORE dispatch (a refused + // start runs nothing). Both entrances reach this one line — REST `/actions` + // and MCP `run_action` — and the action's own `requiredPermissions` gate + // (ADR-0066 D4) has already answered upstream of it at each. Holding that + // capability does not open such a target: an author who wants members to + // start elevated logic declares the target `screen` or `api`. Thrown with + // `code` + `status` so the ADR-0112 envelope survives both entrances, as + // the 409 / 422 rows below do; the words are the trigger door's own + // (`flow-start-admission.ts`). + if (await refusesElevatedSelfTriggeredStart(automation, action.target, ec)) { + throw Object.assign(new Error(ELEVATED_START_REFUSAL.message), { + status: ELEVATED_START_REFUSAL.status, + code: ELEVATED_START_REFUSAL.code, + }); + } // Pass a proper AutomationContext (the engine never read the former // `triggerData` envelope). const result: any = await automation.execute(action.target, { diff --git a/packages/runtime/src/action-flow-elevated-door.test.ts b/packages/runtime/src/action-flow-elevated-door.test.ts new file mode 100644 index 00000000000..78e56d0dcb5 --- /dev/null +++ b/packages/runtime/src/action-flow-elevated-door.test.ts @@ -0,0 +1,293 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The action door × a flow declared `runAs: 'system'`: a caller that is not + * the system principal may not start, through an action of `type: 'flow'`, one + * whose `type` is self-triggered (`autolaunched`, `record_change`, + * `schedule`) — the same type × caller rule the trigger door applies (the + * maintainer's ruling, letter A, extending letter B to every door that starts + * a flow by name). + * + * Both entrances to the door run every case: REST `POST /actions/:object/:action` + * (`HttpDispatcher.handleActions`) and the MCP `run_action` bridge + * (`invokeBusinessAction`). They reach one `dispatchFlowAction`, and a pin + * that covered only one of them would let the other drift unnoticed. + * + * These are the DOOR-side pins, driven with a scripted automation service so + * each one isolates the door's decision: `getFlow` serves the declaration the + * door reads, and `execute` is a spy, so "never dispatched" is a fact about the + * engine call rather than an inference from a status code. The wire half — the + * real kernel, a real member, a real engine, the elevated write that did or did + * not land — is `@objectstack/verify`'s `action-flow-elevated-door.test.ts` + * and the dogfood `flow-door-elevated-start.dogfood.test.ts`. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { resolveThrownHttpError } from '@objectstack/types'; + +import { HttpDispatcher } from './http-dispatcher.js'; +import { callData, invokeBusinessAction } from './action-execution.js'; + +const OBJECT = 'fda_watch'; +const FLOW = 'fda_target_flow'; +const ACTION = 'run_target'; + +/** A signed-in, non-system caller holding no capability. */ +const MEMBER_EC = { userId: 'user_1', systemPermissions: [] as string[] }; +/** The system principal: the in-process caller a job or an internal dispatch is. */ +const SYSTEM_EC = { isSystem: true }; + +const REFUSED_TYPES = ['autolaunched', 'record_change', 'schedule'] as const; +const DOOR_TYPES = ['screen', 'api'] as const; + +interface Declared { + type: string; + runAs?: string; +} + +/** + * One automation service, one object carrying one flow action, and both + * entrances to the door over them. `flow` is the declaration `getFlow` serves + * for the action's target (`null` = the service holds no such flow). + */ +function makeDoor(opts: { + flow: Declared | null; + omitGetFlow?: boolean; + requiredPermissions?: string[]; +}) { + const execute = vi.fn(async (_name: string, _context?: unknown) => ({ success: true, output: {} })); + const getFlow = vi.fn(async (name: string) => (name === FLOW && opts.flow ? { name, ...opts.flow } : null)); + const automation: Record = opts.omitGetFlow ? { execute } : { execute, getFlow }; + + const action = { + name: ACTION, + label: 'Run target', + objectName: OBJECT, + type: 'flow', + target: FLOW, + ai: { exposed: true, description: 'Starts the target flow on the watched object for this test.' }, + ...(opts.requiredPermissions ? { requiredPermissions: opts.requiredPermissions } : {}), + }; + const objectDef = { name: OBJECT, actions: [action] }; + const schemaOf = (n: string) => (n === OBJECT ? objectDef : undefined); + const ql: any = { + executeAction: vi.fn(async () => ({ ran: 'script' })), + getSchema: schemaOf, + registry: { getObject: schemaOf, getItem: () => undefined }, + find: vi.fn(async () => []), + insert: vi.fn(), update: vi.fn(), delete: vi.fn(), + }; + const metadata: any = { + load: vi.fn(async () => null), + loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })), + listObjects: vi.fn(async () => [objectDef]), + getObject: vi.fn(async (n: string) => schemaOf(n)), + }; + 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 dispatcher = new HttpDispatcher(kernel); + + /** REST `POST /actions/:object/:action`, answered as the route answers. */ + const viaRest = async (ec: unknown): Promise<{ status: number; code?: string; message?: string; body: any }> => { + const res: any = await dispatcher.handleActions(`/${OBJECT}/${ACTION}`, 'POST', {}, { + request: {}, environmentId: 'platform', executionContext: ec, + } as any); + const body = res.response?.body; + return { status: res.response?.status, code: body?.error?.code, message: body?.error?.message, body }; + }; + + /** MCP `run_action`, its throw resolved exactly as the MCP tool surface and REST resolve one. */ + const viaMcp = async (ec: unknown): Promise<{ status: number; code?: string; message?: string }> => { + const request: any = { request: {}, environmentId: 'platform', executionContext: ec }; + const deps: any = { + resolveService: async (_ctx: any, name: string) => (name === 'automation' ? automation : undefined), + getObjectQL: async () => ql, + }; + try { + await invokeBusinessAction(deps, request, ACTION, { objectName: OBJECT } as any, { + driver: undefined, + envId: 'platform', + ec, + getMeta: () => ({ listObjects: async () => [objectDef] }), + callData: (a, params, dataDriver, scopeId, execCtx) => + callData(deps, request, a, params, dataDriver, scopeId, execCtx), + }); + return { status: 200 }; + } catch (err) { + const thrown = resolveThrownHttpError(err, 500); + return { status: thrown.status, code: thrown.code, message: thrown.message }; + } + }; + + return { viaRest, viaMcp, execute, getFlow }; +} + +const ENTRANCES = ['REST /actions', 'MCP run_action'] as const; +type Entrance = (typeof ENTRANCES)[number]; +const knock = (door: ReturnType, entrance: Entrance, ec: unknown) => + entrance === 'REST /actions' ? door.viaRest(ec) : door.viaMcp(ec); + +/** The trigger door's refusal for the same declaration — the envelope every door shares. */ +async function triggerDoorRefusal(type: string): Promise<{ status: number; code?: string; message?: string }> { + const automation = { + execute: vi.fn(async () => ({ success: true, output: {} })), + getFlow: vi.fn(async (name: string) => ({ name, type, runAs: 'system' })), + }; + const resolve = (n: string) => (n === 'automation' ? automation : null); + const kernel: any = { getService: resolve, getServiceAsync: async (n: string) => resolve(n), context: { getService: resolve } }; + const res: any = await new HttpDispatcher(kernel).handleAutomation(`/${FLOW}/trigger`, 'POST', {}, { + request: {}, executionContext: MEMBER_EC, + } as any); + return { status: res.response?.status, code: res.response?.body?.error?.code, message: res.response?.body?.error?.message }; +} + +describe('a non-system caller is refused an elevated self-triggered flow at the action door', () => { + for (const entrance of ENTRANCES) { + for (const type of REFUSED_TYPES) { + it(`${entrance}: target type '${type}', runAs 'system' → 403 PERMISSION_DENIED, never dispatched`, async () => { + const door = makeDoor({ flow: { type, runAs: 'system' } }); + + const answer = await knock(door, entrance, MEMBER_EC); + + expect(answer.status).toBe(403); + expect(answer.code).toBe('PERMISSION_DENIED'); + // The refusal happens BEFORE dispatch: the engine was never + // asked, so no run record and no node ran. + expect(door.execute).not.toHaveBeenCalled(); + }); + } + + it(`${entrance}: the refusal discloses nothing of the flow, and is the trigger door's own envelope`, async () => { + const messages: string[] = []; + for (const type of REFUSED_TYPES) { + const door = makeDoor({ flow: { type, runAs: 'system' } }); + const answer = await knock(door, entrance, MEMBER_EC); + // A refusal first — so the absence checks below cannot pass + // over an answer that carries no message at all. + expect(answer.status).toBe(403); + const message = String(answer.message ?? ''); + expect(message.length).toBeGreaterThan(0); + // Neither the flow's name, its type nor its run-as declaration. + expect(message).not.toContain(FLOW); + expect(message).not.toContain(type); + expect(message).not.toMatch(/runAs|'system'/); + // One rule at every door: the same code, status and words the + // trigger door answers for the same declaration. + expect(answer).toMatchObject(await triggerDoorRefusal(type)); + messages.push(message); + } + expect(new Set(messages).size).toBe(1); + }); + } + + it('REST /actions: the refusal carries no inner data and the ADR-0112 httpStatus', async () => { + const door = makeDoor({ flow: { type: 'autolaunched', runAs: 'system' } }); + + const answer = await door.viaRest(MEMBER_EC); + + expect(answer.body?.success).toBe(false); + expect(answer.body?.error?.httpStatus).toBe(403); + expect(answer.body?.data).toBeUndefined(); + }); +}); + +describe('what stays exactly as it was at the action door', () => { + for (const entrance of ENTRANCES) { + for (const type of REFUSED_TYPES) { + it(`${entrance}: the system principal still starts a '${type}' flow declared runAs 'system'`, async () => { + const door = makeDoor({ flow: { type, runAs: 'system' } }); + + const answer = await knock(door, entrance, SYSTEM_EC); + + expect(answer.status).toBe(200); + expect(door.execute).toHaveBeenCalledTimes(1); + expect(door.execute.mock.calls[0]?.[0]).toBe(FLOW); + }); + + it(`${entrance}: a member still starts a '${type}' flow that does not declare runAs 'system'`, async () => { + const asUser = makeDoor({ flow: { type, runAs: 'user' } }); + // A declaration with no `runAs` at all (the parsed default is 'user'). + const bare = makeDoor({ flow: { type } }); + + expect((await knock(asUser, entrance, MEMBER_EC)).status).toBe(200); + expect((await knock(bare, entrance, MEMBER_EC)).status).toBe(200); + expect(asUser.execute).toHaveBeenCalledTimes(1); + expect(bare.execute).toHaveBeenCalledTimes(1); + }); + } + + for (const type of DOOR_TYPES) { + it(`${entrance}: a member still starts a '${type}' flow declared runAs 'system' — an entry its author designed`, async () => { + const door = makeDoor({ flow: { type, runAs: 'system' } }); + + const answer = await knock(door, entrance, MEMBER_EC); + + expect(answer.status).toBe(200); + expect(door.execute).toHaveBeenCalledTimes(1); + }); + } + + it(`${entrance}: an unknown target still answers 404 — existence is asked first`, async () => { + const door = makeDoor({ flow: null }); + + const answer = await knock(door, entrance, MEMBER_EC); + + expect(answer.status).toBe(404); + expect(door.execute).not.toHaveBeenCalled(); + }); + + it(`${entrance}: a service that cannot be asked for the declaration dispatches as before`, async () => { + const door = makeDoor({ flow: null, omitGetFlow: true }); + + const answer = await knock(door, entrance, MEMBER_EC); + + expect(answer.status).toBe(200); + expect(door.execute).toHaveBeenCalledTimes(1); + }); + } +}); + +describe("the action's own requiredPermissions gate (ADR-0066 D4) keeps its place", () => { + const GATED = ['fda_run_elevated']; + + for (const entrance of ENTRANCES) { + it(`${entrance}: a member lacking the declared capability is refused by the action's gate first — the flow is never read`, async () => { + const door = makeDoor({ flow: { type: 'autolaunched', runAs: 'system' }, requiredPermissions: GATED }); + + const answer = await knock(door, entrance, MEMBER_EC); + + // The gate's refusal names the missing capability; the flow check + // never ran (it reads the declaration through `getFlow`, which the + // existence probe asks first — neither was reached). REST answers + // the gate 403; the MCP bridge throws the gate's sentence bare, as + // it did before this check existed. + if (entrance === 'REST /actions') expect(answer.status).toBe(403); + expect(answer.status).not.toBe(200); + expect(answer.message).toContain('fda_run_elevated'); + expect(door.getFlow).not.toHaveBeenCalled(); + expect(door.execute).not.toHaveBeenCalled(); + }); + + it(`${entrance}: holding the declared capability does not open a self-triggered elevated target`, async () => { + const door = makeDoor({ flow: { type: 'autolaunched', runAs: 'system' }, requiredPermissions: GATED }); + + const answer = await knock(door, entrance, { ...MEMBER_EC, systemPermissions: GATED }); + + expect(answer.status).toBe(403); + expect(answer.code).toBe('PERMISSION_DENIED'); + expect(answer.message).not.toContain('fda_run_elevated'); + expect(door.getFlow).toHaveBeenCalled(); + expect(door.execute).not.toHaveBeenCalled(); + }); + + it(`${entrance}: holding the declared capability starts an elevated entry ('screen') — the route the ruling names`, async () => { + const door = makeDoor({ flow: { type: 'screen', runAs: 'system' }, requiredPermissions: GATED }); + + const answer = await knock(door, entrance, { ...MEMBER_EC, systemPermissions: GATED }); + + expect(answer.status).toBe(200); + expect(door.execute).toHaveBeenCalledTimes(1); + }); + } +}); diff --git a/packages/runtime/src/domains/automation.ts b/packages/runtime/src/domains/automation.ts index 17cef8197b2..4945776a222 100644 --- a/packages/runtime/src/domains/automation.ts +++ b/packages/runtime/src/domains/automation.ts @@ -30,7 +30,7 @@ import { isServiceServeable } from '../service-serveable.js'; import { validationFailure, validationFailureDetails, fieldsFromZodIssues, VALIDATION_FAILED_STATUS, } from '../validation-failure.js'; -import { ExecutionStatus, type FlowParsed } from '@objectstack/spec/automation'; +import { ExecutionStatus } from '@objectstack/spec/automation'; import { ListRunsRequestSchema } from '@objectstack/spec/api'; import type { ResumeFailureDetails } from '@objectstack/spec/api'; import { parseEnumParam, parseIntegerParam, parseStringParam } from '../query-param.js'; @@ -43,6 +43,9 @@ import { isPausedRun, FLOW_NOT_FOUND_STATUS, } from '../flow-dispatch-status.js'; +// Who may START a flow by name — the one rule the trigger door, the action door +// and the declared endpoint share (the maintainer's ruling, letters B and A). +import { ELEVATED_START_REFUSAL, refusesElevatedSelfTriggeredStart } from '../flow-start-admission.js'; // [#12156] ADR-0126 §7.1 clone — the whole-definition copy, the keys it must // not carry forward, the same-name refusal and the references notice. import { @@ -1684,87 +1687,6 @@ async function unregisterAndDeleteFlow( return undefined; } -/** - * The three flow types that start on their OWN trigger — or as a sub-flow - * called from a parent flow's `subflow` node — and never as a door: an - * `autolaunched` flow has no trigger of its own beyond a parent or an engine - * event, a `record_change` flow starts on a write, and a `schedule` flow on - * its cadence. Bound to the spec's `Flow.type` enum at compile time, so a - * member the spec drops reds this line. - * - * `screen` and `api` are deliberately NOT here: they are doors the author - * designed for users and API callers, and an elevated one is the author's - * explicit choice (ADR-0073 D2), reviewable at publish. - */ -const SELF_TRIGGERED_FLOW_TYPES: ReadonlySet = new Set( - ['autolaunched', 'record_change', 'schedule'] as const satisfies readonly FlowParsed['type'][], -); - -/** - * Refusal vocabulary for an elevated self-triggered flow at the trigger door - * (ADR-0112: code AND status) — the code and status this domain's other - * permission refusals already answer with (`RUN_READ_DENY_*`, - * `FLOW_WRITE_DENY_*`, `RUN_LIFECYCLE_DENY_*`). ⛔ No new code is minted here. - * - * The message names what admits such a flow and nothing about THIS flow: not - * its type, not its run-as declaration, not its definition. It reads the same - * for every refused flow, so it tells a caller nothing the refusal itself does - * not. - */ -const ELEVATED_TRIGGER_DENY_STATUS = 403; -const ELEVATED_TRIGGER_DENY_CODE = 'PERMISSION_DENIED'; -const ELEVATED_TRIGGER_DENY_MESSAGE = - 'This caller may not start this flow through the trigger door. A flow that runs on its own trigger ' - + "starts there, or as a sub-flow from a parent flow's `subflow` node."; - -/** - * Whether the trigger door refuses this caller starting `flowName`: the - * caller is not the system principal, AND the flow is declared - * `runAs: 'system'`, AND its `type` is one of {@link SELF_TRIGGERED_FLOW_TYPES}. - * - * Implements the maintainer's ruling (letter B) on the defect class "a - * self-triggered flow declared to run as system could be started by any - * signed-in member through the trigger door": the door used to ask only - * whether the caller was anonymous, so an elevated flow meant to run on its - * own trigger — or as a sub-flow, the platform's own pattern for an elevated - * write — was also an elevated door every signed-in user could open. Same - * direction as ADR-0073 D2 (`system` is an explicit opt-in, never a default) - * and as ADR-0138 D2b, its publish-time sibling (no anonymous flow door may - * target a `system` flow). - * - * What stays exactly as it was, and why each is outside this predicate: - * - * - **The system principal** (`executionContext.isSystem` — the same field - * the domain's anonymous floor reads, never set on inbound HTTP) still - * starts every flow. - * - **A parent flow's `subflow` node** starts its child through the engine - * (`engine.execute`), never through this door, so an elevated sub-flow - * called from its parent is untouched — the check lives at the door - * precisely so that path stays open. - * - **`screen` and `api` flows**, elevated or not, and every flow that does - * not declare `runAs: 'system'`. - * - * Reads the flow through the automation service's own `getFlow` — the probe - * {@link flowIsUnknown} uses, which serves the same definition `execute` - * runs — so there is no second loader and no second copy of the engine's - * run-as policy here: the predicate reads two declared keys and decides - * admission, while elevation stays the engine's. `getFlow` is optional on - * `IAutomationService`; an implementation that omits it cannot be asked, and - * the door dispatches as before, exactly as the existence check does. - */ -async function refusesElevatedSelfTriggeredStart( - automationService: IAutomationService, - flowName: string, - context: HttpProtocolContext, -): Promise { - const ec: any = (context as any)?.executionContext; - if (ec?.isSystem === true) return false; - if (typeof automationService.getFlow !== 'function') return false; - const flow = await automationService.getFlow(flowName); - if (!flow) return false; - return flow.runAs === 'system' && SELF_TRIGGERED_FLOW_TYPES.has(flow.type); -} - /** * [#9378] The ONE mapper both trigger doors answer through — `POST * /:name/trigger` and the legacy `POST /trigger/:name`, which @@ -1883,12 +1805,14 @@ async function respondToFlowTrigger( } // The caller × flow check: AFTER existence (an unknown name keeps its 404) // and BEFORE dispatch, so a refused start runs nothing — no run record, no - // node, no side effect. See {@link refusesElevatedSelfTriggeredStart}. - if (await refusesElevatedSelfTriggeredStart(automationService, flowName, context)) { + // node, no side effect. The ONE rule every door that starts a flow by name + // asks (`../flow-start-admission.ts`): the action door and the declared + // endpoint answer the same refusal for the same declaration. + if (await refusesElevatedSelfTriggeredStart(automationService, flowName, context?.executionContext)) { return { handled: true, - response: deps.error(ELEVATED_TRIGGER_DENY_MESSAGE, ELEVATED_TRIGGER_DENY_STATUS, { - code: ELEVATED_TRIGGER_DENY_CODE, + response: deps.error(ELEVATED_START_REFUSAL.message, ELEVATED_START_REFUSAL.status, { + code: ELEVATED_START_REFUSAL.code, }), }; } @@ -2265,7 +2189,9 @@ export async function classifyResumeResult( * type (`autolaunched`, `record_change`, * `schedule`) — the system principal only; * anyone else → 403 `PERMISSION_DENIED`, never - * dispatched (`refusesElevatedSelfTriggeredStart`) + * dispatched (`refusesElevatedSelfTriggeredStart`, + * `../flow-start-admission.ts`, which the action + * door and the declared endpoint ask too) * POST /:name/toggle → toggleFlow (unknown name → 404, #7535). Switches * PACKAGED flows only — it writes the ADR-0126 §7.2 * activation ledger. A flow no package ships → 409 diff --git a/packages/runtime/src/endpoint-executor.ts b/packages/runtime/src/endpoint-executor.ts index 71e99c29944..83029b41fe0 100644 --- a/packages/runtime/src/endpoint-executor.ts +++ b/packages/runtime/src/endpoint-executor.ts @@ -60,6 +60,9 @@ import { flowNotFoundMessage, FLOW_NOT_FOUND_STATUS, } from './flow-dispatch-status.js'; +// Who may START a flow by name — the one rule the trigger door, the action door +// and this door share (the maintainer's ruling, letters B and A). +import { ELEVATED_START_REFUSAL, refusesElevatedSelfTriggeredStart } from './flow-start-admission.js'; import type { HttpProtocolContext } from './http-dispatcher.js'; // ============================================================================ @@ -545,6 +548,27 @@ async function executeFlow( }); } + // The caller × flow check (the maintainer's ruling, letter A: the trigger + // door's type × caller rule binds every door that starts a flow by name). + // A caller that is not the system principal may not start a flow declared + // `runAs: 'system'` whose type is self-triggered (`autolaunched`, + // `record_change`, `schedule`) — those run on their own trigger or as a + // sub-flow, so an endpoint that names one is wiring, not an entry. AFTER + // existence (an unknown target keeps its 404) and BEFORE dispatch (a refused + // start runs nothing). The policy chain has already run upstream: an + // anonymous caller at an `authRequired: true` endpoint is 401 before this + // line, and the guest principal an `authRequired: false` endpoint admits is + // not the system one. The same code, status and words the trigger door + // answers (`flow-start-admission.ts`), so #5040 §4's "same operation, same + // answer" holds for this refusal too. + if (await refusesElevatedSelfTriggeredStart(service, plan.flow, ctx.executionContext)) { + return apiErrorResponse({ + message: ELEVATED_START_REFUSAL.message, + httpStatus: ELEVATED_START_REFUSAL.status, + code: ELEVATED_START_REFUSAL.code, + }); + } + const automationContext = buildAutomationContext(ctx.body, ctx.protocolContext) as AutomationContext; const result = await automation.execute(plan.flow, automationContext); diff --git a/packages/runtime/src/endpoint-flow-elevated-door.test.ts b/packages/runtime/src/endpoint-flow-elevated-door.test.ts new file mode 100644 index 00000000000..fea21ec3fc0 --- /dev/null +++ b/packages/runtime/src/endpoint-flow-elevated-door.test.ts @@ -0,0 +1,182 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The declared endpoint door × a flow declared `runAs: 'system'`: a caller + * that is not the system principal may not start, through an endpoint of + * `type: 'flow'`, one whose `type` is self-triggered (`autolaunched`, + * `record_change`, `schedule`) — the same type × caller rule the trigger door + * and the action door apply (the maintainer's ruling, letter A, extending + * letter B to every door that starts a flow by name). + * + * Driven through `executeEndpointTarget` with a scripted automation service, so + * each pin isolates the door's decision: `getFlow` serves the declaration the + * door reads, and `execute` is a spy, so "never dispatched" is a fact about the + * engine call. The policy chain (`authRequired`, `rateLimit`) runs upstream of + * this function and is untouched: an anonymous caller at an + * `authRequired: true` endpoint is still `401` before any of this runs, and an + * `authRequired: false` endpoint's anonymous caller arrives here as the guest + * principal, never the system one. The wire half, on a real boot, is the + * dogfood `flow-door-elevated-start.dogfood.test.ts`. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { ApiEndpointSchema, ApiErrorSchema, BaseResponseSchema, envelopeViolations } from '@objectstack/spec/api'; +import type { ApiEndpointMatch } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; + +import { + buildEndpointExecutionContext, + executeEndpointTarget, + type EndpointExecutionAnswer, +} from './endpoint-executor.js'; +import { HttpDispatcher } from './http-dispatcher.js'; + +const FLOW = 'fde_target_flow'; + +const FLOW_ENDPOINT = () => + ApiEndpointSchema.parse({ + name: 'fde_start', + path: '/api/v1/apps/fde/start', + method: 'POST', + type: 'flow', + target: FLOW, + authRequired: true, + }); + +/** A signed-in, non-system caller. */ +const MEMBER_EC = { userId: 'user-1', positions: ['member'], permissions: [], tenantId: 'org-1' } as unknown as ExecutionContext; +/** The guest principal an `authRequired: false` endpoint's anonymous caller executes as (#22147). */ +const GUEST_EC = { principalKind: 'guest', positions: ['guest'], isSystem: false } as unknown as ExecutionContext; +/** The system principal. */ +const SYSTEM_EC = { isSystem: true } as unknown as ExecutionContext; + +const REFUSED_TYPES = ['autolaunched', 'record_change', 'schedule'] as const; +const DOOR_TYPES = ['screen', 'api'] as const; + +function automationServiceWith(flow: { type: string; runAs?: string } | null, opts: { omitGetFlow?: boolean } = {}) { + const execute = vi.fn(async (_name: string, _context?: unknown) => ({ success: true, output: {} })); + const getFlow = vi.fn(async (name: string) => (name === FLOW && flow ? { name, ...flow } : null)); + const service: Record = opts.omitGetFlow ? { execute } : { execute, getFlow }; + return { service, execute, getFlow }; +} + +async function viaEndpoint(service: unknown, executionContext: ExecutionContext): Promise { + const match: ApiEndpointMatch = { endpoint: FLOW_ENDPOINT(), params: {} }; + const ctx = buildEndpointExecutionContext({ + request: { method: 'POST', path: '/api/v1/apps/fde/start', query: {}, headers: {}, body: {} }, + match, + executionContext, + environmentId: 'env-1', + }); + return executeEndpointTarget(ctx, { callData: vi.fn().mockResolvedValue({ ok: true }), automationService: service }); +} + +/** The trigger door's refusal for the same declaration — the envelope every door shares. */ +async function triggerDoorRefusal(type: string) { + const { service } = automationServiceWith({ type, runAs: 'system' }); + const resolve = (n: string) => (n === 'automation' ? service : null); + const kernel: any = { getService: resolve, getServiceAsync: async (n: string) => resolve(n), context: { getService: resolve } }; + const res: any = await new HttpDispatcher(kernel).handleAutomation(`/${FLOW}/trigger`, 'POST', {}, { + request: {}, executionContext: MEMBER_EC, + } as any); + return { status: res.response?.status, code: res.response?.body?.error?.code, message: res.response?.body?.error?.message }; +} + +function errorOf(answer: EndpointExecutionAnswer) { + const body: any = answer.body; + expect(BaseResponseSchema.safeParse(body).success).toBe(true); + expect(envelopeViolations(body), `not the declared envelope: ${JSON.stringify(body)}`).toEqual([]); + expect(body.success).toBe(false); + expect(body.data).toBeUndefined(); + expect(ApiErrorSchema.safeParse(body.error).success).toBe(true); + expect(body.error.httpStatus).toBe(answer.status); + return body.error; +} + +describe('a non-system caller is refused an elevated self-triggered flow at a declared flow endpoint', () => { + for (const [label, ec] of [['a signed-in member', MEMBER_EC], ['the guest principal', GUEST_EC]] as const) { + for (const type of REFUSED_TYPES) { + it(`${label}: target type '${type}', runAs 'system' → 403 PERMISSION_DENIED, never dispatched`, async () => { + const { service, execute } = automationServiceWith({ type, runAs: 'system' }); + + const answer = await viaEndpoint(service, ec); + + expect(answer.status).toBe(403); + expect(errorOf(answer).code).toBe('PERMISSION_DENIED'); + expect(execute).not.toHaveBeenCalled(); + }); + } + } + + it('the refusal discloses nothing of the flow, and is the trigger door\'s own envelope', async () => { + const messages: string[] = []; + for (const type of REFUSED_TYPES) { + const { service } = automationServiceWith({ type, runAs: 'system' }); + const answer = await viaEndpoint(service, MEMBER_EC); + expect(answer.status).toBe(403); + const error = errorOf(answer); + const message = String(error.message ?? ''); + expect(message.length).toBeGreaterThan(0); + expect(message).not.toContain(FLOW); + expect(message).not.toContain(type); + expect(message).not.toMatch(/runAs|'system'/); + expect(error.details).toBeUndefined(); + expect({ status: answer.status, code: error.code, message }).toEqual(await triggerDoorRefusal(type)); + messages.push(message); + } + expect(new Set(messages).size).toBe(1); + }); +}); + +describe('what stays exactly as it was at a declared flow endpoint', () => { + for (const type of REFUSED_TYPES) { + it(`the system principal still starts a '${type}' flow declared runAs 'system'`, async () => { + const { service, execute } = automationServiceWith({ type, runAs: 'system' }); + + const answer = await viaEndpoint(service, SYSTEM_EC); + + expect(answer.status).toBe(200); + expect(execute).toHaveBeenCalledTimes(1); + expect(execute.mock.calls[0]?.[0]).toBe(FLOW); + }); + + it(`a member still starts a '${type}' flow that does not declare runAs 'system'`, async () => { + const asUser = automationServiceWith({ type, runAs: 'user' }); + const bare = automationServiceWith({ type }); + + expect((await viaEndpoint(asUser.service, MEMBER_EC)).status).toBe(200); + expect((await viaEndpoint(bare.service, MEMBER_EC)).status).toBe(200); + expect(asUser.execute).toHaveBeenCalledTimes(1); + expect(bare.execute).toHaveBeenCalledTimes(1); + }); + } + + for (const type of DOOR_TYPES) { + it(`a member still starts a '${type}' flow declared runAs 'system' — an entry its author designed`, async () => { + const { service, execute } = automationServiceWith({ type, runAs: 'system' }); + + const answer = await viaEndpoint(service, MEMBER_EC); + + expect(answer.status).toBe(200); + expect(execute).toHaveBeenCalledTimes(1); + }); + } + + it('an unknown target still answers 404 — existence is asked first', async () => { + const { service, execute } = automationServiceWith(null); + + const answer = await viaEndpoint(service, MEMBER_EC); + + expect(answer.status).toBe(404); + expect(execute).not.toHaveBeenCalled(); + }); + + it('a service that cannot be asked for the declaration dispatches as before', async () => { + const { service, execute } = automationServiceWith(null, { omitGetFlow: true }); + + const answer = await viaEndpoint(service, MEMBER_EC); + + expect(answer.status).toBe(200); + expect(execute).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/runtime/src/flow-start-admission.ts b/packages/runtime/src/flow-start-admission.ts new file mode 100644 index 00000000000..d0f69698501 --- /dev/null +++ b/packages/runtime/src/flow-start-admission.ts @@ -0,0 +1,120 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Who may START a flow at a door that starts one by name — ONE definition, + * asked by every such door. + * + * Three doors start a flow by name, and each hands the name straight to + * `IAutomationService.execute`: + * + * - the trigger routes, `POST /automation/:name/trigger` and the legacy + * `POST /automation/trigger/:name` (`domains/automation.ts`); + * - an action of `type: 'flow'`, reached through `POST /actions/:object/:action` + * and through the MCP `run_action` bridge, which share `dispatchFlowAction` + * (`action-execution.ts`); + * - a declared endpoint of `type: 'flow'` (`endpoint-executor.ts`). + * + * The rule (the maintainer's ruling, letter B at the trigger door, extended to + * every door that starts a flow by name by letter A): a caller that is not the + * system principal may not start a flow declared `runAs: 'system'` whose + * `type` is self-triggered — `autolaunched`, `record_change` or `schedule`. + * Those types run on their own trigger, or as a sub-flow from a parent flow's + * `subflow` node, and are never an entry, so a button, an action or an + * endpoint that happens to name one is wiring, not a design. `screen` and + * `api` flows stay the doors their author designed, elevated or not. + * + * ## Why a module, and why every door asks it + * + * The same reason `flow-dispatch-status.ts` is one: a rule each door spells + * for itself is a rule that drifts, and a door left out is the defect, not a + * gap. The type set, the refusal's code and status, and its words live here + * once, so a caller refused at one door is refused alike at the other two — + * an MCP agent and a person are judged at the same door by the same rule. + * ⛔ A second copy of the type set or the refusal, at any door, is the defect + * by construction. + * + * ## What the predicate does NOT decide + * + * Admission only. Elevation stays the engine's: the predicate reads two + * declared keys off the definition the service serves and never re-implements + * the engine's run-as policy. A door's own gates are untouched and keep their + * place: the action's declared `requiredPermissions` (ADR-0066 D4) still + * answers first at the action door, and a declared endpoint's policy chain + * (`authRequired`, `rateLimit`) still runs before its executor. This check + * runs after the door's existence probe (an unknown name keeps its `404`) and + * before dispatch, so a refused start runs nothing. + */ + +import type { FlowParsed } from '@objectstack/spec/automation'; + +/** + * The three flow types that start on their OWN trigger — or as a sub-flow + * called from a parent flow's `subflow` node — and never as an entry: an + * `autolaunched` flow has no trigger of its own beyond a parent or an engine + * event, a `record_change` flow starts on a write, and a `schedule` flow on + * its cadence. Bound to the spec's `Flow.type` enum at compile time, so a + * member the spec drops reds this line. + * + * `screen` and `api` are deliberately NOT here: they are entries the author + * designed for users and API callers, and an elevated one is the author's + * explicit choice (ADR-0073 D2), reviewable at publish. + */ +export const SELF_TRIGGERED_FLOW_TYPES: ReadonlySet = new Set( + ['autolaunched', 'record_change', 'schedule'] as const satisfies readonly FlowParsed['type'][], +); + +/** + * The refusal every door answers (ADR-0112: code AND status) — the code and + * status the automation domain's other permission refusals already answer + * with. ⛔ No new code is minted here. + * + * The message names what admits such a flow and nothing about THIS flow: not + * its name, its type, its run-as declaration or its definition, and not the + * door, so it reads the same at every door and for every refused flow and + * tells a caller nothing the refusal itself does not. + */ +export const ELEVATED_START_REFUSAL = Object.freeze({ + code: 'PERMISSION_DENIED', + status: 403, + message: + 'This caller may not start this flow. A flow that runs on its own trigger starts there, ' + + "or as a sub-flow from a parent flow's `subflow` node.", +} as const); + +/** + * Whether a door refuses this caller starting `flowName`: the caller is not + * the system principal, AND the flow is declared `runAs: 'system'`, AND its + * `type` is one of {@link SELF_TRIGGERED_FLOW_TYPES}. + * + * What stays exactly as it was, and why each is outside this predicate: + * + * - **The system principal** (`executionContext.isSystem`, never set on + * inbound HTTP; an in-process caller such as a job) still starts every flow. + * The guest principal an `authRequired: false` endpoint admits carries + * `isSystem: false` and is refused like any other caller. + * - **A parent flow's `subflow` node** starts its child through the engine + * (`engine.execute`), never through a door, so an elevated sub-flow called + * from its parent is untouched — the check lives at the doors precisely so + * that path stays open. + * - **`screen` and `api` flows**, elevated or not, and every flow that does + * not declare `runAs: 'system'`. + * + * Reads the flow through the automation service's own `getFlow` — the probe + * `flowIsUnknown` (`flow-dispatch-status.ts`) uses, which serves the same + * definition `execute` runs — so there is no second loader. `getFlow` is + * optional on `IAutomationService`; an implementation that omits it cannot be + * asked, and the door dispatches as before, exactly as the existence check + * does. + */ +export async function refusesElevatedSelfTriggeredStart( + automation: unknown, + flowName: string, + executionContext: { isSystem?: boolean } | null | undefined, +): Promise { + if (executionContext?.isSystem === true) return false; + const svc = automation as { getFlow?: (name: string) => Promise } | null | undefined; + if (typeof svc?.getFlow !== 'function') return false; + const flow = (await svc.getFlow(flowName)) as { type?: FlowParsed['type']; runAs?: unknown } | null | undefined; + if (!flow) return false; + return flow.runAs === 'system' && flow.type !== undefined && SELF_TRIGGERED_FLOW_TYPES.has(flow.type); +} diff --git a/packages/verify/src/action-flow-elevated-door.test.ts b/packages/verify/src/action-flow-elevated-door.test.ts index 9d20e356e1c..5bca5a91d90 100644 --- a/packages/verify/src/action-flow-elevated-door.test.ts +++ b/packages/verify/src/action-flow-elevated-door.test.ts @@ -27,6 +27,10 @@ * flow per type, each creating a ledger row named after itself, each named by * one flow action. * + * The table was MEASURED FIRST, before the door asked anything of the caller + * (this branch's first commit carries it as the assertion); each row's + * `before` comment is that reading. + * * ⚠️ This suite resolves `@objectstack/runtime` and * `@objectstack/service-automation` through their BUILT `dist/`. Rebuild both * before trusting a run of this file — and especially an ablated one. @@ -40,6 +44,7 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; import type { Flow } from '@objectstack/spec/automation'; import { bootStack, type VerifyStack } from './harness.js'; +import { isVerifyRefusal } from './handle.js'; // Booting the full in-process stack runs well past vitest's 5s default. const BOOT_TIMEOUT = 120_000; @@ -258,33 +263,76 @@ describe('control: the member cannot write the ledger directly', () => { }); }); +const REFUSED = { answer: 403, code: 'PERMISSION_DENIED', rows: 0, runs: 0 } as const; const RAN = { answer: 200, rows: 1, runs: 1 } as const; /** - * Caller × flow → what the action door answers and what the request caused, - * MEASURED BEFORE the door asked anything of the caller (this branch's first - * commit carries these readings as the assertions). + * Caller × flow → what the action door answers and what the request caused. + * `before` is the reading this branch's first commit took before the door + * asked anything of the caller, so the change the check makes is visible row + * by row. */ -const TABLE: Array<{ caller: Caller; flow: Target; rowsOf?: string; outcome: Outcome }> = [ - { caller: 'member', flow: AUTO_SYS, outcome: RAN }, - { caller: 'member', flow: CHANGE_SYS, outcome: RAN }, - { caller: 'member', flow: SCHED_SYS, outcome: RAN }, - { caller: 'admin', flow: AUTO_SYS, outcome: RAN }, - { caller: 'admin', flow: CHANGE_SYS, outcome: RAN }, - { caller: 'admin', flow: SCHED_SYS, outcome: RAN }, - { caller: 'system', flow: AUTO_SYS, outcome: RAN }, - { caller: 'system', flow: CHANGE_SYS, outcome: RAN }, - { caller: 'system', flow: SCHED_SYS, outcome: RAN }, - { caller: 'member', flow: SCREEN_SYS, outcome: RAN }, - { caller: 'member', flow: API_SYS, outcome: RAN }, - { caller: 'member', flow: AUTO_USER, outcome: { answer: 400, code: 'FLOW_FAILED', rows: 0, runs: 1 } }, - { caller: 'member', flow: PARENT_SCREEN, rowsOf: AUTO_SYS, outcome: RAN }, +const TABLE: Array<{ caller: Caller; flow: Target; rowsOf?: string; outcome: Outcome; before: string }> = [ + // REFUSED — a signed-in member, the three self-triggered types. + { caller: 'member', flow: AUTO_SYS, outcome: REFUSED, before: '200, elevated row written' }, + { caller: 'member', flow: CHANGE_SYS, outcome: REFUSED, before: '200, elevated row written' }, + { caller: 'member', flow: SCHED_SYS, outcome: REFUSED, before: '200, elevated row written' }, + // REFUSED — the platform admin is a signed-in user too, not the system principal. + { caller: 'admin', flow: AUTO_SYS, outcome: REFUSED, before: '200, row written' }, + { caller: 'admin', flow: CHANGE_SYS, outcome: REFUSED, before: '200, row written' }, + { caller: 'admin', flow: SCHED_SYS, outcome: REFUSED, before: '200, row written' }, + // UNCHANGED — the system principal starts each refused type through the action. + { caller: 'system', flow: AUTO_SYS, outcome: RAN, before: '200, row written' }, + { caller: 'system', flow: CHANGE_SYS, outcome: RAN, before: '200, row written' }, + { caller: 'system', flow: SCHED_SYS, outcome: RAN, before: '200, row written' }, + // UNCHANGED — `screen` and `api`: entries the author designed. + { caller: 'member', flow: SCREEN_SYS, outcome: RAN, before: '200, elevated row written' }, + { caller: 'member', flow: API_SYS, outcome: RAN, before: '200, elevated row written' }, + // UNCHANGED — a non-elevated flow: the member's own identity is refused the write. + { + caller: 'member', + flow: AUTO_USER, + outcome: { answer: 400, code: 'FLOW_FAILED', rows: 0, runs: 1 }, + before: '400 FLOW_FAILED, nothing written', + }, + // UNCHANGED — the route the ruling names: a `screen` entry that is not + // elevated, whose `subflow` node runs the elevated child the action door now + // refuses to start directly. The child writes its own name. + { caller: 'member', flow: PARENT_SCREEN, rowsOf: AUTO_SYS, outcome: RAN, before: '200, elevated child row written' }, ]; describe('the action door × runAs: system, per type and caller', () => { for (const row of TABLE) { - it(`${row.caller} starts ${row.flow} through its action → ${row.outcome.answer}`, async () => { + const verdict = row.outcome.answer === 403 ? 'refused 403 PERMISSION_DENIED, nothing ran' : `answers ${row.outcome.answer}`; + it(`${row.caller} starts ${row.flow} through its action: ${verdict} (before: ${row.before})`, async () => { expect(await startAs(row.caller, row.flow, row.rowsOf)).toEqual(row.outcome); }); } }); + +describe('the refusal envelope at the wire', () => { + it('carries the ADR-0112 code and status, nothing of the flow, and the trigger door\'s own words', async () => { + let atAction: unknown; + try { + await stack.actions.run(WATCH, actionOf(SCHED_SYS), { as: member }); + } catch (e) { + atAction = e; + } + let atTrigger: unknown; + try { + await stack.flows.run(SCHED_SYS, {}, { as: member }); + } catch (e) { + atTrigger = e; + } + expect(isVerifyRefusal(atAction)).toBe(true); + expect(codeOf(atAction)).toBe('PERMISSION_DENIED'); + expect(statusOf(atAction)).toBe(403); + const message = (atAction as Error).message; + expect(message).not.toContain(SCHED_SYS); + expect(message).not.toMatch(/schedule|runAs|'system'/); + // One rule at every door: the trigger door answers the same refusal. + expect(codeOf(atTrigger)).toBe(codeOf(atAction)); + expect(statusOf(atTrigger)).toBe(statusOf(atAction)); + expect((atTrigger as Error).message).toBe(message); + }); +}); From 28fe1079411e467f5bc3fb05f6013734549f754c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 9 Oct 2026 04:56:54 +0000 Subject: [PATCH 4/5] docs(permissions): the census row names every door that starts a flow by name; changeset The elevated self-triggered start's isSystem read moves with the shared predicate, so its row anchors the new module and states the bypass at all three doors. Counts regenerated by gen:system-context-census. Claude-Session: https://claude.ai/code/session_01BmsuLyUeuG5CNpZFMH1jzS Co-authored-by: Claude --- .changeset/22407-flow-door-elevated-start.md | 22 ++++++++++++++++++++ content/docs/permissions/system-context.mdx | 8 +++---- 2 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 .changeset/22407-flow-door-elevated-start.md diff --git a/.changeset/22407-flow-door-elevated-start.md b/.changeset/22407-flow-door-elevated-start.md new file mode 100644 index 00000000000..07704781fea --- /dev/null +++ b/.changeset/22407-flow-door-elevated-start.md @@ -0,0 +1,22 @@ +--- +'@objectstack/runtime': patch +--- + +fix(runtime): the action door and the declared flow endpoint refuse a self-triggered flow declared to run as system to any caller but the system principal + +Clause-②: no + +The trigger door already refused this start, but two other doors that start a flow by name did not ask: an action of `type: 'flow'` (`POST /api/v1/actions/:object/:action`, and the MCP `run_action` tool, which reaches the same dispatch) and a declared endpoint of `type: 'flow'`. Any signed-in member who was refused at the trigger door could start the same elevated flow through either one, and its elevated write landed. + +**What changes.** All three doors now apply one rule from one place. A caller that is not the system principal gets `403 PERMISSION_DENIED` (ADR-0112 envelope) when it starts a flow declared `runAs: 'system'` whose `type` is `autolaunched`, `record_change` or `schedule`. Nothing runs: no run record, no node, no side effect. This includes a platform admin's session and the guest principal an `authRequired: false` endpoint admits. The refusal names no part of the flow, and its message is now the same at every door: it no longer names the trigger door. + +**What stays as it was.** + +- `screen` and `api` flows, elevated or not: entries the author designed (ADR-0073 D2). +- Every flow that does not declare `runAs: 'system'`. +- A parent flow's `subflow` node calling an elevated flow: the child starts through the engine, never through a door. +- The system principal (an in-process caller, such as a job), which starts every flow. +- The action's own `requiredPermissions` gate (ADR-0066 D4) still answers first. Holding that capability does not open a self-triggered elevated target. +- A declared endpoint's policy chain: an anonymous caller at an `authRequired: true` endpoint still gets `401` first. + +**If an action or an endpoint now answers 403.** Its target flow runs on its own trigger. If members are meant to start that elevated work, declare the target `type: 'screen'` (or `type: 'api'` for a signed inbound hook), which states that it is an entry and keeps the elevation reviewable. Or keep it self-triggered and point the action or endpoint at such an entry whose `subflow` node calls it. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index f060800af0e..d44482bde61 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -180,7 +180,7 @@ The largest single consumer — **17 of the 119 sites**. | 53 | Package REST route capability gate bypassed | rest | Get: a marketplace publish over REST (`POST /packages/publish`, the one route the REST registrar mounts since #14503) without `manage_metadata`; the package read cohort (`studio.access` / `setup.access`) is enforced by the dispatcher `/packages` domain's own read gate, where the reads are served | `packages/rest/src/package-routes.ts#refusePackageRequest` | | 54 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `packages/runtime/src/domains/packages.ts#requireManageMetadata`, `#requireReadCapability` | | 55 | Activation write / authoring refusals do not fire | runtime | Get: activation artifacts writable and authorable without the activation-authoring capability | `packages/runtime/src/domains/activation-gate.ts#refuseUngrantedActivationWrite`, `#refuseUngrantedActivationAuthoring` | -| 56 | Automation run-state read, flow-authoring write, the paused-run caller gate (screen read and resume), the two operator run-lifecycle writes and the trigger door's elevated self-triggered start all pass | runtime | Get: run state, flow writes, a paused run's screen and its resume with no grant and without being the run's starter — and cancelling or restoring a suspension without the platform-operator rung. The screen read and the resume ask one predicate, so this is one bypass for both. The lifecycle bypass is the in-process owner's door: plugin-approvals' revise-window recall (ADR-0044) cancels on behalf of a decision it already authorized and recorded. And starting, through the trigger door, a flow declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`), which every other caller is refused `403 PERMISSION_DENIED` (the maintainer's ruling, letter B). That bypass is the in-process caller's, such as a job: inbound HTTP never carries the flag | `packages/runtime/src/domains/automation.ts#mayReadRunState`, `#refuseUngrantedFlowWrite`, `#isRunStarterOrRunStateReader`, `#refuseUngrantedRunLifecycleWrite`, `#refusesElevatedSelfTriggeredStart` | +| 56 | Automation run-state read, flow-authoring write, the paused-run caller gate (screen read and resume), the two operator run-lifecycle writes and the elevated self-triggered start at every door that starts a flow by name all pass | runtime | Get: run state, flow writes, a paused run's screen and its resume with no grant and without being the run's starter — and cancelling or restoring a suspension without the platform-operator rung. The screen read and the resume ask one predicate, so this is one bypass for both. The lifecycle bypass is the in-process owner's door: plugin-approvals' revise-window recall (ADR-0044) cancels on behalf of a decision it already authorized and recorded. And starting a flow declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) through any door that starts a flow by name — the trigger route, an action of `type: 'flow'` (REST `/actions` and the MCP `run_action` bridge) and a declared endpoint of `type: 'flow'` — which every other caller, the guest principal included, is refused `403 PERMISSION_DENIED` (the maintainer's rulings, letters B and A). The three doors ask one predicate, so this is one bypass for all of them, and it is the in-process caller's, such as a job: inbound HTTP never carries the flag | `packages/runtime/src/domains/automation.ts#mayReadRunState`, `#refuseUngrantedFlowWrite`, `#isRunStarterOrRunStateReader`, `#refuseUngrantedRunLifecycleWrite`, `packages/runtime/src/flow-start-admission.ts#refusesElevatedSelfTriggeredStart` | | 57 | Audience-binding suggestion recording skipped | plugin-security | Lose: install-time suggestions are not recorded for system callers | `packages/plugins/plugin-security/src/suggested-audience-bindings.ts#assertTenantAdmin` | | 58 | Email-template organization door passes; webhook provenance stamp skipped | plugin-email, plugin-webhooks | Get (`sys_email_template`): a create or update of a template row. The door refuses every other write that names a caller, `403 PERMISSION_DENIED` (ADR-0131 D6), so the seeds, the boot sweep and the projection of a Studio save are the only writers. Lose (`sys_webhook`): the row is not marked as an admin customization | `packages/plugins/plugin-email/src/email-template-door.ts#isOrganizationWrite`, `packages/plugins/plugin-webhooks/src/webhook-provenance.ts#bindWebhookProvenanceStamp` | | 59 | **Automation flow data nodes re-add the `owner_id` stamp** (the one place row 2's gap is compensated inline) | service-automation | Get: a flow-authored INSERT under system elevation still lands owned, when the run resolved a user. Fill-only — flow-authored values win | `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner`, called from `packages/services/service-automation/src/builtin/crud-nodes.ts#registerCrudNodes` | @@ -356,7 +356,7 @@ still holds equal to the census on every pull request: | — in tests | 1013 | — | | — in non-test sources | 798 | — | | Appearances of the bare identifier `isSystem` in non-test sources | 813 | — | -| — parsed as a declaration | 27 | ✅ | +| — parsed as a declaration | 28 | ✅ | | — parsed as an object-literal / type key (producers and option objects) | 310 | — | | — parsed as a property **read** | 125 | ✅ | | — parsed in some other syntactic position (a local, a cast, a conditional) | 9 | ✅ | @@ -366,7 +366,7 @@ still holds equal to the census on every pull request: | — behaviour-bearing (rows 1–61 above) | 116 | ✅ | | — carry the flag onward only (rows 62–64 above) | 3 | ✅ | | Packages containing at least one elevation read | **20** | ✅ | -| Files containing at least one elevation read | 55 | ✅ | +| Files containing at least one elevation read | 56 | ✅ | | — the distinct symbols those reads live in — what this page anchors | 102 | ✅ | | — of those files, the ones holding more than one read in one symbol | 8 | ✅ | @@ -431,7 +431,7 @@ same resolver, and the same registration shape, that holds `docs/adr/**`. Renaming a symbol is now a loud red instead of a silent misdirection. ⚠️ **The precision that costs, priced here rather than buried.** A symbol anchor -cannot say WHICH read inside a function it means, and **8** of the **55** +cannot say WHICH read inside a function it means, and **8** of the **56** anchored files hold more than one read inside a single symbol. So the population check runs per file at symbol granularity: every file the census finds a read in must be anchored, and the set of symbols this page cites into that file must From d7b2170de0bff5326cc7142799dc80f1cdefcf0d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 9 Oct 2026 05:47:19 +0000 Subject: [PATCH 5/5] docs(automation,ui,api): the flow-dispatch tables list the 403 every door answers an elevated self-triggered start The status table on the flows page gains the 403 PERMISSION_DENIED row for a non-system caller starting a runAs-system flow of a self-triggered type, the same at the trigger route, a flow action and a declared flow endpoint. Its lead sentence now says that row is the door's own admission check, not the engine's verdict, and the never-dispatched count moves from four to five. The actions page's flow row and the requiredPermissions bullet, and the declarative endpoints page's flow row, state the same refusal. Claude-Session: https://claude.ai/code/session_01BmsuLyUeuG5CNpZFMH1jzS Co-authored-by: Claude --- content/docs/api/declarative-endpoints.mdx | 2 +- content/docs/automation/flows.mdx | 12 +++++++----- content/docs/ui/actions.mdx | 8 +++++--- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/content/docs/api/declarative-endpoints.mdx b/content/docs/api/declarative-endpoints.mdx index ec1b4cbea5a..041baf5bfbc 100644 --- a/content/docs/api/declarative-endpoints.mdx +++ b/content/docs/api/declarative-endpoints.mdx @@ -101,7 +101,7 @@ declaration to shadow a built-in one. Match → policy chain (`rateLimit` → `a | `type` | Delegates to | Request shape | |:---|:---|:---| | `object_operation` | the same `callData` binding that serves `/api/v1/data/{object}` | `find` reads its criteria from the query string; `get` / `update` / `delete` take the record id from `query.id`; `create` / `update` take the body. `create` answers `201`, the rest `200` | -| `flow` | the same automation pipeline as `POST /api/v1/automation/{name}/trigger` | the request body is the flow input. A refused or failed run answers a real status: `404` unknown flow, `409` `FLOW_DISABLED`, `422` `FLOW_NO_START_NODE`, `422` `FLOW_INPUT_SCHEMA_INVALID`, `400` `FLOW_FAILED` | +| `flow` | the same automation pipeline as `POST /api/v1/automation/{name}/trigger` | the request body is the flow input. A refused or failed run answers a real status: `404` unknown flow, `409` `FLOW_DISABLED`, `422` `FLOW_NO_START_NODE`, `422` `FLOW_INPUT_SCHEMA_INVALID`, `400` `FLOW_FAILED`, and `403` `PERMISSION_DENIED`, nothing run, when the target is declared `runAs: 'system'` with a self-triggered type (`autolaunched`, `record_change`, `schedule`), exactly as the trigger door answers | The frozen vocabulary has **no path-template syntax**, so an endpoint cannot express `/leads/{id}` — a record id travels as `?id=…`. A method that no declaration claims diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index 17421e58d09..2cef0d3115c 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -2057,18 +2057,20 @@ curl -b cookies.txt -X POST \ | `POST /api/v1/automation/:name/runs/:runId/restore-suspension` | Re-arm a run stranded by a failed resume — and, for a nested run, every ancestor whose pause that strand's cascade consumed, deepest first, from whichever member you name. Same gate as `cancel`; body `{ reason? }`. `501 NOT_IMPLEMENTED` when the service does not declare the verb | **Failures answer real HTTP status codes.** A flow that does not run is not a -`200`. The route classifies five outcomes, and it reads the engine's own verdict -to do it — never the message text: +`200`. The route classifies six outcomes. Five of them it reads off the engine's +own verdict — never the message text; the `403` is the door's own admission +check, made before anything is dispatched: | Status | `error.code` | What happened | What to do | |:---|:---|:---|:---| | `404` | — | No flow by that name in this deployment | Check the name; nothing was dispatched | +| `403` | `PERMISSION_DENIED` | The caller is not the system principal, and the flow is declared `runAs: 'system'` with a self-triggered `type` (`autolaunched`, `record_change`, `schedule`). The same answer at every door that starts a flow by name: this route, a `type: 'flow'` action (REST and MCP `run_action`) and a declared `type: 'flow'` endpoint | Let it run on its own trigger, or call it from a parent flow's `subflow` node. If members are meant to start it, declare it `type: 'screen'` (or `'api'` for a signed inbound hook) | | `409` | `FLOW_DISABLED` | The flow exists but is switched off | Enable it — the identical request then succeeds | | `422` | `FLOW_NO_START_NODE` | The stored definition has no `start` node | Fix the flow; retrying cannot help | | `422` | `FLOW_INPUT_SCHEMA_INVALID` | A node's `config` violates the `inputSchema` its own definition declares | Fix the flow; the refusal is non-retryable — even under `errorHandling.strategy: 'retry'` the engine refuses once and never enters the retry loop | | `400` | `FLOW_FAILED` | The flow **ran** and was rejected | Read `error.details.summary` for the failing node | -The first four never dispatched anything: no node executed, no record was +The first five never dispatched anything: no node executed, no record was written, and there is no run to look up. Only `400` describes a run. The `FLOW_INPUT_SCHEMA_INVALID` verdict is a pure function of the flow definition — re-running the guard cannot change the answer — so a `retry` strategy does not @@ -2079,8 +2081,8 @@ burn its budget on it: the run log holds exactly one refusal row. `POST /api/v1/actions/:object/:action`, and calling a declared `type: 'flow'` [endpoint](/docs/protocol/kernel/http-protocol) under `/api/v1/apps/`, both dispatch the same flow through the same service call and classify the outcome -the same way — the table above has one definition that all three doors read, so -they cannot answer one engine outcome differently. Branch on the status and +the same way — each row of the table above has one definition that all three +doors read, so they cannot answer one request differently. Branch on the status and `error.code` at any of them. ``` diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index 8d12ef2dcb0..7bd958ae58a 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -407,8 +407,10 @@ is a spec proposal for a properly named key, not a values map under this one. - **`requiredPermissions: ['can_close_tickets']`** is a **dual-surface gate** (one declaration, two enforcement points): the server rejects unauthorized calls with 403, and the UI hides or disables the button for the same users. - Unset means no gate beyond object CRUD permissions. Referenced capabilities - must exist — `os lint` checks that. + Unset means no gate beyond object CRUD permissions — except that a `flow` + action whose target is an elevated self-triggered flow is refused to every + caller but the system principal either way (the `flow` row below). Referenced + capabilities must exist — `os lint` checks that. - **`visible`** is a CEL predicate evaluated **fail-closed**: an expression that throws hides the action silently. Two rules save real debugging time: @@ -544,7 +546,7 @@ The endpoint dispatches on the **declared `type`**, exactly like the MCP | `type` | Over REST | |:---|:---| | `script` | Runs the registered handler / inline body. | -| `flow` | Runs `target` on the automation engine, with your identity forwarded (a `runAs: 'user'` flow enforces RLS as you). Dispatches the same flow as `POST /api/v1/automation/:target/trigger`, without having to know the flow name — **and answers the same way**: a run that ran and was rejected is **400** `FLOW_FAILED`, while a dispatch that never happened is separated out (**404** unknown flow / **409** `FLOW_DISABLED` / **422** `FLOW_NO_START_NODE` / **422** `FLOW_INPUT_SCHEMA_INVALID`). See [Run a flow via API](/docs/automation/flows#run-a-flow-via-api) for the full table — it is one table, read by both doors. | +| `flow` | Runs `target` on the automation engine, with your identity forwarded (a `runAs: 'user'` flow enforces RLS as you). Dispatches the same flow as `POST /api/v1/automation/:target/trigger`, without having to know the flow name — **and answers the same way**: a run that ran and was rejected is **400** `FLOW_FAILED`, while a dispatch that never happened is separated out (**404** unknown flow / **409** `FLOW_DISABLED` / **422** `FLOW_NO_START_NODE` / **422** `FLOW_INPUT_SCHEMA_INVALID`). A target declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) is refused **403** `PERMISSION_DENIED` to every caller but the system principal, exactly as at the trigger door, and nothing runs; holding the action's `requiredPermissions` does not open it. See [Run a flow via API](/docs/automation/flows#run-a-flow-via-api) for the full table — it is one table, read by both doors. | | `api` | **400** — it dispatches on `target`; call that endpoint directly. | | `url` / `modal` / `form` | **400** — client-side navigation; there is nothing for the server to run. |