Skip to content

Commit 64b46fe

Browse files
fix(runtime, service-automation)!: an AI service account starts a flow that runs as the system only through an action its author opted into AI (#32912)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DNhgzn8MNCLr1g5gPQ2a2vU)_ Fixes #31874 Clause-②: no (narrowing) — an AI service account's start of a flow declared `runAs: 'system'` is refused with `403 PERMISSION_DENIED` at `POST /api/v1/automation/NAME/trigger` (and the legacy `POST /api/v1/automation/trigger/NAME`), at a declared endpoint of `type: 'flow'`, and at the REST actions route when the action that starts the flow does not declare `ai.exposed: true`; nothing is widened. Metadata-protocol: none Skills-docs: updated here — `content/docs/automation/flows.mdx` (the start-refusal table under "Run a flow via API" gains the AI service account row, between the elevated self-triggered row and the `requiredPermissions` row, and the two "checked after" clauses below it count the new row), `content/docs/ui/actions.mdx` (the `flow` row under "Call it over REST" and the `'rest'` posture row say the REST door reads `ai.exposed` for an AI service account starting a `runAs: 'system'` flow), `content/docs/ai/agents.mdx` (the AI service account paragraph says how an account starts a flow that runs as the system). No skill teaches which principal kinds a flow start admits. ## 维护者速读 - 改了什么:AI 服务账号(ADR-0151 的无人值守 AI 账号)启动一个声明为 `runAs: 'system'`(以系统身份运行)的流程时,默认被拒(`403 PERMISSION_DENIED`);只有通过作者已声明 `ai.exposed: true` 的 `type: 'flow'` 动作来启动才放行。能按名字启动流程的三道门(触发路由、动作门、声明式端点)问的是同一条规则,拒绝文案直接告诉作者该加哪个声明。放行后的系统身份运行,每次数据操作都带 `principalKind: 'agent'`。ADR-0151 的 Non-goals 加了一句话。 - 为什么改:裁决 6812617393(C 方案,维护者「同意」):系统身份流程用的是平台权限而不是调用者自己的权限,所以 AI 账号能不能启动它,要有作者明示的 AI 授权;MCP 门已经这样要求,其余的门补上同一条规则。 - 风险与回滚:收窄(BREAKING)。AI 服务账号经触发路由或声明式端点启动系统身份流程,一律被拒;经 REST 动作路由启动、而动作没有 `ai.exposed` 的,也被拒。人、代表某个人的 OAuth 代理、系统主体都不受影响;以用户身份运行的流程不受影响。第一方受影响的调用 0:hotcrm 里声明 `runAs: 'system'` 的流程全是自触发类型,本来就不能按名字启动;本仓示例里只有 showcase 的两个流程(`showcase_inquiry_purge`、`showcase_inbound_task_webhook`)会对 AI 账号改口,没有测试或示例用 AI 账号启动它们。回滚即 revert。 - 先看:`packages/runtime/src/flow-start-admission.ts`(`flowStartRefusal` 里规则 2 的那一个 `if`:排在规则 1 之后、`requiredPermissions` 之前);`packages/runtime/src/action-execution.ts` 的 `dispatchFlowAction`(唯一能把作者授权带给规则的门);`packages/services/service-automation/src/run-resume.ts` 的 `seedRunGrants`(系统身份运行保留门传来的 kind)。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/flow-start-required-permissions.test.ts`,应见 `Tests 81 passed (81)`。 - 需要你做的:批准本 PR(Tier H:`docs/adr/0151-…` 加了一句话,按方案 A 写)。契约复核 PASS 见评论 6839053991(`Head-sha: 183ed60…`;文档轮 `7de0545a` 只动散文面,记录续管)。批准后由席位落地。 - **席位意见**:同意按方案 A 落地。系统身份流程用平台权限写数据,AI 账号要启动它必须经过作者明示授权(`ai.exposed: true`)的流程动作;三道门同一条规则,已由隔离复核核实没有漏门。方案 A/B 已另呈维护者,ADR 句按 A 写;若改 B,ADR 句与三页文档同改。规格描述文字的过时处转卡 #32924。 ## 席位核对 **Tier H 席位记录** · PR #32912 · head `7de0545a6e658b43a49af23c92fe4674a51b0ea7` · `Fixes #31874` 1. **形态:** draft PR 指向 `main`,仅 `Fixes #31874`。路径面(读文件清单):`docs/adr/0151-…`(一句 Non-goals)、`packages/runtime/src/**` 五个文件、`packages/services/service-automation/src/**` 四个文件、一个 changeset、`content/docs/{automation/flows,ui/actions,ai/agents}.mdx`。`docs/adr/**` 命中 governed 面 ⇒ Tier H。 2. **前提实测:** 隔离复核在树上核实 `flowStartRefusal` 恰有三个调用方,且是 `packages/runtime` 里仅有的三个请求可达的流程启动点;MCP `run_action` 经动作门;第四道门因参数必填而无法静默漏掉。 3. **门禁:** 代码 head `183ed607` 的 check-runs 36 成功、16 跳过、0 失败;文档轮 head `7de0545a` 的 check-runs 落地前重读。 4. **契约复核:** `CONTRACT_REVIEW_TIER` PASS,评论 6839053991,`Head-sha: 183ed60`,无 must-fix;`183ed607 → 7de0545` 仅动散文面(三页 `content/docs`),记录续管,`Regen-provenance:` 行在 PR 评论。 5. **接受的偏差与范围外去向:** 包级测试在 `20959acac0` 上测(head 只多一行测试 import,CI 为准);文档轮不重跑包测试(无包内测试读这三页)。复核 S1(`tool.zod.ts` 描述文字)与 S2(REST 上 AI 账号的确认门,待维护者定)→ 卡 #32924;N1/N2 两条 nit 接受不改。`Skills-docs: updated here`,三页文档席位逐句对照 diff 核过:账号行排在自触发行之后、`requiredPermissions` 行之前,与规则顺序一致;人、OAuth 代理、系统主体与以用户身份运行的流程不受此行判定,与代码一致。 6. **落地条款:** Tier H,等 governed 审批人(os-zhuang、hotlong)批准;批准后席位过落地前检、清 `pm:awaiting-merge`、转 ready、挂 auto-merge。`Clause-②: no (narrowing)`,BREAKING 横幅与 ADR-0087 `not-required` 处置在 changeset。 ## What changes **The ruling this executes.** Ruling record 6812617393 on #31874 (batch #1 item 4, letter C, maintainer 「同意」 2026-11-12T02:29Z): > **Chosen: C, the author's explicit opt-in.** When an AI service account starts a flow that runs as system, the start is refused by default. It is admitted only when the flow (or the action that starts it) carries the author's existing `ai.exposed: true` opt-in. **One rule on every door that can start such a flow:** the MCP door already applies it, and the REST trigger route, the REST action door and declarative endpoints get the same rule. No new spec key. > > **Execution:** one `domain:server` PR, `Clause-②: no (narrowing)`. The same rule goes on the doors above, with a refusal by name that tells the author which opt-in to add. Pins and an ablation. ADR-0151's Non-goals gain one sentence. The system-run branch also carries `principalKind` on its run facts (it does not today). **One rule, in the module every door already asks.** `packages/runtime/src/flow-start-admission.ts#flowStartRefusal` is the one check the trigger routes, the action door and a declared `type: 'flow'` endpoint ask before a flow starts. It gains rule 2, between the two it had: 1. an elevated self-triggered flow is refused to any caller but the system principal (unchanged); 2. **new:** an AI service account (`principalKind: 'agent'` with no `onBehalfOf`, ADR-0151 D3) starting a flow declared `runAs: 'system'` is refused unless what starts the flow at that door carries the author's `ai.exposed: true` opt-in; 3. the flow's own `requiredPermissions` (unchanged, and still asked of an admitted account). Each door states one fact about itself, as a required argument (`FlowStartDoor.aiExposed`), so a door that never considered the rule does not compile: | Door | What it states | AI service account at a `runAs: 'system'` flow | |:---|:---|:---| | `POST /api/v1/automation/NAME/trigger` and the legacy spelling (`domains/automation.ts#respondToFlowTrigger`) | no action in hand: `aiExposed: false` | refused | | declared endpoint of `type: 'flow'` (`endpoint-executor.ts#executeFlow`) | no action in hand: `aiExposed: false` | refused | | action door, REST actions route (`action-execution.ts#dispatchFlowAction`) | the action's own opt-in | admitted when the action declares `ai.exposed: true`, refused otherwise | | action door, MCP `run_action` (same function) | the action's own opt-in | admitted; the tool's exposure gate has already refused an action without the opt-in, for every caller | The Flow schema and the Endpoint schema declare no AI opt-in, and the ruling adds no key, so the opt-in stands only where an action is in hand. That reading is the narrower of two the ruling's "the flow (or the action that starts it)" allows; the other is in the report's `open_questions` for the maintainer. **One reading of the opt-in.** `action-execution.ts#actionIsAiExposed` is now the single predicate behind the MCP exposure gate (`actionAiExposureError`), the system-object exposure gate, the `list_actions` attestation and the flow start door. No second copy of the check exists. **The refusal.** `403 PERMISSION_DENIED` (no new code), the same words at every door, naming the opt-in and the doors where it stands: > An AI service account starts a flow that runs as the system only through an action its author opted into AI. Declare `ai: { exposed: true, description: … }` on an action of type 'flow' that targets the flow, and have the account run that action (the REST actions route or the MCP `run_action` tool). It names nothing of the flow, the action or the door. Nothing is dispatched. **The run keeps its kind.** `service-automation/src/runtime-identity.ts#resolveRunDataContext`: the system arm now carries `principalKind: 'agent'` when the run context does, as the user arm already did. `run-resume.ts#seedRunGrants` keeps the kind a launch door forwarded onto a `runAs: 'system'` run (setup resolves no grants for one, so nothing would re-seed it). It is attribution: `isSystem` answers before any gate reads the kind, so the run's own operations are authorized exactly as before; a hook reads the kind off its session (ADR-0151 D5). **ADR-0151, one sentence in Non-goals:** > **No elevated run on an account's own say**: an account's start of a flow that runs as the system (`runAs: 'system'`) is refused by default at every door that can start one and admitted only where the action that starts it carries its author's existing `ai.exposed: true` opt-in (`packages/runtime/src/flow-start-admission.ts#flowStartRefusal`; #31874, ruling record `6812617393`), the elevated run keeping `principalKind: 'agent'` on its run facts. **Unchanged.** A person, an agent acting for a person over OAuth, and the system principal start the same flows as before. An account starts a `runAs: 'user'` flow (the default) at every door as before. The `ai.requiresConfirmation` gate does not move: it stays on the doors that ask the opt-in of every action. The run log's `trigger` record is not touched. **Not in this PR.** The prose of `packages/spec/src/ai/tool.zod.ts`, which describes the REST actions route as outside the `ai.exposed` opt-in and is now imprecise for this one pair: it is with card #32924 (spec lane). No `scripts/adr-anchors/` entry (outside the claimed surface; the code carries the ADR id). ## Tests - `packages/runtime/src/flow-start-required-permissions.test.ts`: a new top-level `describe` on the shared four-door harness, 36 tests (the file: 45 before, 81 now). For `screen` and `api` flows: the account refused at the trigger route and at the declared endpoint even though an exposed action targets the flow; refused at the REST actions route behind an action without the opt-in; admitted at REST and MCP behind an action with it, the run carrying `principalKind: 'agent'`. The refusal is asserted by `code`, `status` and its words (the message is the contract that names the remedy), and every refusal pin asserts the engine was never called. Order pins: rule 1 answers an account first; holding the flow's capability does not open rule 2; an admitted account is still judged by `requiredPermissions`. CONTROLS at every door: a person, an OAuth-delegated agent, the system principal, and an account at a `runAs: 'user'` or undeclared flow, all admitted with no opt-in anywhere. - `packages/services/service-automation/src/run-agent-account-kind.test.ts`: a new `describe`, 4 tests (the file: 5 before, 9 now). The door-forwarded kind survives run setup on a system run and rides the facts beside `isSystem`, with no grants resolved; a system run handed only a user carries none; CONTROLS for a person and for non-`agent` values. **Ablations** (fix committed first; each mutation through `node scripts/ablation-replace.mjs`, which proves the write on disk and the restore against `HEAD`; these suites resolve the mutated files from `src/`, so no build sits between mutation and reading): | # | Forbidden behaviour put back | Suite | Result | |:---|:---|:---|:---| | 1 | trigger routes state `aiExposed: true` | runtime file | 4 failed, 77 passed | | 2 | declared endpoint states `aiExposed: true` | runtime file | 4 failed, 77 passed | | 3 | action door states `aiExposed: true` whatever the action declares | runtime file | 5 failed, 76 passed | | 4 | rule 2 removed from `flowStartRefusal` | runtime file | 11 failed, 70 passed | | 5 | system arm of `resolveRunDataContext` drops the kind | service-automation file | 1 failed, 8 passed | | 6 | run setup deletes the kind on a system run | service-automation file | 1 failed, 8 passed | <details> <summary>Ablation failures and restore proofs</summary> ```text #1 FAIL trigger: an elevated 'screen' flow — the account is refused 403 PERMISSION_DENIED, never dispatched FAIL trigger: an elevated 'api' flow — the account is refused 403 PERMISSION_DENIED, never dispatched FAIL one refusal at every door that can answer it: the same status, code and words FAIL the order of the rules: trigger: holding the flow's capability does not open it AssertionError: expected { status: 200, code: undefined, …(1) } to match object { status: 403, …(1) } ablation-replace: ok restored: blob == HEAD (f8f81b8) and `git diff HEAD` is empty #2 FAIL endpoint: an elevated 'screen' flow — the account is refused 403 PERMISSION_DENIED, never dispatched FAIL endpoint: an elevated 'api' flow — the account is refused 403 PERMISSION_DENIED, never dispatched FAIL one refusal at every door that can answer it: the same status, code and words FAIL the order of the rules: endpoint: holding the flow's capability does not open it AssertionError: expected { status: 200, code: undefined, …(1) } to match object { status: 403, …(1) } ablation-replace: ok restored: blob == HEAD (9094884) and `git diff HEAD` is empty #3 FAIL REST /actions: an elevated 'screen' flow behind an action WITHOUT the opt-in — the account is refused, never dispatched FAIL REST /actions: an elevated 'api' flow behind an action WITHOUT the opt-in — the account is refused, never dispatched FAIL the refusal names the opt-in the author adds, and nothing of the flow FAIL one refusal at every door that can answer it: the same status, code and words FAIL the order of the rules: REST /actions: holding the flow's capability does not open it AssertionError: expected { status: 200, code: undefined, …(1) } to match object { status: 403, …(1) } ablation-replace: ok restored: blob == HEAD (488d079) and `git diff HEAD` is empty #4 the 11 pins of #1, #2 and #3 together (the three share the "one refusal at every door" pin) ablation-replace: ok restored: blob == HEAD (fac1b4d) and `git diff HEAD` is empty #5 FAIL the door-forwarded kind survives run setup and rides every data operation, beside isSystem AssertionError: expected { isSystem: true, …(3), …(1) } to match object { isSystem: true, …(2) } ablation-replace: ok restored: blob == HEAD (fea0d07) and `git diff HEAD` is empty #6 FAIL the door-forwarded kind survives run setup and rides every data operation, beside isSystem AssertionError: expected undefined to be 'agent' // Object.is equality ablation-replace: ok restored: blob == HEAD (7572dcc) and `git diff HEAD` is empty ``` The ablations ran on `60bea520dd`; the files they mutate are byte-identical at the PR head (the later commits touch the ADR, the changeset, one test file's cast, and merge `main`). </details> ## Acceptance notes - **"One rule on every door"**: the rule is one `if` in `flowStartRefusal`; the three call sites differ only in the fact they state. The MCP door's existing check and the new rule read the opt-in through the same predicate. - **"A refusal by name that tells the author which opt-in to add"**: the message above; pinned. - **"Pins and an ablation"**: 40 tests, six ablations, one per door plus the rule itself and the two halves of the kind. - **"ADR-0151's Non-goals gain one sentence"**: exactly one line added to the ADR, nothing else in `docs/adr/**`. - **"The system-run branch also carries `principalKind` on its run facts"**: `resolveRunDataContext`'s system arm, pinned and ablated. - **"No new spec key"**: `packages/spec` is untouched. - **Merge**: `origin/main` merged once before opening (`5c0f113498`, two commits, none touching these packages). ## Verification Head `7de0545a6e658b43a49af23c92fe4674a51b0ea7`. Whole-tree build after the merge: `turbo run build`, 120 of 120 tasks successful. | Check | Result | Measured on | |:---|:---|:---| | `pnpm --filter @objectstack/runtime typecheck` (source and test layer) | exit 0 | `183ed60759` | | `pnpm --filter @objectstack/service-automation typecheck` (source and test layer) | exit 0 | `20959acac0` | | `pnpm --filter @objectstack/runtime test` | Test Files 588 passed (588) · Tests 10287 passed, 19 skipped (10306) | `20959acac0` | | `pnpm --filter @objectstack/service-automation test` | Test Files 278 passed (278) · Tests 3811 passed (3811) | `20959acac0` | | the two pin files | 81 passed (81) · 9 passed (9) | `183ed60759` | | `pnpm lint` | exit 0 | `183ed60759` | | derived gate families: `node scripts/pm/dispatch-gates.mjs --commands`, each run, then `--ran` | 109 derived, 109 run, 0 NOT-MEASURED, 0 UNRUN; all 109 exit 0 | the head | | full dogfood battery, `pnpm --filter @objectstack/dogfood test` under the verify lock | VERDICT command-exit 0 · Test Files 456 passed, 3 skipped (459) · Tests 3831 passed, 42 skipped (3873) · no failure | the head | Docs round (`183ed60759` to `7de0545a6e`): one commit, three `content/docs` pages, 14 insertions and 4 deletions, no file of any package. No merge of `main`. The docs paths add 27 derived gate families to the 82; all 109 were run on the head and exit 0 (`Run reconciliation — 109 derived, 109 run, 0 NOT-MEASURED, 0 UNRUN.`). The package suites, typechecks, `pnpm lint` and the dogfood battery were not run again: no test in `packages/**` reads these three pages, and their readings on `183ed60759` stand for the code. The claim was re-posted whole with the three pages in its file surface (comment 6838944179). `20959acac0` is the head's parent. The head adds one module-top import line to the runtime pin file and nothing else: the first pass of the 82 gates, on `20959acac0`, had one red, `pnpm check:test-source-alias` (the edited pin file reaches a dynamic import of `@objectstack/metadata` in the source under test), and the import is that gate's own prescribed fix. After it, the runtime typecheck, both pin files, lint, the whole gate list and the dogfood battery were run again on the head. No file of `service-automation` and no non-test file differs between the two commits. <details> <summary>Gate reconciliation and the 82 recorded exit codes</summary> ```text Run reconciliation — 82 derived, 82 run, 0 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 82 derived famil(ies) accounted for — 82 run, 0 NOT-MEASURED (a DERIVED zero — all 82 recorded an exit code and none of them is 3). pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-adr-links.mjs :: exit 0 node scripts/check-adr-links.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0 node scripts/check-tenant-audit-census.mjs :: exit 0 node scripts/check-tenant-audit-census.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/lint run check:doc-formula-expressions :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm --filter @objectstack/spec run check:error-code-provenance :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:adr-index :: exit 0 pnpm check:adr-symbol-anchors :: exit 0 pnpm check:authz-resolver :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:durability-log-level :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:error-status-conformance :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:init-service-contract :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:object-def-param-keys :: exit 0 pnpm check:objectql-double-limit :: exit 0 pnpm check:optional-error-sink :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:package-naming :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:pm-governed-merges :: exit 0 pnpm check:pm-prior-rulings :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:route-envelope :: exit 0 pnpm check:settings-bind-window :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:startup-registry-verdict :: exit 0 pnpm check:swallow-census-controls :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 pnpm check:wildcard-fallthrough :: exit 0 ``` </details> <details> <summary>Dogfood battery</summary> ```text os-verify-lock: VERDICT command-exit 0 · held the lock 1717s (28m37s) · waited 0s Test Files 456 passed | 3 skipped (459) Tests 3831 passed | 42 skipped (3873) Duration 1715.06s ``` One run, no shard and no path filter, after the closure build. This PR adds or edits no dogfood file, so the 3 skipped files and 42 skipped tests are the suite's own. </details> CI on the PR runs the whole farm; none of it was re-run locally beyond the derived list above. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4d1G1mMRC6sZXKcRqqu)_ <!-- signed: domain:server#8 · os-elon-musk · session_016WV4cwqTK71kjQzHae8T5J --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4a1e9cc commit 64b46fe

14 files changed

Lines changed: 455 additions & 35 deletions
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/runtime': patch
3+
'@objectstack/service-automation': patch
4+
---
5+
6+
fix(runtime, service-automation)!: an AI service account starts a flow that runs as the system only through an action its author opted into AI
7+
8+
Clause-②: no (narrowing) — an AI service account's start of a flow declared `runAs: 'system'` is refused with `403 PERMISSION_DENIED` at `POST /api/v1/automation/NAME/trigger` (and the legacy `POST /api/v1/automation/trigger/NAME`), at a declared endpoint of `type: 'flow'`, and at the REST actions route when the action that starts the flow does not declare `ai.exposed: true`; nothing is widened.
9+
Metadata-protocol: none
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) no key of any schema is added, removed or re-shaped and no stored row is converted: what moves is the answer an AI service account gets when it starts a flow that runs as the system, and opting an action into AI is an author's choice made by hand, not a mechanical conversion -->
12+
13+
**BREAKING** for a deployment whose AI service account (ADR-0151) starts a flow declared `runAs: 'system'` through the trigger route, through a declared `type: 'flow'` endpoint, or through the REST actions route on an action that does not declare `ai.exposed: true`.
14+
15+
- **The rule (ADR-0151 Non-goals).** A flow that runs as the system writes with the platform's authority, not the caller's. An AI service account starts one only through an action whose author opted it into AI: a `type: 'flow'` action that declares `ai: { exposed: true, description: … }`. It is the opt-in the MCP `run_action` tool already asks of every action, and no new key. One rule, asked by every door that starts a flow by name (`flowStartRefusal`): the trigger route and a declared endpoint start a flow with no action in hand, so nothing there carries the opt-in and the account is refused; the action door, behind REST and MCP alike, admits the account when the action carries it.
16+
- **The answer.** `403 PERMISSION_DENIED`, the same words at every door: "An AI service account starts a flow that runs as the system only through an action its author opted into AI. Declare `ai: { exposed: true, description: … }` on an action of type 'flow' that targets the flow, and have the account run that action (the REST actions route or the MCP `run_action` tool)." Nothing is dispatched. It is checked after the refusal of an elevated self-triggered flow and before the flow's `requiredPermissions`, which still answers an admitted account.
17+
- **The run keeps its kind.** The elevated run an admitted account starts carries `principalKind: 'agent'` on the facts of every data operation it makes, so a hook reading its session tells an agent-started elevated run from a person's. It is attribution: the run's own operations are authorized as the system, exactly as before.
18+
- **Unchanged.** A person, an agent acting for a person over OAuth, and the system principal start the same flows as before. An account starts a flow that runs as the user (`runAs: 'user'`, the default) at every door as before, under its own grants. Flows that start on their own trigger (a record change, a schedule) are not judged.
19+
- **Who moves, and the fix.** For each flow declared `runAs: 'system'` that an AI service account starts: declare an action of `type: 'flow'` whose `target` is the flow, with `ai: { exposed: true, description: … }` (or add that block to the action that already starts it), and have the account run the action, `POST /api/v1/actions/OBJECT/ACTION` or the MCP `run_action` tool, in place of the trigger route or the declared endpoint. A flow the account should run under its own grants declares `runAs: 'user'` instead and needs no action.

