Skip to content

Commit bb169c3

Browse files
fix(plugin-security): a record an action body inserts is owned by the user who ran the action (#34957)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBQ3DFv6XZAspQRYGQoEWhr8)_ Fixes #34885 Clause-②: yes Metadata-protocol: none repo:objectstack#3 · os-support-ai · session_01WGufzgNCAXyGfBQFZBwixH ## 维护者速读 - **改了什么**:动作(action)脚本里用 `ctx.api.object(X).insert` 新建的记录,现在会把执行动作的用户写进 `owner_id`,和用户直接新建记录时一样。 - **为什么改**:以前这类记录的 `owner_id` 是空的;在私有对象上,普通用户运行动作后看不到、也改不了自己刚建的记录(qa 在差旅报销和服务台场景里都撞到了)。 - **风险与回滚**:只影响动作脚本里的新建,且只填空的 `owner_id`;flow、hook、种子数据和其它系统写入不变。回滚就是 revert 本 PR;已存的旧记录不会被改。 分派规则(assignment rules)此前会路由动作脚本建的无主记录,现在与直接新建一致归执行人、不再被路由。 - **先看**:`packages/plugins/plugin-security/src/owner-anchor-stamp.ts`(新规则全文);`security-plugin-authz-middleware.ts` 里 isSystem 放行前新增的那段,和 3.5 步改成共用函数的那几行;`action-body-insert-owner-stamp.test.ts`。 - **两分钟验证**:`pnpm --filter @objectstack/plugin-security exec vitest run src/action-body-insert-owner-stamp.test.ts`,预期 23 个用例全部通过。 - **需要你做的**:无,席位落地。 ## What changes An action body's `ctx.api` and `ctx.engine` run the invoker's envelope elevated: `{ ...envelope, isSystem: true }` plus the `'action'` app-automation elevation mark (`buildActionExecutionContext`, `packages/runtime/src/action-execution.ts`). The authz middleware's `isSystem` bypass returned before step 3.5, the empty-owner stamp. So the body's insert landed with `owner_id` null while `created_by` named the invoker, and on a private object the invoker could neither read nor update the row. - New `packages/plugins/plugin-security/src/owner-anchor-stamp.ts`. It holds the insert stamp step 3.5 applies (`hasEmptyOwner`, `stampEmptyOwner`, `writesOwner`), the predicate `isActionBodyElevation` (`isSystem`, the `'action'` mark, no `flowRunId`), and `stampActionBodyInsertOwners`. - `security-plugin-authz-middleware.ts`: ahead of the `isSystem` bypass, beside the existing app-automation checks, an insert under an action body's elevation on an object that carries `owner_id` has every EMPTY owner stamped. Step 3.5 now calls the same `stampEmptyOwner`, so there is one owner rule, not two copies. Step 3.5's behaviour is byte-for-byte the same. - The stamp follows step 3.5 exactly: - The guest is stamped with nothing (ADR-0138 D1). - Under delegation the stamp is the envelope's `userId`, the principal a direct create is stamped with (ADR-0090 D10). - Every row of a batch is stamped. - An `owner_id` the body sets itself is kept, another user's included. The body is trusted code, so the forge/transfer guard is not run on it. - Queue (ADR-0142 D3): the body is treated as step 3.5 treats a trusted writer (the grant holder). - `owner_id` supplied empty beside a supplied queue parks the row unowned. - An absent owner is stamped, and the queue becomes the row's home queue. - The queue is not resolved here, as it was not before (system bypass). - What the mark covers: every handler an action door dispatches, not only a script body's `ctx.api`. A host code action handler and an action reached through `ObjectRepository.execute` carry the same `'action'` mark, so their inserts are stamped the same way. - Assignment rules (ADR-0142 D5) route only a row whose `owner_id` and `queue` are both still empty, after `beforeInsert` hooks. Seat ruling 6959099293: an action-body insert is owned exactly as the invoker's direct create of the same row would be. Measured on a routed object: - The invoker's direct create is stamped by step 3.5 before the rule runs, so it is not routed. - An action-body insert is now owned the same way, so assignment rules route neither. - Before this change, an action body's unowned, queue-less insert on such an object was routed by the rule. It now goes to the invoker. - A body has no spelling today that asks a rule to route its row (`owner_id: null` is stamped too). - `Metadata-protocol` stays `none`: no authored meaning changes, and the action path joins the existing direct-create behaviour. - Unchanged: a flow run (a `flowRunId` wins over the mark, as `elevationSource` reads it), a hook's `runAs: 'system'` (`'hook'` mark), seed/boot/import writes, and a bare `isSystem`. An unowned, queue-less insert from any of them is still routed. - `content/docs/permissions/system-context.mdx`: row 2 ("`owner_id` is not auto-stamped on INSERT") would be false after this change. It now names the action-body exception, keyed `isActionBodyElevation`, the routing consequence and the mark's reach, and the site register was regenerated with `--write`. `check:system-context-census` required this. - `packages/core/src/security/app-automation-elevation.ts`: the module header said the mark's "only reader narrows (it refuses; it admits nothing)". It now names the owner stamp as a second reader: the stamp gives ownership of an empty `owner_id` to the context's own `userId`, never to another principal, and admits no operation. The header ships in `@objectstack/core`'s `dist/index.d.ts`, so the changeset adds a `@objectstack/core` patch line. Who sets the stamp cannot be steered by a client. The mark is a symbol key: `APP_AUTOMATION_ELEVATION = Symbol.for(...)` in `packages/core/src/security/app-automation-elevation.ts`. Only server derivation sites set it: - `packages/runtime/src/action-execution.ts` `buildActionExecutionContext`; - `packages/objectql/src/engine-object-repository.ts` `execute`; - the hook sites in `engine-scoped-context.ts`. A request body, a query string or a stored row has no spelling for a symbol. The sandbox boundary is JSON in both directions (`packages/runtime/src/sandbox/body-runner.ts`, the entry-snapshot note). `ObjectRepository.insert(data)` takes no context, so the repository's own context is used. The stamped id is the envelope's `userId`, never a payload value. ## Tests `packages/plugins/plugin-security/src/action-body-insert-owner-stamp.test.ts` uses the real `SecurityPlugin`, a real `ObjectQL` over better-sqlite3, and the real `SharingService` with its middleware. The two private objects rely on the registry-injected `owner_id` and `queue` columns. One of them (`abo_ticket`) is routed by a declared assignment rule to a member of the organization. The body's `ctx.api` is `engine.createContext(markAppAutomationElevation({ ...envelope, isSystem: true }, 'action'))`, which is what `buildActionApi` builds. The suite has 23 cases: - the repro: owner is the invoker, who can read the row by id and update it; a direct create is the control; an owner supplied as null or `''` is stamped; - an owner the body sets is kept (another user's, and the invoker's own); - a guest invoker gets no stamp; - delegation: the stamp equals a direct create under the same envelope (the agent); - forge: a context spelled through JSON with `isSystem` and the mark's name as a string is not stamped; a payload `created_by` does not move the stamp; - controls that still land owner null: a flow run, a flow reaching an action, a hook's `runAs: 'system'`, a bare `isSystem` with a user, and a bare `isSystem`; - a batch from a body; - queue park, and queue with an absent owner; - routed object (ADR-0142 D5): - the rule routes on this rig (a system insert and a flow run's insert go to the rule's user); - the invoker's direct create is stamped and not routed; - an action body's insert is owned exactly as that direct create (the invoker, no queue, readable by the invoker); - a body's `owner_id: null` is stamped too. <details><summary>Results</summary> - At 6cacf68, `pnpm --filter @objectstack/plugin-security exec vitest run --maxWorkers=2 src/action-body-insert-owner-stamp.test.ts` (closure rebuilt): Test Files 1 passed (1), Tests 23 passed (23); lock VERDICT command-exit 0. - At 6cacf68, `pnpm --filter @objectstack/plugin-security typecheck && pnpm --filter @objectstack/core typecheck`: VERDICT command-exit 0. - At 6cacf68, `pnpm --filter @objectstack/core exec vitest run src/security/app-automation-elevation.test.ts`: 6 of 6 passed. - At 330df04, the full plugin-security suite: Test Files 275 passed (275), Tests 6913 passed, 45 skipped; exit 0. </details> <details><summary>Ablation (one-shot, committed tree, restored to HEAD by blob hash)</summary> All runs used `node scripts/ablation-replace.mjs`. The suite imports the package's `src` relatively, so no dist rebuild is involved. 1. Remove the action-body stamp call (origin/main's behaviour for the action path), at 6cacf68. The mutation landed (anchor 1 to 0, blob e083bd0 to fa951e5c9ebc). Result: 9 failed and 14 passed. The two routed-object body cases failed with "expected 'usr_abo_lead' to be 'usr_abo_invoker'", so before this change the rule routed the body's row. Restored: blob equals HEAD and `git diff HEAD` is empty. 2. Widen `isActionBodyElevation` to `!!context?.isSystem`, at 330df04. The mutation landed (blob 02233cc to f5b51e91341e). Result: 5 failed. The failures were the JSON-spelt context, the flow run, the flow reaching an action, the hook `runAs: 'system'`, and the bare `isSystem` with a user. Restored to HEAD. </details> ## Acceptance notes - Assignment routing (ADR-0142 D5) is disclosed, per seat ruling 6959099293. - An action-body insert is now owned like a direct create, so assignment rules route neither; this is pinned on a routed object. - An action body's unowned, queue-less insert that a rule used to route now goes to the invoker. - A body has no spelling today that asks a rule to route its row. - Rows stored before this change keep `owner_id` null. An administrator holding the transfer grant can assign their owners. This PR does not include a backfill. - The mark rides every spread of the body's context, as its module header states. So a write a body's insert sets off under the same context is also stamped when its owner is empty: a hook that inherits the context (not `runAs: 'system'`, which re-marks `'hook'`), or a `sudo()` taken inside the body. That is the invoker's own action. - `created_by` (objectql `plugin.ts`, from `session.userId`) and the new stamp both read the envelope's `userId`, so they name the same user for an ordinary invoker. This was established by reading the code, not measured. The rig boots a bare `ObjectQL` without the audit hook. - The claimed file surface was amended to include `content/docs/permissions/system-context.mdx` (6958279133) and `packages/core/src/security/app-automation-elevation.ts`, where only header text changed (this round). ## Verification <details><summary>Local gate subset (dispatch-gates --commands, re-run on the final head 6cacf68)</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` gave 104 commands, each run with its exit code captured before any pipe (two more than at b413fd2: `check-dev-prereqs --self-test` and `check:kernel-hook-pairs`). - 100 exited 0, including `check:system-context-census`, `check:doc-authoring`, `check:kernel-hook-pairs`, `check:adr-anchors` and the changeset gates. - 4 are NOT MEASURED (exit 3, prerequisite not met; CI owns them): `check-plugin-teardown-shape.mjs --self-test` (history the shallow clone lacks), and spec `check:skill-examples`, `check:dual-build-cjs-loads` and `check:i18n` (they need a whole-workspace build). `check:dual-build-cjs-loads` and `check:i18n` exited 0 at b413fd2, and this round's only published-code change is a core header comment. - `dispatch-gates --ran`: "104 derived famil(ies) accounted for — 100 run, 4 NOT-MEASURED (4 DERIVED from a recorded exit 3)". - Families CI runs (Test Core, Build Core, Lint & Repo Gates, TypeScript Type Check and the rest) are left to this PR's check-runs, which are green at 6cacf68. </details> overlap-check before the push of 6cacf68: `✓ origin/main: merges cleanly`, `✓ #34817 (shares content/docs/permissions/system-context.mdx): merges cleanly`, `VERDICT clean exit 0`. Earlier runs also listed `✓ #34811 (shares security-plugin-authz-middleware.ts): merges cleanly`. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzgNCAXyGfBQFZBwixH --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d652996 commit bb169c3

6 files changed

Lines changed: 608 additions & 18 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
'@objectstack/plugin-security': patch
3+
'@objectstack/core': patch
4+
---
5+
6+
fix(plugin-security): a record an action body inserts is owned by the user who ran the action
7+
8+
Clause-②: yes
9+
Metadata-protocol: none
10+
11+
An action body's `ctx.api` (and `ctx.engine`) runs the invoking user's context elevated to system. The security middleware's system bypass skipped the owner stamp a direct create gets, so a row the body inserted with `ctx.api.object(X).insert({...})` was stored with `owner_id` null, while `created_by` named the invoker. On an object with `sharingModel: 'private'` a non-admin invoker then could not read or update the record their own action had just created: `get` by the returned id answered not-found.
12+
13+
An action body's insert now fills an EMPTY `owner_id` with the invoker, as a direct create by that user does:
14+
15+
- every row of a batch insert whose owner is empty is stamped;
16+
- an `owner_id` the body sets itself is kept, another user's included (the body is trusted code, as before);
17+
- a guest invoker is stamped with nothing (ADR-0138 D1);
18+
- under delegation the stamp names the same principal a direct create under that context names (ADR-0090 D10);
19+
- a body that names an ownership queue and supplies `owner_id` empty beside it parks the row unowned in the queue; a body that names a queue and leaves `owner_id` out gets an owned row with that home queue (ADR-0142 D3).
20+
21+
This covers every handler an action door dispatches, not only a script body's `ctx.api`. A host code action handler and an action reached through `ObjectRepository.execute` run under the same action context, and their inserts are stamped the same way.
22+
23+
Assignment rules (ADR-0142 D5) route only a row whose `owner_id` and `queue` are both still empty. An action-body insert is now the invoker's own record, as a direct create by that user already was, so assignment rules route neither. Before this release, an action body's unowned, queue-less insert on an object a rule reaches was routed by the rule. It now goes to the invoker. A body has no spelling today that asks a rule to route its row.
24+
25+
`@objectstack/core`: the header of the app-automation elevation mark (shipped in its type declarations) now names the owner stamp as a second reader beside the refusals.
26+
27+
Unchanged: flows (`runAs: 'system'` or not), hooks with `runAs: 'system'`, seed, boot and import writes, and any other system context. They still store the owner they write, or none, and an unowned, queue-less insert from one of them is still routed by assignment rules. Rows stored before this release keep `owner_id` null; an administrator can assign their owners.

‎content/docs/permissions/system-context.mdx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ bugs — it is the protection or the side effect that silently does not happen.
101101
|:--|:---|:---|:---|:---|
102102
| 1 | **The whole security middleware short-circuits** before any gate runs | plugin-security | Get: every CRUD/FLS/tenant/owner gate below skipped in one branch. Lose: every gate under it in this lane at once, down to and including the write-bypass row that widens the effective write scope to `org` (row 7) — this is the single largest behaviour on the page | `registerAuthzMiddleware` |
103103
| 1b | **App-authored automation's system context is REFUSED governed writes to the identity-assignment objects** — a flow run's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and an action body's; checked ahead of the middleware's short-circuit, beside the append-only refusal (`assertAppAutomationAppendOnlyWriteAllowed`) | plugin-security | Get: nothing — an insert, update, delete, transfer, restore or purge of `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` from a context carrying `isSystem` and either a `flowRunId` (a `runAs: 'system'` flow's data nodes) or the app-automation elevation mark (`@objectstack/core`; set only by a hook's `runAs: 'system'` derivation, by the action body's execution-context builder and `ObjectRepository.execute`, and on the api of a hook bound through the hook binder, whose inherited system context and `sudo()` it marks), at any depth of their writes, is refused `PERMISSION_DENIED` before the short-circuit skips the ADR-0090 D12 gate and the identity write guard. Lose: nothing a platform writer held — a system context with neither (the seeders, better-auth and its reconciliation, invitation placement, platform code's `sudo()`, which never sets the mark, and a hook registered in code) passes on to the short-circuit unchanged, reads are not judged, and a `runAs: 'user'` flow or hook carries no `isSystem`, so the D12 gate judges it as the user it acts for | `elevationSource`, `appAuthoredHookApi` |
104-
| 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware` |
104+
| 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) — except an action body's insert | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability. Except an action body's: an insert from a context carrying `isSystem` and the `'action'` app-automation elevation mark, with no `flowRunId`, has every EMPTY `owner_id` stamped with the envelope's own `userId` ahead of the short-circuit, by the same stamp step 3.5 applies (nothing for the guest; an owner the body sets is kept; an `owner_id` supplied empty beside a supplied queue parks the row). Like a direct create, such an insert is the invoker's own record, so assignment rules (ADR-0142 D5), which route only a row whose owner and queue are both still empty, route neither; a body has no spelling today that asks a rule to route its row. The mark is set on every handler an action door dispatches (a host code action handler included) and by `ObjectRepository.execute`. A flow run, a hook's `runAs: 'system'`, the seeders and every other system context still land the owner they write, or none, and an unowned, queue-less one is still routed | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware`; the action-body exception is `isActionBodyElevation` |
105105
| 3 | Row-level read filter resolves to "no filter" | plugin-security | Get: unscoped reads. Lose: row-level scoping entirely | `getReadFilter` |
106106
| 4 | Field-level security returns **all** fields | plugin-security | Get: every column readable (`getReadableFields`) and writable (`getWritableFields`). Lose: field masking | `resolveProjectionFieldMask` |
107107
| 5 | Export permission granted unconditionally | plugin-security | Get: `canExport` is `true` | `canExport` |
@@ -605,6 +605,7 @@ and CI refuses one that differs from what the tree produces.
605605
| `packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts#onUpdate` | 1 | 23d |
606606
| `packages/plugins/plugin-security/src/grant-permission-set-name.ts#onInsert` | 1 | 23c |
607607
| `packages/plugins/plugin-security/src/grant-permission-set-name.ts#onUpdate` | 1 | 23c |
608+
| `packages/plugins/plugin-security/src/owner-anchor-stamp.ts#isActionBodyElevation` | 1 | 2 |
608609
| `packages/plugins/plugin-security/src/position-catalog-refusal.ts#assertPositionNamesCatalogRow` | 1 | 23b |
609610
| `packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts#registerAuthzMiddleware` | 1 | 1, 2, 30 |
610611
| `packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts#checkControlledByParentWrite` | 1 | 9b |

‎packages/core/src/security/app-automation-elevation.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,12 @@
3737
* It is server-constructed by construction: no request body, query string or
3838
* stored row can spell a symbol, so no caller can claim or shed it. It is an
3939
* in-process provenance fact, never a principal and never an authorization
40-
* grant — its only reader narrows (it refuses; it admits nothing). `Symbol.for`
40+
* grant. It has two readers, both in plugin-security, and neither admits an
41+
* operation. The identity-write and append-only refusals narrow: they refuse.
42+
* The owner stamp (`owner-anchor-stamp.ts`) reads the `'action'` mark to give
43+
* ownership on an insert: an EMPTY `owner_id` is filled with the context's own
44+
* `userId`, the principal a direct create under the same envelope is stamped
45+
* with, and never a different one. `Symbol.for`
4146
* rather than a module-local `Symbol()`, because this package ships an ESM and
4247
* a CJS build and a process may load both: the mark must be the same key in
4348
* each.

0 commit comments

Comments
 (0)