Skip to content

Commit 6e1ab9b

Browse 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>
1 parent 26b5994 commit 6e1ab9b

6 files changed

Lines changed: 507 additions & 8 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/plugin-security': patch
3+
---
4+
5+
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.

‎packages/plugins/plugin-security/src/delegated-organization-membership.test.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -847,13 +847,24 @@ describe('[#25107] every reader in this package that resolves a delegator asks t
847847
const SRC = dirname(fileURLToPath(import.meta.url));
848848
const calls = (text: string, name: string) =>
849849
(text.match(new RegExp(`\\b${name}\\(`, 'g')) ?? []).length - (text.match(new RegExp(`function ${name}\\(`, 'g')) ?? []).length;
850+
// The per-context memo (`SecurityPlugin.resolveDelegatorForContext`) resolves
851+
// in ONE place for the readers that ask it, and asks nothing itself: each of
852+
// its askers asks the check beside its own call, so an ask of the memo counts
853+
// as a resolution in the asker's file, and the memo's one resolution counts
854+
// in none.
855+
const MEMO_FILE = 'security-plugin.ts';
856+
const memoAsks = (text: string) => (text.match(/\bthis\.resolveDelegatorForContext\(context\b/g) ?? []).length;
850857

851858
it('per source file, the asks equal the resolutions — and the seven files that resolve one are all counted', () => {
852859
const counted: Record<string, [number, number]> = {};
853860
for (const file of readdirSync(SRC, { recursive: true }) as string[]) {
854861
if (!file.endsWith('.ts') || file.endsWith('.test.ts') || file.includes('.testkit.')) continue;
855862
const text = readFileSync(join(SRC, file), 'utf8');
856-
const resolutions = calls(text, 'resolveDelegatorContext');
863+
let resolutions = calls(text, 'resolveDelegatorContext') + memoAsks(text);
864+
if (file === MEMO_FILE) {
865+
expect(calls(text, 'resolveDelegatorContext'), 'the memo resolves in exactly one place').toBe(1);
866+
resolutions -= 1;
867+
}
857868
if (resolutions === 0) continue;
858869
counted[file] = [resolutions, calls(text, 'delegatedOrganizationRefusal')];
859870
}

‎packages/plugins/plugin-security/src/security-plugin-field-readers.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@
6767
import type { SecurityPlugin } from './security-plugin.js';
6868
import type { PermissionSet } from '@objectstack/spec/security';
6969
import type { FieldMaskingRule } from '@objectstack/spec/data';
70-
import { delegatedOrganizationRefusal, intersectFieldMasks, resolveDelegatorContext } from './explain-engine.js';
70+
import { delegatedOrganizationRefusal, intersectFieldMasks } from './explain-engine.js';
7171

7272
/**
7373
* The `SecurityPlugin` members the functions below read — every one of them,
@@ -89,6 +89,7 @@ export interface FieldReadersHost {
8989
getObjectFieldNames: SecurityPlugin['getObjectFieldNames'];
9090
getObjectSecurityMeta: SecurityPlugin['getObjectSecurityMeta'];
9191
resolveCallerPosture: SecurityPlugin['resolveCallerPosture'];
92+
resolveDelegatorForContext: SecurityPlugin['resolveDelegatorForContext'];
9293
resolveFallbackPermissionSets: SecurityPlugin['resolveFallbackPermissionSets'];
9394
resolvePermissionSetsForContext: SecurityPlugin['resolvePermissionSetsForContext'];
9495
resolveProjectionFieldMask: SecurityPlugin['resolveProjectionFieldMask'];
@@ -134,7 +135,7 @@ export async function computeReadableFields(
134135

135136
/** The body of `SecurityPlugin#resolveProjectionFieldMask`; the method's docblock there is its contract. */
136137
export async function resolveProjectionFieldMask(
137-
this: Pick<FieldReadersHost, 'computeForbiddenFieldWrites' | 'computeQueryGuardFieldPerms' | 'computeReadPartialMaskRules' | 'foldFieldRequiredPermissions' | 'getObjectFieldNames' | 'metadata' | 'permissionEvaluator' | 'ql' | 'resolveCallerPosture' | 'resolveFallbackPermissionSets' | 'resolvePermissionSetsForContext' | 'tenancyPosture'>,
138+
this: Pick<FieldReadersHost, 'computeForbiddenFieldWrites' | 'computeQueryGuardFieldPerms' | 'computeReadPartialMaskRules' | 'foldFieldRequiredPermissions' | 'getObjectFieldNames' | 'metadata' | 'permissionEvaluator' | 'ql' | 'resolveCallerPosture' | 'resolveDelegatorForContext' | 'resolveFallbackPermissionSets' | 'resolvePermissionSetsForContext' | 'tenancyPosture'>,
138139
object: string,
139140
context: any,
140141
options: { fallbackOnEmptySets: boolean },
@@ -208,7 +209,9 @@ export async function resolveProjectionFieldMask(
208209
let delBasePerms: Record<string, { readable: boolean; editable: boolean }> | null = null;
209210
let delegatorSets: PermissionSet[] | null = null;
210211
if (permissionSets.length > 0 && context?.onBehalfOf?.userId) {
211-
const del = await resolveDelegatorContext(this.ql, context);
212+
// Once per context while no write intervenes (`resolveDelegatorForContext`):
213+
// a schema-serving door asks this of every object it serves.
214+
const del = await this.resolveDelegatorForContext(context);
212215
if (del.kind === 'missing') return { kind: 'answer', fields: [] };
213216
if (del.kind === 'resolved') {
214217
if (delegatedOrganizationRefusal(context, del.context, this.tenancyPosture) !== undefined) {

‎packages/plugins/plugin-security/src/security-plugin-object-admission.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,12 +91,13 @@ export interface ObjectAdmissionHost {
9191
getObjectSecurityMeta: SecurityPlugin['getObjectSecurityMeta'];
9292
objectReadAdmission: SecurityPlugin['objectReadAdmission'];
9393
organizationWallRefusal: SecurityPlugin['organizationWallRefusal'];
94+
resolveDelegatorForContext: SecurityPlugin['resolveDelegatorForContext'];
9495
resolvePermissionSetsForContext: SecurityPlugin['resolvePermissionSetsForContext'];
9596
}
9697

9798
/** The body of `SecurityPlugin#canReadObject`; the method's docblock there is its contract. */
9899
export async function canReadObject(
99-
this: Pick<ObjectAdmissionHost, 'delegatedAdminGate' | 'logger' | 'objectReadAdmission' | 'ql' | 'resolvePermissionSetsForContext' | 'tenancyPosture'>,
100+
this: Pick<ObjectAdmissionHost, 'delegatedAdminGate' | 'logger' | 'objectReadAdmission' | 'ql' | 'resolveDelegatorForContext' | 'resolvePermissionSetsForContext' | 'tenancyPosture'>,
100101
object: string,
101102
context?: any,
102103
): Promise<boolean> {
@@ -121,7 +122,9 @@ export async function canReadObject(
121122
// ({@link delegatedOrganizationRefusal}).
122123
let delegatorSets: PermissionSet[] | null = null;
123124
if (context?.onBehalfOf?.userId) {
124-
const del = await resolveDelegatorContext(this.ql, context);
125+
// Once per context while no write intervenes (`resolveDelegatorForContext`):
126+
// a schema-serving door asks this of every object it serves.
127+
const del = await this.resolveDelegatorForContext(context);
125128
if (del.kind === 'missing') return false;
126129
if (del.kind === 'resolved') {
127130
if (delegatedOrganizationRefusal(context, del.context, this.tenancyPosture) !== undefined) return false;

‎packages/plugins/plugin-security/src/security-plugin.ts‎

Lines changed: 81 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,9 @@ import {
191191
objectReadAdmission,
192192
type ObjectAdmissionHost,
193193
} from './security-plugin-object-admission.js';
194+
// The ADR-0090 D10 delegator resolution the two object-schema read sites ask
195+
// through {@link SecurityPlugin.resolveDelegatorForContext}.
196+
import { resolveDelegatorContext, type DelegatorResolution } from './explain-engine.js';
194197
// [#25223 cut 10] The `everyone` anchor's declarations: the anchor's
195198
// definition a started kernel derives, and the built-in positions `init()`
196199
// declares; the methods of the same names below hand each body the members it
@@ -3343,7 +3346,7 @@ export class SecurityPlugin implements Plugin {
33433346
const readPermissionEvaluator = () => this.permissionEvaluator;
33443347
const readQl = () => this.ql;
33453348
const readTenancyPosture = () => this.tenancyPosture;
3346-
const host: Pick<FieldReadersHost, 'computeForbiddenFieldWrites' | 'computeQueryGuardFieldPerms' | 'computeReadPartialMaskRules' | 'foldFieldRequiredPermissions' | 'getObjectFieldNames' | 'metadata' | 'permissionEvaluator' | 'ql' | 'resolveCallerPosture' | 'resolveFallbackPermissionSets' | 'resolvePermissionSetsForContext' | 'tenancyPosture'> = {
3349+
const host: Pick<FieldReadersHost, 'computeForbiddenFieldWrites' | 'computeQueryGuardFieldPerms' | 'computeReadPartialMaskRules' | 'foldFieldRequiredPermissions' | 'getObjectFieldNames' | 'metadata' | 'permissionEvaluator' | 'ql' | 'resolveCallerPosture' | 'resolveDelegatorForContext' | 'resolveFallbackPermissionSets' | 'resolvePermissionSetsForContext' | 'tenancyPosture'> = {
33473350
computeForbiddenFieldWrites: (...a) => this.computeForbiddenFieldWrites(...a),
33483351
computeQueryGuardFieldPerms: (...a) => this.computeQueryGuardFieldPerms(...a),
33493352
computeReadPartialMaskRules: (...a) => this.computeReadPartialMaskRules(...a),
@@ -3353,6 +3356,7 @@ export class SecurityPlugin implements Plugin {
33533356
get permissionEvaluator() { return readPermissionEvaluator(); },
33543357
get ql() { return readQl(); },
33553358
resolveCallerPosture: (...a) => this.resolveCallerPosture(...a),
3359+
resolveDelegatorForContext: (...a) => this.resolveDelegatorForContext(...a),
33563360
resolveFallbackPermissionSets: (...a) => this.resolveFallbackPermissionSets(...a),
33573361
resolvePermissionSetsForContext: (...a) => this.resolvePermissionSetsForContext(...a),
33583362
get tenancyPosture() { return readTenancyPosture(); },
@@ -3476,11 +3480,12 @@ export class SecurityPlugin implements Plugin {
34763480
const readLogger = () => this.logger;
34773481
const readQl = () => this.ql;
34783482
const readTenancyPosture = () => this.tenancyPosture;
3479-
const host: Pick<ObjectAdmissionHost, 'delegatedAdminGate' | 'logger' | 'objectReadAdmission' | 'ql' | 'resolvePermissionSetsForContext' | 'tenancyPosture'> = {
3483+
const host: Pick<ObjectAdmissionHost, 'delegatedAdminGate' | 'logger' | 'objectReadAdmission' | 'ql' | 'resolveDelegatorForContext' | 'resolvePermissionSetsForContext' | 'tenancyPosture'> = {
34803484
get delegatedAdminGate() { return readDelegatedAdminGate(); },
34813485
get logger() { return readLogger(); },
34823486
objectReadAdmission: (...a) => this.objectReadAdmission(...a),
34833487
get ql() { return readQl(); },
3488+
resolveDelegatorForContext: (...a) => this.resolveDelegatorForContext(...a),
34843489
resolvePermissionSetsForContext: (...a) => this.resolvePermissionSetsForContext(...a),
34853490
get tenancyPosture() { return readTenancyPosture(); },
34863491
};
@@ -3763,6 +3768,80 @@ export class SecurityPlugin implements Plugin {
37633768
return permissionSetMemoKey(context);
37643769
}
37653770

3771+
/**
3772+
* The ADR-0090 D10 delegator resolutions {@link resolveDelegatorForContext}
3773+
* has made, per live execution context — the {@link permissionSetMemo}
3774+
* discipline, for the second question an on-behalf-of read asks.
3775+
*/
3776+
private readonly delegatorMemo = new WeakMap<
3777+
object,
3778+
{ epoch: number; key: string; resolution: Promise<DelegatorResolution> }
3779+
>();
3780+
3781+
/**
3782+
* [ADR-0090 D10] The delegator behind an on-behalf-of `context`
3783+
* ({@link resolveDelegatorContext}), resolved once per context while no
3784+
* write intervenes. Asked by the two object-schema read questions —
3785+
* {@link canReadObject} and the field projection
3786+
* ({@link resolveProjectionFieldMask}) — which a schema-serving door asks
3787+
* once PER OBJECT: `/meta` lists and MCP `list_objects` ask both of every
3788+
* object in the environment.
3789+
*
3790+
* ## The duplicate it removes
3791+
*
3792+
* Each ask re-read the delegator (`sys_user`, memberships, grants,
3793+
* positions) and handed back a context object nobody had seen, so the
3794+
* delegator's sets missed {@link permissionSetMemo} too: one OAuth client's
3795+
* `list_objects` issued 22 statements per object (two questions x 11) for
3796+
* one unchanged answer, measured on a real kernel. Against a database a
3797+
* network hop away that is the listing's whole latency.
3798+
*
3799+
* ## Why it is not a cache
3800+
*
3801+
* Exactly the {@link permissionSetMemo} argument, unchanged: keyed on the
3802+
* context OBJECT, which a door builds once per request (the `/mcp` door,
3803+
* REST's per-`req` memo), so nothing outlives the caller it was resolved
3804+
* for; reused only while {@link epoch} stands, so any write in this process
3805+
* — a grant revoked, a membership removed — retires it; and keyed on the
3806+
* three members the resolution reads off the context (`onBehalfOf.userId`,
3807+
* `tenantId`, `org_user_ids`), so a context edited in place resolves again.
3808+
* Every kind is kept (`none`, `missing`, `resolved`); a rejection is not.
3809+
*
3810+
* One consequence, stated: `resolveDelegatorContext`'s clock is read at the
3811+
* first resolution, so one request judges the delegator's time-limited
3812+
* grants (ADR-0091) at one instant rather than at each object's — which
3813+
* makes one listing coherent, and moves no answer except one whose grant
3814+
* window closes inside the request.
3815+
*
3816+
* The resolved context is FROZEN (shallowly, with its arrays): every asker
3817+
* shares it, and the two sites only read it — the organization check
3818+
* ({@link delegatedOrganizationRefusal}, still asked at each site, every
3819+
* call) and the delegator's sets. ⛔ Not for a site that carries the
3820+
* delegator context onward into a filter or a write (the read filter, the
3821+
* operation prologue, explain): those keep resolving their own.
3822+
*/
3823+
private resolveDelegatorForContext(context: any): Promise<DelegatorResolution> {
3824+
// A primitive/absent context has no identity to key on: resolved, not kept.
3825+
const keyed = !!context && typeof context === 'object';
3826+
const key = keyed
3827+
? JSON.stringify([context.onBehalfOf?.userId ?? null, context.tenantId ?? null, context.org_user_ids ?? null])
3828+
: '';
3829+
const hit = keyed ? this.delegatorMemo.get(context) : undefined;
3830+
if (hit && hit.epoch === this.epoch.current && hit.key === key) return hit.resolution;
3831+
const resolution = resolveDelegatorContext(this.ql, context).then((resolved) => {
3832+
if (resolved.kind !== 'resolved') return Object.freeze(resolved);
3833+
for (const value of Object.values(resolved.context)) if (Array.isArray(value)) Object.freeze(value);
3834+
return Object.freeze({ kind: 'resolved' as const, context: Object.freeze(resolved.context) });
3835+
});
3836+
if (!keyed) return resolution;
3837+
const entry = { epoch: this.epoch.current, key, resolution };
3838+
this.delegatorMemo.set(context, entry);
3839+
resolution.catch(() => {
3840+
if (this.delegatorMemo.get(context) === entry) this.delegatorMemo.delete(context);
3841+
});
3842+
return resolution;
3843+
}
3844+
37663845
/**
37673846
* [#18783] `ISecurityService.getEffectiveObjectPermissions` — the subject's
37683847
* EFFECTIVE object-permission map, object name -> `EffectiveObjectPermission`.

0 commit comments

Comments
 (0)