‎content/docs/ai/agents.mdx‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,15 @@ SKILL.md download (`GET /api/v1/mcp/skill`), and API-key minting.
111111
key — the account's own included — can neither register an account nor mint
112112
one's key. An account is never counted as one of the administrators that
113113
keep an organization manageable, and never receives administrator mail.
114+
A flow that runs as the system (`runAs: 'system'`) writes past the
115+
account's grants, so an account starts one only through an action whose
116+
author opted it into AI (`ai: { exposed: true }`), run over
117+
`POST /api/v1/actions/...` or the MCP `run_action` tool. The flow's trigger
118+
route and a declared `type: 'flow'` endpoint refuse it **403**
119+
`PERMISSION_DENIED`, and the refusal names the declaration to add (see
120+
[Run a flow via API](/docs/automation/flows#run-a-flow-via-api)). A flow
121+
that runs as the user, the default, it starts at every door under its own
122+
grants.
114123
Its lifecycle has doors of its own, each taking a signed-in session only
115124
(`POST /api/v1/auth/service-account/<door>`):
116125
- **`suspend`** (its owner or an administrator) stops every key on its

‎content/docs/automation/flows.mdx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2678,8 +2678,9 @@ door's own admission check, made before anything is dispatched:
26782678
|:---|:---|:---|:---|
26792679
| `404` | — | No flow by that name is held in this deployment. A flow stored with no `start` node is never armed (see the `FLOW_NO_START_NODE` row), so it answers here too | Check the name; nothing was dispatched |
26802680
| `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) |
2681-
| `403` | `PERMISSION_DENIED` | The flow declares `requiredPermissions` and the caller, not the system principal, does not hold every capability it names. Checked after the row above, at the same doors; the message names the declared and the missing capabilities | Grant the capability through a permission set's `systemPermissions`, or start the flow as someone who holds it |
2682-
| `404` | `RECORD_NOT_FOUND` | The start names a record (`recordId`, or the object's id alias such as `crmLeadId`) that the caller, not the system principal, cannot read in its own scope, or that does not exist: the two get one answer, the one the action door gives. Checked after the two rows above, at the same doors. A record key that is not one id, or a record named with no `objectName` for a flow declared `runAs: 'system'`, is refused `400` `VALIDATION_FAILED` naming the key. Where the flow's own definition reads a start input as the id of a record of a fixed object (a `get_record`, `update_record` or `delete_record` node with a literal `objectName` whose `filter.id` or `filter.id.$eq` is the input, or whose `filter.id.$in` is; a `screen` node with a literal `objectName` whose `recordId` is the input; a `subflow` or `map` node that hands the input to a callee input the callee reads so), that input is also loaded in the caller's own scope from THAT object, whatever object the start names, or none, and whatever the flow runs as: a value the caller cannot read there gets this `404`, and a value that is not one id (or a list of ids, where the definition reads a list) is refused `400` `VALIDATION_FAILED` naming the input. An input the flow declares a record id (`objectName` on the variable, [above](#a-start-input-that-is-a-record-id)) is loaded from the declared object the same way, whether or not the definition reads it | Start the flow on a record the caller can read, and name the record's object (`objectName`) beside `recordId`. Hand an input the flow reads as a record id the id of a record the caller can read in the object the flow reads it from, in the shape the flow reads (one id, or a list of ids) |
2681+
| `403` | `PERMISSION_DENIED` | The caller is an [AI service account](/docs/ai/agents) and the flow is declared `runAs: 'system'`. An account starts a flow that runs as the system only through an action its author opted into AI (`ai.exposed: true`). This route and a declared `type: 'flow'` endpoint start a flow by name with no action in hand, so they refuse an account every elevated flow; a `type: 'flow'` action (REST and MCP `run_action`) admits the account when the action declares the opt-in, and refuses it otherwise. Checked after the row above, at the same doors. A person, an agent acting for a person over OAuth and the system principal are not judged by this row, and neither is a flow that runs as the user | Declare `ai: { exposed: true, description: … }` on an action of `type: 'flow'` whose `target` is the flow, and have the account run that action (`POST /api/v1/actions/...` or MCP `run_action`). A flow the account should run under its own grants declares `runAs: 'user'` instead |
2682+
| `403` | `PERMISSION_DENIED` | The flow declares `requiredPermissions` and the caller, not the system principal, does not hold every capability it names. Checked after the two rows above, at the same doors; the message names the declared and the missing capabilities | Grant the capability through a permission set's `systemPermissions`, or start the flow as someone who holds it |
2683+
| `404` | `RECORD_NOT_FOUND` | The start names a record (`recordId`, or the object's id alias such as `crmLeadId`) that the caller, not the system principal, cannot read in its own scope, or that does not exist: the two get one answer, the one the action door gives. Checked after the three rows above, at the same doors. A record key that is not one id, or a record named with no `objectName` for a flow declared `runAs: 'system'`, is refused `400` `VALIDATION_FAILED` naming the key. Where the flow's own definition reads a start input as the id of a record of a fixed object (a `get_record`, `update_record` or `delete_record` node with a literal `objectName` whose `filter.id` or `filter.id.$eq` is the input, or whose `filter.id.$in` is; a `screen` node with a literal `objectName` whose `recordId` is the input; a `subflow` or `map` node that hands the input to a callee input the callee reads so), that input is also loaded in the caller's own scope from THAT object, whatever object the start names, or none, and whatever the flow runs as: a value the caller cannot read there gets this `404`, and a value that is not one id (or a list of ids, where the definition reads a list) is refused `400` `VALIDATION_FAILED` naming the input. An input the flow declares a record id (`objectName` on the variable, [above](#a-start-input-that-is-a-record-id)) is loaded from the declared object the same way, whether or not the definition reads it | Start the flow on a record the caller can read, and name the record's object (`objectName`) beside `recordId`. Hand an input the flow reads as a record id the id of a record the caller can read in the object the flow reads it from, in the shape the flow reads (one id, or a list of ids) |
26832684
| `409` | `FLOW_DISABLED` | The flow exists but is switched off | Enable it — the identical request then succeeds |
26842685
| `422` | `FLOW_NO_START_NODE` | A defensive exit of the engine that no door reaches today. A flow with no `start` node is refused at registration (`POST` / `PUT /api/v1/automation` answer `400` `VALIDATION_FAILED`), and a stored one is not armed, so its trigger answers `404` above, not `422` | Add a `start` node to the flow; its metadata read shows `registration: refused` until then |
26852686
| `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 |

‎content/docs/ui/actions.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -615,7 +615,7 @@ The endpoint dispatches on the **declared `type`**, exactly like the MCP
615615
| `type` | Over REST |
616616
|:---|:---|
617617
| `script` | Runs the registered handler / inline body. |
618-
| `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, a stored flow with no `start` node included, as it is never armed / **409** `FLOW_DISABLED` / **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. A target that declares its own `requiredPermissions` is refused **403** `PERMISSION_DENIED` to a caller who does not hold every capability it names, even when the action declares none. 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. |
618+
| `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, a stored flow with no `start` node included, as it is never armed / **409** `FLOW_DISABLED` / **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. A target that declares its own `requiredPermissions` is refused **403** `PERMISSION_DENIED` to a caller who does not hold every capability it names, even when the action declares none. An [AI service account](/docs/ai/agents) is refused a target declared `runAs: 'system'` **403** `PERMISSION_DENIED` unless the action declares `ai.exposed: true`: an action with the opt-in is the one way an account starts a flow that runs as the system, here and over MCP `run_action`. 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. |
619619
| `api` | **Same-origin `target`** (a path starting with `/`): the door runs its gates — the sign-in floor, `requiredPermissions`, the packaged-action switch, the param contract, the subject-row load — and then **forwards the request in-process** to `target` with your own credentials, assembling the body exactly as the Console does (`recordIdParam` / `recordIdField` from the subject row, `bodyShape`, `bodyExtra` merged last, `organizationId` for an `/api/v1/auth/` target, `method`). The target endpoint still authorizes you itself; its status and body come back as the answer (its `data` unwrapped), and a credential rotation it emits (`Set-Cookie`, `set-auth-token`) is relayed. A `${ctx.selection.*}` or `{{page.<var>}}` token exists only in the browser and is refused **400** by name. **Off-origin `target`** (another host): **400** — the browser calls it directly, and such an action cannot be switched off in the activation ledger (the write door refuses, **409**, with the reason). |
620620
| `url` / `modal` / `form` | **400** — client-side navigation; there is nothing for the server to run. |
621621
@@ -710,7 +710,7 @@ Pick the **posture** by who drives your door:
710710

711711
| `posture` | Rules | Use it for |
712712
|:---|:---|:---|
713-
| `'rest'` (default) | Exactly the REST door's. | A door a person drives, or your own server code. |
713+
| `'rest'` (default) | Exactly the REST door's. It reads `ai.exposed` once: an AI service account starting a `runAs: 'system'` flow needs the action's opt-in (the `flow` row under [Call it over REST](#call-it-over-rest)). | A door a person drives, or your own server code. |
714714
| `'ai'` | The REST door's, plus the three the MCP `run_action` tool adds: a `sys_*` action needs its own `ai.exposed`, every action needs `ai.exposed: true`, and an action with `ai.requiresConfirmation` is refused **428** `ACTION_CONFIRMATION_REQUIRED` until the call carries `confirm: true`. A script action with no handler binding is also refused. A client-side or off-origin `api` action is refused **400** as under `'rest'`, with `run_action`'s sentence (`cannot be invoked via MCP`) instead of the REST prescription, so the agent is not handed the action's `target`. | **A host's in-product AI tool** — an agent picks the action, so it takes the AI door's rules. |
715715

716716
`posture` is `'rest'`, `'ai'` or absent (`'rest'`); any other value is

‎docs/adr/0151-ai-service-account-a-headless-agent-is-a-registered-principal-of-its-own.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ Open code defines the identity and counts nothing: it caps nothing and refuses n
147147
- **No console** — inventory, kill switch, trace, usage and cost: cloud#3820's cards consume this identity.
148148
- **No MCP tool-call interceptor**: O2.
149149
- **No change to OAuth agents**, and nothing about cutting off live OAuth tokens or suspending a person's own key: O5.
150+
- **No elevated run on an account's own say**: an account's start of a flow that runs as the system (`runAs: 'system'`) is refused by default at every door that can start one and admitted only where the action that starts it carries its author's existing `ai.exposed: true` opt-in (`packages/runtime/src/flow-start-admission.ts#flowStartRefusal`; #31874, ruling record `6812617393`), the elevated run keeping `principalKind: 'agent'` on its run facts.
150151
- **Not decided here**: OAuth `client_credentials`; an account acting on behalf of a person (token exchange); a flow or job `runAs` naming an account (ADR-0073's automation principal stays the identity of user-less runs); the `service` kind; external or multi-organization accounts; a `/mcp` policy that refuses persons' keys.
151152

152153
---

0 commit comments

Comments
 (0)