You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 6e1ab9b
Browse filesBrowse the repository at this point in the historyBrowse files
fix(plugin-security): an OAuth MCP client's list_objects resolves its delegator once per request (#33202)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} -->
_Requested by **Tesla** · [project
thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoSLDKWQ8v7cxY9uDGijfncD)_Fixes#33179
Clause-②: no
Metadata-protocol: none
## 维护者速读
- 改了什么:用 OAuth 登录的 MCP 客户端代表某个人操作时,`list_objects`
现在每个请求只查一次「被代表的人」的权限,不再每个对象查两次。150 个对象的列表从 4620 条 SQL 降到 11
条,`describe_object` 从 22 条降到 11 条。
- 为什么改:每个对象都要重新读一遍这个人的用户行、成员、授权和岗位,对象一多、数据库在远端时,环境 owner 列一次对象要几十秒,接近客户端
60 秒超时。
- 风险与回滚:每个调用者看到的对象、字段数和顺序与 main 逐字节一致(有 golden
钉);复用只在同一个请求上下文内,且任何写入都会立即作废,撤销授权或移除成员在同一请求内也立刻生效。回滚 = revert 本
PR,不涉及数据。
- 先看:`packages/plugins/plugin-security/src/security-plugin.ts` 新增的
`resolveDelegatorForContext`(约 L3776–L3845),以及 object-admission /
field-readers 两处调用点的改动。
- 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run
src/mcp-list-objects-statements.pin.test.ts`,预期 19/19 通过。
- 需要你做的:无,席位落地。
## What changes
- **The cost that grew.** An OAuth MCP client acts on behalf of a person
(ADR-0090 D10: `onBehalfOf`, permissions `mcp_agent_data_read`). For
such a caller, `list_objects` asks the security service two questions
per object, `canReadObject` and `getMetadataReadableFields` (through
`resolveObjectSchemaMaskPosture`). Each one called
`resolveDelegatorContext(ql, context)`, which re-reads the person's
`sys_user` row, memberships, permission-set grants, positions and
activation rows (11 statements), and returns a fresh delegator context,
so the per-context permission-set memo missed every time. That is 22
statements per listed object. Signed-in sessions and API keys carry no
`onBehalfOf` and were already constant; this matches the card's split
(OAuth slow, API key fast).
- **The fix.** `SecurityPlugin.resolveDelegatorForContext(context)`
(private) memoizes `resolveDelegatorContext` per live context object, on
the same discipline as `permissionSetMemo`: a `WeakMap` keyed on the
context, reused only while the write epoch (`this.epoch.current`) and a
key of `onBehalfOf.userId`, `tenantId` and `org_user_ids` stand. All
three resolution kinds (`none`, `missing`, `resolved`) are memoized. A
rejected resolution is dropped, not kept. Because the same resolved
delegator context comes back, the delegator's own permission-set memo
hits too.
- **Wired at the two object-schema read sites only:** `canReadObject`
(`security-plugin-object-admission.ts`) and `computeReadableFields`
(`security-plugin-field-readers.ts`). Both only read `del.context`, and
both still run `delegatedOrganizationRefusal` themselves on every call.
The other call sites (read filter, write admission, export, explain,
operation principals, scope) are untouched, because some of them carry
the delegator context onward.
- **Frozen.** The memoized resolution, its `context` and every array on
it are frozen, so neither site (nor a future one) can mutate a shared
answer.
- **No cache outlives the request.** The memo lives on the context
object, which every door that produces an `onBehalfOf` context builds
fresh per request (checked below). `mcp.ts` is unchanged: the security
API is per object, so a bridge-side memo could not remove these reads.
## Tests
- **New
`packages/runtime/src/mcp-list-objects-statements.pin.test.ts`**, a full
kernel (`ObjectQLPlugin`, sqlite-wasm datasource,
`PlatformObjectsPlugin`, `AuthPlugin`, `SecurityPlugin`,
`SharingServicePlugin`, REST, dispatcher) with the dev admin as owner
and a member signed up by invitation. The OAuth callers are built by
`assembleExecutionContext` with an `oauth` grant, the way `/mcp` builds
them. Statements are counted with knex's `query` event inside an
`AsyncLocalStorage`.
- ⭐ round-trip pin, for owner, member, ownerAgent and memberAgent:
statements per `list_objects` at 150 objects equal those at 10, within
2.
- ⭐ the delegated callers pay their delegator once: a listing costs at
most one `describe_object` on main (22).
- answer-identity golden: the sha256 of each caller's listing at 10 and
150 objects and of `describe_object`, taken from the main-side run, must
match byte for byte.
- CONTROL: `describe_object` answers unchanged for all four callers.
- ⭐ invalidation pin: inside one bridge (one context), the memberAgent
lists, the member's `sys_member` rows are deleted, and the next listing
is strictly narrower and a subset (rows restored in `finally`).
- **Why a new file.** `mcp-object-schema-mask.test.ts`'s rig has no
identity tables, so no delegator can be resolved there.
- **Census pin updated** in `delegated-organization-membership.test.ts`.
It counts the files that resolve a delegator and must also refuse a
foreign organization. It now counts
`this.resolveDelegatorForContext(context` as a resolution, and checks
that the memo resolves in exactly one place. The seven-file list is
unchanged.
## Acceptance notes
- **Time-limited grants.** A request now judges the delegator's
time-limited grants at one instant, its first resolution, instead of at
each object. This makes one listing coherent and changes no answer
outside a sub-second boundary (only a grant whose window closes inside
that request).
- **Ruling #11971** (`buildContextForUser`: "⭐ Ruled bypass of the
#11633 leg-B grants cache", maintainer acceptance 2026-08-25). That
ruling keeps the explainer off the cross-request grants cache. It still
holds. The new memo is per context, epoch-invalidated, and not a grants
cache. `buildContextForUser` keeps `bypassGrantsCache: true`, and the
explain call sites are untouched.
- **Doors that produce `onBehalfOf` (seat condition 1).**
- The runtime `/mcp` door builds it per request
(`resolveExecutionContext` → `assembleExecutionContext` with `oauth`).
- REST forward-agent builds it per `req` (`execCtxMemo`).
- stdio, print, settings, storage, messaging and the other
`assembleExecutionContext` callers pass `oauth: undefined`, so they
produce no delegated context.
- The tool-call interceptor's `toolCallPrincipalOf` is a frozen
projection, not a context the security service is asked with. The
explain engine's `onBehalfOf` (explain-engine.ts) is output only.
- No door keeps one delegated context across requests.
- **Hosted was not reachable.** Every figure below is from a local
in-memory sqlite kernel. The hosted estimate is an inference only: about
22 round trips per object × about 170 objects on a remote database gives
tens of seconds, which matches the 44 s report.
- **Serial.** Open PRs #33194 and #33188 touch
`runtime/src/domains/mcp.ts`, which this PR does not edit. No open PR
touches the three plugin-security files.
- **Ruling grep** (`ruling|Ruling-ref|maintainer|⛔`) on the touched
surface: security-plugin.ts 80 hits (only "ruling 6278784335 letter B"
touches delegation, outside the edited region); object-admission 3;
field-readers 1. None governs this memo besides #11971 above.
## Verification
All readings are at head `04753f4b` (base `68972cd2`; `origin/main`
merged once at `f8b2d950`, with no overlap with the touched files),
unless named otherwise.
<details><summary>Measured at origin/main first, then after (statements
per call, real kernel, in-memory sqlite)</summary>
| caller | objects listed (10 / 150 app objects) | main statements 10 →
150 | main wall 10 → 150 | after statements 10 → 150 | after wall 10 →
150 |
|---|---|---|---|---|---|
| owner (signed in) | 68 / 208 | 0 → 0 | — | 0 → 0 | — |
| member (signed in) | 29 / 29 | 0 → 0 | — | 0 → 0 | — |
| ownerAgent (OAuth, on behalf of owner) | 49 / 189 | 1540 → 4620 | 1057
ms → 2059 ms | 11 → 11 | 31 ms → 40 ms |
| memberAgent (OAuth, on behalf of member) | 23 / 23 | 1260 → 3780 | 642
ms → 1734 ms | 9 → 9 | 28 ms → 44 ms |
`describe_object`: ownerAgent 22 → 11, memberAgent 18 → 9 statements.
The listings and descriptions hash identically before and after:
| caller | 10 objects | 150 objects |
|---|---|---|
| owner | `304fb285…` | `9edb5243…` |
| member | `1c5b772f…` | `1c5b772f…` |
| ownerAgent | `f4e77a4d…` | `d0342442…` |
| memberAgent | `6e73539a…` | `6e73539a…` |
Growth on main is 22 statements per extra listed object for ownerAgent
((4620 − 1540) / 140), which is 2 security calls × 11 statements.
</details>
<details><summary>Ablations (each leg rebuilt through dist, then
restored)</summary>
- **A, memo hook-up removed** (`resolveDelegatorForContext` returns
`resolveDelegatorContext(this.ql, context)` directly): 3 failed | 16
passed.
- ownerAgent: `expected 3080 to be less than or equal to 2`
- memberAgent: `expected 2520 to be less than or equal to 2`
- delegated-once pin: `ownerAgent: expected 4620 to be less than or
equal to 22`
- The golden hashes still matched, so main's answers are the ones this
PR keeps.
- **B, epoch check removed** (a hit no longer compares
`this.epoch.current`): 1 failed | 18 passed.
- invalidation pin: `expected 23 to be less than 23`, so the delegator's
removed membership was not seen inside the request.
- **Restored:** 19 passed (19). `ablation-dist-preflight --absent`
exited 0 and the tree was clean.
</details>
<details><summary>Suites, gates, lint</summary>
- `mcp-list-objects-statements.pin.test.ts` at head: Tests 19 passed
(19).
- `pnpm --filter @objectstack/plugin-security test`: Test Files 267
passed (267), Tests 6605 passed | 45 skipped (6650), exit 0.
- `pnpm --filter @objectstack/runtime test`: Test Files 598 passed
(598), Tests 10620 passed | 19 skipped (10639), exit 0.
- runtime MCP suites (`mcp-object-schema-mask`, the bridge tests): 5
files, 251 tests passed.
- `pnpm --filter @objectstack/plugin-security --filter
@objectstack/runtime typecheck`: exit 0.
- `node scripts/pm/dispatch-gates.mjs --commands`: 70 families derived.
All 70 were run with `</dev/null` and every exit code was recorded.
`--ran` reconciliation: "70 derived famil(ies) accounted for — 70 run, 0
NOT-MEASURED".
- `check-plugin-teardown-shape --self-test` first answered 3 on a
shallow clone. It answered 0 after fetching the commit it reads.
- `check:i18n` and `check:dual-build-cjs-loads` first answered 3 (not
built). They answered 0 after a full build.
- `check:test-source-alias` first answered 1 on a lazy
`@objectstack/metadata` load in the new pin. The load moved to the
module top, and the gate now answers 0.
- `pnpm lint`: exit 0.
</details>
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01L9qibzmMRNkjCwvFhzunNc
---------
Co-authored-by: Claude <noreply@anthropic.com>
fix(plugin-security): an OAuth MCP client's `list_objects` resolves the person it acts for once per request, not once per object
6
+
7
+
Clause-②: no
8
+
Metadata-protocol: none
9
+
10
+
An MCP client signed in with OAuth acts on behalf of a person (ADR-0090 D10). Every object-schema read such a caller makes is the intersection of the client's grants and that person's. `list_objects` asks two questions of every object in the environment: may this caller read the object, and which of its fields. Each question re-read the person's user row, memberships, grants and positions, so one listing cost about 22 database statements per object. Measured on a real kernel, 150 objects took 4620 statements. An environment owner with about 170 objects on a remote database waited tens of seconds, close to a client's 60-second timeout.
11
+
12
+
The security service now resolves that person once per request and reuses the answer for every object, so the same listing costs 11 statements whatever the object count. `describe_object` drops from 22 statements to 11. The answers are byte for byte the same for every caller: the same objects, field counts and order. Signed-in sessions and API keys act for nobody and were not affected.
13
+
14
+
The reuse lasts only as long as the request's context and only until the next write. Revoking a grant or removing a membership retires it at once, inside the same request too. One request now judges the person's time-limited grants at one instant, its first resolution, instead of at each object, so one listing is coherent. No answer moves except one whose grant window closes inside that request.
0 commit comments