diff --git a/.changeset/35526-calldata-relation-disabled-package.md b/.changeset/35526-calldata-relation-disabled-package.md index ee619834954..b4af7af430d 100644 --- a/.changeset/35526-calldata-relation-disabled-package.md +++ b/.changeset/35526-calldata-relation-disabled-package.md @@ -5,7 +5,7 @@ fix(runtime)!: `callData`'s aggregate arm and no-protocol query fallback refuse a relation condition on a disabled package's object, the answer the data route already gives -Clause-②: no (narrowing: for a non-system caller, `callData`'s `aggregate` arm and its `query` fallback on a host with no protocol service refuse a nested-relation condition whose target belongs to a disabled package with 404 `OBJECT_PACKAGE_DISABLED`, where they answered the count or the matching rows) +Clause-②: yes (narrowing: adds the root export `objectPackageDisabledError` to `@objectstack/metadata-protocol`; for a non-system caller, `callData`'s `aggregate` arm and its `query` fallback on a host with no protocol service refuse a nested-relation condition whose target belongs to a disabled package with 404 `OBJECT_PACKAGE_DISABLED`, where they answered the count or the matching rows) Metadata-protocol: none @@ -13,8 +13,8 @@ Metadata-protocol: none **BREAKING** for a non-system caller of `callData` on an environment that disables a package: the `/mcp` HTTP bridge's `aggregate_records` tool, and any host door that hands a caller's `where` to this function. A disable takes the package's records off the data plane: the data route answers its objects `404 OBJECT_PACKAGE_DISABLED`, and it refuses a nested-relation condition (`{ "lookup": { "field": VALUE } }`) on such an object the same way. `callData`'s `aggregate` arm never reaches the protocol, and on a host that registers no protocol service neither does its `query` fallback, so both still lowered the condition through the engine: a count came back 1 for the stored value and 0 for any other, a yes/no answer on a field of an object nobody may read. - FROM: the condition was evaluated and the count (or the matching rows) returned. -- TO: the call is refused `404 OBJECT_PACKAGE_DISABLED`, naming the disabled object as `object` and the condition's position as `param` (for example `where.b_ref`), before the engine reads anything. The error is the data route's own. +- TO: a condition directly beneath a lookup of the queried object is refused `404 OBJECT_PACKAGE_DISABLED`, naming the disabled object as `object` and the condition's position as `param` (for example `where.b_ref`), before the engine reads anything. The error is the data route's own. -The fix: re-enable the package to filter on its records again, or filter on the lookup's stored id. An environment with no disabled package sees no change. A system context (an in-process caller, such as a hook's `ctx.api`) is not changed: it is still answered the count. +The fix: re-enable the package to filter on its records again, or filter on the lookup's stored id. An environment with no disabled package sees no change. A system context handed to `callData` is not changed by this entry: it is still answered the count. (A hook's `ctx.api` is not such a caller: it reaches the engine directly and never passes through `callData`.) `@objectstack/metadata-protocol` now exports `objectPackageDisabledError`, the one constructor of that refusal, so the runtime raises the same error instead of a copy. No behaviour of that package changes. diff --git a/.changeset/36393-calldata-disabled-package-every-hop.md b/.changeset/36393-calldata-disabled-package-every-hop.md new file mode 100644 index 00000000000..4790657ab60 --- /dev/null +++ b/.changeset/36393-calldata-disabled-package-every-hop.md @@ -0,0 +1,18 @@ +--- +'@objectstack/runtime': patch +'@objectstack/mcp': patch +--- + +fix(runtime)!: `callData` refuses a disabled package's data at every relation hop and for a system context too; the MCP stdio bridge asks every hop + +Clause-②: yes (narrowing: `callData` newly refuses 404 `OBJECT_PACKAGE_DISABLED` for a nested-relation condition into a disabled package's object at any hop, not only directly beneath the queried object's lookup, for every caller including a system context, and refuses a disabled package's addressed object for a system context and on a host with no protocol service; a non-system caller is also refused 404 `OBJECT_API_DISABLED` / 405 `OBJECT_API_METHOD_NOT_ALLOWED` for an unexposed target past the first hop, on `callData` and on the MCP stdio bridge; no export is added or removed) +Metadata-protocol: none + + + +**BREAKING** for callers of `callData` on an environment that disables a package or declares an object unexposed, and for the MCP stdio bridge. The engine lowers a condition beneath a condition (`{ "c_ref": { "b_ref": { "field": VALUE } } }`) up to three relationships, reading each related object, so the refusal that stopped at the first hop still answered a count of 1 for a stored value and 0 for any other one relationship further. The protocol's data route refuses every hop and every caller. + +- FROM: `callData`'s `aggregate` arm and its no-protocol `query` fallback asked only the first hop of a relation condition, and skipped the disabled-package question for a system context; on a host with no protocol service, a disabled package's object addressed directly was served to every caller, and so was any disabled package's object addressed by a system context on the `aggregate` arm. The MCP stdio bridge asked the exposure question of the first hop only. +- TO: every target on the way is asked, disabled package first and then exposure, and refused with its full position as `param` (for example `where.c_ref.b_ref`). The disabled-package question is asked of every caller, a system context included, for the addressed object and for every relation target; the exposure question still skips a system context. The MCP stdio bridge asks both questions at every hop of a non-system caller's condition. + +Who changes: a host that hands `callData` a system context (`HttpDispatcher.handleMcp` / `buildMcpBridge`, `dispatchAction`) now gets the data route's refusal for a disabled package's data; no door in this repository hands `callData` a system context, and a hook's `ctx.api` never passes through it. The fix for a caller that needs the records: re-enable the package, expose the object, or filter on the lookup's stored id. An environment with no disabled package and no unexposed object sees no change. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 5226887b793..f117cca6421 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -202,7 +202,7 @@ One of the largest consumers of the flag; | # | Behaviour when `isSystem` | Package | What you get / what you lose | Symbol | |:--|:---|:---|:---|:---| -| 48 | Object API-exposure gate bypassed (`apiEnabled` / `apiMethods`) | runtime | Get: internal self-writes ignore exposure declarations — these govern **external** exposure, not engine self-writes. The gate is `refuseUnexposedDataAction`, which `callData` asks first and the `/data` domain asks before its request gate; `callData` reads the same bypass once more for each nested-relation condition's target | `callData`, `refuseUnexposedDataAction` | +| 48 | Object API-exposure gate bypassed (`apiEnabled` / `apiMethods`) | runtime | Get: internal self-writes ignore exposure declarations — these govern **external** exposure, not engine self-writes. The gate is `refuseUnexposedDataAction`, which `callData` asks first and the `/data` domain asks before its request gate; `callData` reads the same bypass once more for each nested-relation condition's target. The bypass covers exposure only: a disabled package's object is refused `404 OBJECT_PACKAGE_DISABLED` to a system context too, addressed or as a relation target at any hop | `callData`, `refuseUnexposedDataAction` | | 49 | Action `requiredPermissions` bypassed, and an action call's selection is not read first | runtime | Get: engine self-invocation runs any action, and a call's `params._selectedIds` is handed on without the caller-scope read every other caller's selection gets (the system principal reads every row anyway) | `actionPermissionError`, `actionSelectionIsRead` | | 50 | `manage_metadata` bypassed on metadata writes | runtime, rest | Get: schema writes without the capability (the permission-set clone door's save included) — and, because REST's save door and the stored-version read doors ask one save verdict, an app's full stored version on `/layers`, `?layers=true` and `/diff`, whatever its entry gates withhold | `handleMetadataRequest`, `registerMetaCollectionRoutes`, `registerMetaItemWriteRoutes`, `registerMetaItemHistoryRoutes`, `metaSaveVerdict`, `handlePermissionSetCloneWrite` | | 50b | `setup.write` bypassed on the record-currency code backfill door | rest | Get: `POST /meta/_migrate-record-currency-codes` without the capability. The door still fills only the caller's current organization's rows: a system context with no organization is refused like any other caller | `registerMetaRecordCurrencyBackfillRoute` | diff --git a/packages/mcp/src/stdio-data-bridge.relation-condition-target-exposure.test.ts b/packages/mcp/src/stdio-data-bridge.relation-condition-target-exposure.test.ts index 4d93112f158..f2c9d0ce046 100644 --- a/packages/mcp/src/stdio-data-bridge.relation-condition-target-exposure.test.ts +++ b/packages/mcp/src/stdio-data-bridge.relation-condition-target-exposure.test.ts @@ -141,3 +141,106 @@ describe('[#22777] the stdio bridge refuses a condition on a target the decision } }); }); + +/** + * [#36393] Every hop the engine serves, not the first one only: the engine + * lowers a condition beneath a condition up to three relationships, reading + * each related object, so the bridge asks every target on the way, disabled + * package first, at its full position. `rcx_hop_source.mid → rcx_hop_mid`, + * whose lookups reach `rcx_hidden` (not exposed), `rcx_open` and + * `rcx_hop_locked` (a disabled package's object that also declares + * `apiEnabled: false`: the order pin). The protocol's by-name read refuses a + * disabled package's object, as the shipped protocol does. + */ +describe('[#36393] the stdio bridge asks every hop of a nested-relation condition', () => { + const HOP_DEFS: Record = { + ...DEFS, + rcx_hop_source: { name: 'rcx_hop_source', fields: { name: { type: 'text' }, mid: lookup('rcx_hop_mid') } }, + rcx_hop_mid: { + name: 'rcx_hop_mid', + fields: { name: { type: 'text' }, hidden: lookup('rcx_hidden'), open: lookup('rcx_open'), locked: lookup('rcx_hop_locked') }, + }, + rcx_hop_locked: { name: 'rcx_hop_locked', fields: { name: { type: 'text' } }, enable: { apiEnabled: false } }, + }; + + function makeHopBridge(opts: { disabled: ReadonlySet; isSystem?: boolean }) { + const engine = { + find: vi.fn(async (_object: string, _query?: { where?: unknown }) => [{ id: 's1' }]), + aggregate: vi.fn(async (_object: string, _query?: { where?: unknown }) => [{ n: 1 }]), + }; + const byName = async ({ name }: { type: string; name: string }) => { + if (opts.disabled.has(name)) { + throw Object.assign(new Error(`Object '${name}' belongs to a disabled package`), { code: 'OBJECT_PACKAGE_DISABLED', status: 404, object: name }); + } + return { item: HOP_DEFS[name] }; + }; + const bridge = createStdioDataBridge({ + engine: engine as unknown as IDataEngine, + metadataService: { getObject: vi.fn(async (name: string) => HOP_DEFS[name]) } as unknown as IMetadataService, + protocol: () => ({ getMetaItem: byName }), + resolvePrincipal: async () => ({ userId: 'u1', isSystem: opts.isSystem === true }) as unknown as ExecutionContext, + }); + return { bridge, engine }; + } + + const HOP_VERBS = { + query: (b: ReturnType['bridge'], where: Record) => b.query('rcx_hop_source', { where }), + aggregate: (b: ReturnType['bridge'], where: Record) => + b.aggregate!('rcx_hop_source', { where, aggregations: [{ function: 'count', alias: 'n' }] }), + }; + const refusal = async (run: () => Promise) => { + const err = (await run().then(() => null, (e: unknown) => e)) as (McpExposureError & { object?: string }) | null; + expect(err, 'the call resolved: no refusal was raised').toBeTruthy(); + return err!; + }; + + for (const [verb, run] of Object.entries(HOP_VERBS)) { + for (const [shape, where] of [ + ['direct', { mid: { hidden: { name: 'x' } } }], + ['under $or', { $or: [{ mid: { hidden: { name: 'x' } } }, { name: 'y' }] }], + ['under $not', { $not: { mid: { hidden: { name: 'x' } } } }], + ] as const) { + it(`${verb}: a two-hop condition (${shape}) on a target that is not exposed answers 404 at its full position and never reaches the engine`, async () => { + const { bridge, engine } = makeHopBridge({ disabled: new Set() }); + const err = await refusal(() => run(bridge, where)); + expect({ code: err.code, status: err.status }).toEqual({ code: 'OBJECT_API_DISABLED', status: 404 }); + expect(err.message).toContain("'rcx_hidden'"); + expect(err.message).toContain("'where.mid.hidden'"); + expect(engine.find).not.toHaveBeenCalled(); + expect(engine.aggregate).not.toHaveBeenCalled(); + }); + } + + it(`${verb}: a two-hop condition into a disabled package's object answers 404 OBJECT_PACKAGE_DISABLED, the stored value or any other`, async () => { + for (const value of ['secret', 'NOPE']) { + const { bridge, engine } = makeHopBridge({ disabled: new Set(['rcx_open']) }); + const err = await refusal(() => run(bridge, { mid: { open: { name: value } } })); + expect({ code: err.code, status: err.status, object: err.object }).toEqual({ code: 'OBJECT_PACKAGE_DISABLED', status: 404, object: 'rcx_open' }); + expect(engine.find).not.toHaveBeenCalled(); + expect(engine.aggregate).not.toHaveBeenCalled(); + } + }); + + it(`${verb}: ORDER a two-hop target both disabled and not exposed answers the package refusal first, the exposure refusal once enabled`, async () => { + const disabled = await refusal(() => run(makeHopBridge({ disabled: new Set(['rcx_hop_locked']) }).bridge, { mid: { locked: { name: 'x' } } })); + expect({ code: disabled.code, status: disabled.status }).toEqual({ code: 'OBJECT_PACKAGE_DISABLED', status: 404 }); + const enabled = await refusal(() => run(makeHopBridge({ disabled: new Set() }).bridge, { mid: { locked: { name: 'x' } } })); + expect({ code: enabled.code, status: enabled.status }).toEqual({ code: 'OBJECT_API_DISABLED', status: 404 }); + expect(enabled.message).toContain("'where.mid.locked'"); + }); + + it(`${verb}: CONTROL a two-hop condition on a served target reaches the engine unchanged`, async () => { + const { bridge, engine } = makeHopBridge({ disabled: new Set() }); + const where = { mid: { open: { name: 'x' } } }; + await run(bridge, where); + const call = (verb === 'query' ? engine.find : engine.aggregate).mock.calls[0]?.[1]; + expect(call?.where).toBe(where); + }); + + it(`${verb}: CONTROL a system context is not asked the exposure question at any hop (this transport's bypass, unchanged)`, async () => { + const { bridge, engine } = makeHopBridge({ disabled: new Set(), isSystem: true }); + await run(bridge, { mid: { hidden: { name: 'x' } } }); + expect((verb === 'query' ? engine.find : engine.aggregate)).toHaveBeenCalledTimes(1); + }); + } +}); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index bd2c6d16c6d..71e9fcbaaf8 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -916,16 +916,28 @@ export async function enforceApiExposure( * performs — and an unserved target REFUSES the call: dropping the condition * would widen the result. The data door asks the same of the same sites * (`refuseUnservedRelationTarget`), found by the one walk both doors import - * (`relationConditionSites`). One hop, as the engine serves one: a relation - * beneath a condition is refused by the engine before anything is read. + * (`relationConditionSites`). + * + * [#36393] EVERY HOP the engine serves, not the first one only: the engine + * lowers a condition beneath a condition (`{ c_ref: { b_ref: { … } } }`) up to + * `RELATION_CONDITION_MAX_HOPS` relationships (`@objectstack/objectql`), + * reading each related object in turn. So each site's own condition is walked + * against its target's field map, and every target on the way is asked the + * whole of {@link enforceApiExposure} (disabled package first, then exposure) + * at its full position (`where.c_ref.b_ref`), the order the data door's walk + * asks in. A system context is asked nothing at any hop: {@link enforceApiExposure} + * owns that bypass, and this walk only reaches it. `depth` is a backstop against a self-referential + * in-process `where`, never the hop limit. */ async function enforceRelationTargetExposure( reads: StdioObjectReads, object: string, where: unknown, context: ExecutionContext, + prefix = 'where', + depth = 0, ): Promise { - if (where == null) return; + if (where == null || depth > RELATION_CONDITION_WALK_DEPTH) return; let def: ObjectDef | null | undefined; try { // [#25138] The field map from the definition the gate judged, so a @@ -935,10 +947,15 @@ async function enforceRelationTargetExposure( def = undefined; // no field map, no site: the gate above falls open the same way } for (const site of relationConditionSites(def?.fields, where)) { - await enforceApiExposure(reads, site.target, GATED_ACTIONS.query, context, `where.${site.field}`); + const position = `${prefix}.${site.field}`; + await enforceApiExposure(reads, site.target, GATED_ACTIONS.query, context, position); + await enforceRelationTargetExposure(reads, site.target, site.condition, context, position, depth + 1); } } +/** [#36393] The relation walk's backstop depth, the data door's and the engine evaluate gate's. */ +const RELATION_CONDITION_WALK_DEPTH = 8; + // --------------------------------------------------------------------------- // [#21207] The stored-metadata-body family, at this engine-only reader // --------------------------------------------------------------------------- diff --git a/packages/runtime/src/action-execution-calldata-relation-disabled-package-35526.test.ts b/packages/runtime/src/action-execution-calldata-relation-disabled-package-35526.test.ts index 039611ab4d7..60392483dbc 100644 --- a/packages/runtime/src/action-execution-calldata-relation-disabled-package-35526.test.ts +++ b/packages/runtime/src/action-execution-calldata-relation-disabled-package-35526.test.ts @@ -29,15 +29,26 @@ * value nothing holds (the same answer both ways: no oracle), with and * without a protocol service; * - the query fallback on a host with no protocol refuses it the same way; - * - CONTROLS: the package re-enabled answers the count 1 / 0 again, and a - * condition into an enabled package's object is served while `dp_beta`'s - * package is disabled. + * - CONTROLS: the package disabled and then re-enabled answers the count + * 1 / 0 again, and a condition into an enabled package's object is served + * while `dp_beta`'s package is disabled. * - * For a SYSTEM caller this file pins TODAY's answer (the count) and does not - * judge it: whether a system context is refused too is an open point the - * maintainer decides (an in-process caller — a hook's `ctx.api` — is a system - * context, and in-process access is ruled served). The pin is there so a - * change to that answer is a decision someone made, not a side effect. + * [#36393] And, at EVERY hop the engine serves (`dp_gamma.b2_ref → dp_beta`, + * `dp_gamma.d_ref → dp_delta`, so `{ c_ref: { b2_ref: … } }` is two hops): + * + * - a two-hop condition into the disabled package is refused at its full + * position (`where.c_ref.b2_ref`), directly and under `$or` / `$not`; + * - a two-hop condition into an object that is not exposed is refused + * `404 OBJECT_API_DISABLED` for a member; + * - ORDER: a target that is both (`dp_delta`: `apiEnabled: false`, package + * `dp36393_d` disabled) answers the package refusal first, and the + * exposure refusal once the package is re-enabled; + * - SYSTEM (the #35526 ruling, 「系统身份也一律拒绝」): a system context is + * refused the disabled package like a member, one hop and two, while its + * exposure question stays unasked (an unexposed target is served to it); + * - the ADDRESSED object of a disabled package is refused on every arm for + * both callers, a host with no protocol service included (it used to + * serve it there, the refusal living only in the protocol's by-name read). */ import { afterEach, describe, expect, it } from 'vitest'; @@ -59,6 +70,7 @@ const SYSTEM = { isSystem: true } as any; const PKG_A = 'dp35526_a'; const PKG_B = 'dp35526_b'; const PKG_C = 'dp35526_c'; +const PKG_D = 'dp36393_d'; const SECRET = 'BETA_SECRET'; const text = (name: string) => ({ name, label: name, type: 'text' }); @@ -66,7 +78,9 @@ const lookup = (name: string, reference: string) => ({ name, label: name, type: const ALPHA = { name: 'dp_alpha', label: 'Alpha', fields: { name: text('name'), b_ref: lookup('b_ref', 'dp_beta'), c_ref: lookup('c_ref', 'dp_gamma') } }; const BETA = { name: 'dp_beta', label: 'Beta', fields: { name: text('name'), secret_note: text('secret_note') } }; -const GAMMA = { name: 'dp_gamma', label: 'Gamma', fields: { name: text('name'), note: text('note') } }; +const GAMMA = { name: 'dp_gamma', label: 'Gamma', fields: { name: text('name'), note: text('note'), b2_ref: lookup('b2_ref', 'dp_beta'), d_ref: lookup('d_ref', 'dp_delta') } }; +// [#36393] Not exposed (`apiEnabled: false`), in a package of its own: the exposure and the order pins. +const DELTA = { name: 'dp_delta', label: 'Delta', fields: { name: text('name') }, enable: { apiEnabled: false } }; const manifest = (id: string) => ({ id, name: id, version: '1.0.0', type: 'app' } as any); @@ -82,14 +96,16 @@ async function makeHarness(opts: { withProtocol: boolean }) { live.push(engine); engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as any, true); await engine.init(); - for (const id of [PKG_A, PKG_B, PKG_C]) engine.registry.installPackage(manifest(id), 'code'); + for (const id of [PKG_A, PKG_B, PKG_C, PKG_D]) engine.registry.installPackage(manifest(id), 'code'); engine.registry.registerObject(ALPHA as any, PKG_A, undefined, 'own'); engine.registry.registerObject(BETA as any, PKG_B, undefined, 'own'); engine.registry.registerObject(GAMMA as any, PKG_C, undefined, 'own'); + engine.registry.registerObject(DELTA as any, PKG_D, undefined, 'own'); await engine.syncSchemas(); await installDefaultOrganization(engine); const beta: any = await engine.insert('dp_beta', { name: 'beta', secret_note: SECRET }); - const gamma: any = await engine.insert('dp_gamma', { name: 'gamma', note: 'open' }); + const delta: any = await engine.insert('dp_delta', { name: 'delta' }); + const gamma: any = await engine.insert('dp_gamma', { name: 'gamma', note: 'open', b2_ref: beta.id, d_ref: delta.id }); await engine.insert('dp_alpha', { name: 'alpha', b_ref: beta.id, c_ref: gamma.id }); const services: Record = { metadata: { getObject: async () => undefined }, @@ -147,13 +163,21 @@ for (const withProtocol of [true, false]) { expect(await aggregateCount(h.deps, { c_ref: { note: 'NOPE' } }, MEMBER)).toBe(0); }); - // OPEN POINT, not a verdict: a system context is not asked (the - // exposure gate's own system bypass), so today it is answered the - // count. Whether the package check skips system contexts too is the - // maintainer's to decide; this pin moves only with that decision. - it('SYSTEM (today\'s answer, pinned pending the open point): the count is served', async () => { + // [#36393] The #35526 ruling (「系统身份也一律拒绝」): this pin answered + // the count until it; a system context is refused like a member. + it('SYSTEM: the condition into the disabled package is refused 404 like a member\'s, for the stored value and for any other', async () => { + const h = await makeHarness({ withProtocol }); + h.engine.registry.disablePackage(PKG_B); + for (const value of [SECRET, 'NOPE']) { + const err = await refusalOf(() => aggregateCount(h.deps, { b_ref: { secret_note: value } }, SYSTEM)); + expect(envelope(err)).toEqual(REFUSED); + } + }); + + it('SYSTEM CONTROL: the package re-enabled answers a system context the count again', async () => { const h = await makeHarness({ withProtocol }); h.engine.registry.disablePackage(PKG_B); + h.engine.registry.enablePackage(PKG_B); expect(await aggregateCount(h.deps, { b_ref: { secret_note: SECRET } }, SYSTEM)).toBe(1); expect(await aggregateCount(h.deps, { b_ref: { secret_note: 'NOPE' } }, SYSTEM)).toBe(0); }); @@ -175,6 +199,8 @@ describe('[#35526] callData\'s query fallback — a host that registers no proto it('CONTROL: the package re-enabled returns the matching record again', async () => { const h = await makeHarness({ withProtocol: false }); + h.engine.registry.disablePackage(PKG_B); + h.engine.registry.enablePackage(PKG_B); const res: any = await query(h.deps, { b_ref: { secret_note: SECRET } }, MEMBER); expect(res.records.map((r: any) => r.name)).toEqual(['alpha']); }); @@ -195,3 +221,123 @@ describe('[#35526] the query arm through the protocol (the data route\'s own ans expect({ code: err.code, status: err.status, object: err.object }).toEqual({ code: 'OBJECT_PACKAGE_DISABLED', status: 404, object: 'dp_beta' }); }); }); + +// ── [#36393] every hop, the system caller, the addressed object ───────────── + +const TWO_HOPS = (value: string) => ({ c_ref: { b2_ref: { secret_note: value } } }); +const REFUSED_TWO_HOPS = { code: 'OBJECT_PACKAGE_DISABLED', status: 404, object: 'dp_beta', param: 'where.c_ref.b2_ref' }; + +for (const withProtocol of [true, false]) { + const host = withProtocol ? 'a host with a protocol service' : 'a host that registers no protocol service'; + + describe(`[#36393] callData's aggregate arm, two hops — ${host}`, () => { + for (const [who, context] of [['a member', MEMBER], ['a system context', SYSTEM]] as const) { + it(`THE PIN: ${who}'s two-hop condition into the disabled package is refused 404 at its full position, for the stored value and for any other`, async () => { + const h = await makeHarness({ withProtocol }); + h.engine.registry.disablePackage(PKG_B); + for (const value of [SECRET, 'NOPE']) { + const err = await refusalOf(() => aggregateCount(h.deps, TWO_HOPS(value), context)); + expect(envelope(err)).toEqual(REFUSED_TWO_HOPS); + } + }); + + it(`CONTROL: ${who}, the package disabled and then re-enabled, is answered the two-hop count (1 for the stored value, 0 otherwise)`, async () => { + const h = await makeHarness({ withProtocol }); + h.engine.registry.disablePackage(PKG_B); + h.engine.registry.enablePackage(PKG_B); + expect(await aggregateCount(h.deps, TWO_HOPS(SECRET), context)).toBe(1); + expect(await aggregateCount(h.deps, TWO_HOPS('NOPE'), context)).toBe(0); + }); + } + + for (const [shape, where] of [ + ['under $or', { $or: [TWO_HOPS(SECRET), { name: 'nobody' }] }], + ['under $not', { $not: TWO_HOPS(SECRET) }], + ] as const) { + it(`a member's two-hop condition ${shape} is refused the same way`, async () => { + const h = await makeHarness({ withProtocol }); + h.engine.registry.disablePackage(PKG_B); + const err = await refusalOf(() => aggregateCount(h.deps, where, MEMBER)); + expect(envelope(err)).toEqual(REFUSED_TWO_HOPS); + }); + } + + it('a member\'s two-hop condition into an object that is not exposed is refused 404 OBJECT_API_DISABLED; a system context is served (its exposure question is unchanged)', async () => { + const h = await makeHarness({ withProtocol }); + const err = await refusalOf(() => aggregateCount(h.deps, { c_ref: { d_ref: { name: 'delta' } } }, MEMBER)); + expect(envelope(err)).toEqual({ code: 'OBJECT_API_DISABLED', status: 404, object: 'dp_delta', param: 'where.c_ref.d_ref' }); + expect(await aggregateCount(h.deps, { c_ref: { d_ref: { name: 'delta' } } }, SYSTEM)).toBe(1); + }); + + it('ORDER: a target both disabled and not exposed answers the package refusal first, and the exposure refusal once re-enabled', async () => { + const h = await makeHarness({ withProtocol }); + h.engine.registry.disablePackage(PKG_D); + const first = await refusalOf(() => aggregateCount(h.deps, { c_ref: { d_ref: { name: 'delta' } } }, MEMBER)); + expect(envelope(first)).toEqual({ code: 'OBJECT_PACKAGE_DISABLED', status: 404, object: 'dp_delta', param: 'where.c_ref.d_ref' }); + h.engine.registry.enablePackage(PKG_D); + const then = await refusalOf(() => aggregateCount(h.deps, { c_ref: { d_ref: { name: 'delta' } } }, MEMBER)); + expect(envelope(then)).toEqual({ code: 'OBJECT_API_DISABLED', status: 404, object: 'dp_delta', param: 'where.c_ref.d_ref' }); + }); + }); + + describe(`[#36393] callData on the ADDRESSED object of a disabled package — ${host}`, () => { + const arms = { + aggregate: (deps: ActionExecutionDeps, context: unknown) => + callData(deps, REQ, 'aggregate', { object: 'dp_beta', aggregations: COUNT }, undefined, undefined, context as any), + query: (deps: ActionExecutionDeps, context: unknown) => + callData(deps, REQ, 'query', { object: 'dp_beta', query: {} }, undefined, undefined, context as any), + }; + for (const [arm, run] of Object.entries(arms)) { + for (const [who, context] of [['a member', MEMBER], ['a system context', SYSTEM]] as const) { + it(`${arm}: ${who} is refused 404 OBJECT_PACKAGE_DISABLED; CONTROL re-enabled, it is served`, async () => { + const h = await makeHarness({ withProtocol }); + h.engine.registry.disablePackage(PKG_B); + const err = await refusalOf(() => run(h.deps, context)); + expect({ code: err.code, status: err.status, object: err.object }).toEqual({ code: 'OBJECT_PACKAGE_DISABLED', status: 404, object: 'dp_beta' }); + h.engine.registry.enablePackage(PKG_B); + const served: any = await run(h.deps, context); + if (arm === 'aggregate') expect(Number(served.rows?.[0]?.n)).toBe(1); + else expect(served.records.map((r: any) => r.name)).toEqual(['beta']); + }); + } + } + + it('ORDER: an addressed object both disabled and not exposed answers the package refusal to a member', async () => { + const h = await makeHarness({ withProtocol }); + h.engine.registry.disablePackage(PKG_D); + const err = await refusalOf(() => callData(h.deps, REQ, 'aggregate', { object: 'dp_delta', aggregations: COUNT }, undefined, undefined, MEMBER)); + expect({ code: err.code, status: err.status, object: err.object }).toEqual({ code: 'OBJECT_PACKAGE_DISABLED', status: 404, object: 'dp_delta' }); + }); + }); +} + +describe('[#36393] callData\'s query fallback, two hops — a host that registers no protocol service', () => { + const query = (deps: ActionExecutionDeps, where: unknown, context: unknown) => + callData(deps, REQ, 'query', { object: 'dp_alpha', query: { where } }, undefined, undefined, context as any); + + for (const [who, context] of [['a member', MEMBER], ['a system context', SYSTEM]] as const) { + it(`THE PIN: ${who}'s two-hop condition into the disabled package is refused 404, for the stored value and for any other`, async () => { + const h = await makeHarness({ withProtocol: false }); + h.engine.registry.disablePackage(PKG_B); + for (const value of [SECRET, 'NOPE']) { + const err = await refusalOf(() => query(h.deps, TWO_HOPS(value), context)); + expect(envelope(err)).toEqual(REFUSED_TWO_HOPS); + } + }); + + it(`${who}'s one-hop condition into the disabled package is refused 404`, async () => { + const h = await makeHarness({ withProtocol: false }); + h.engine.registry.disablePackage(PKG_B); + const err = await refusalOf(() => query(h.deps, { b_ref: { secret_note: SECRET } }, context)); + expect(envelope(err)).toEqual(REFUSED); + }); + + it(`CONTROL: ${who}, the package disabled and then re-enabled, gets the matching record through two hops`, async () => { + const h = await makeHarness({ withProtocol: false }); + h.engine.registry.disablePackage(PKG_B); + h.engine.registry.enablePackage(PKG_B); + const res: any = await query(h.deps, TWO_HOPS(SECRET), context); + expect(res.records.map((r: any) => r.name)).toEqual(['alpha']); + }); + } +}); diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 6986908f587..626bc59a191 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -355,14 +355,28 @@ const RELATION_CONDITION_TARGET_OPERATION = DATA_ACTION_TO_API_OPERATION[RELATIO * copy of either. A registry that cannot answer disables nothing, as on the * data route. * - * `callData` skips it for a system context on the one decision that skips the - * addressed gate: these flags govern API exposure, not the engine's own reads. A schema - * that cannot be resolved finds no condition (the filtered object) or serves - * (a target), the gate's own fail-open. [#35526] OPEN POINT: the package - * check rides that same bypass, so a system context is still answered the - * count on a disabled package's target. Whether a system context is refused - * too is the maintainer's decision (in-process access is ruled served, and a - * hook's `ctx.api` is a system context); until it is made, the bypass stays. + * [#36393] EVERY HOP the engine serves, not the first one only. The engine + * lowers a condition beneath a condition (`{ c_ref: { b_ref: { … } } }`) up + * to `RELATION_CONDITION_MAX_HOPS` relationships (`@objectstack/objectql`), + * reading each related object in turn, so each site's own condition is + * walked against its target's field map and every target on the way is asked + * both questions, disabled package first, at its full position + * (`where.c_ref.b_ref`). The protocol's twin walk for an engine without an + * evaluate gate (`refuseUnservedRelationTargetsIn`) descends the same way, in + * the same order. A site the engine would refuse for depth is still asked: + * a refusal for a hop it would not serve costs nothing it served. + * + * WHO is asked what: the disabled-package question is asked for EVERY caller, + * a system context included (#35526 ruling, 「系统身份也一律拒绝」: the protocol's + * data plane refuses every caller, and `ctx.api` never passes `callData`). + * The exposure question is skipped for a system context (`exposureGated` + * false), on the one decision that skips the addressed gate: these flags + * govern API exposure, not the engine's own reads. The package predicate is + * the one {@link callData} read from the engine for the addressed object + * ({@link packageDisabledPredicate}), so the arm's own engine (a raw driver + * on the MCP multi-env query fallback, which carries no registry) never + * decides it. A schema that cannot be resolved finds no condition (the + * filtered object) or serves (a target), the gate's own fail-open. */ async function refuseUnservedRelationTargets( deps: ActionExecutionDeps, @@ -370,20 +384,60 @@ async function refuseUnservedRelationTargets( engine: unknown, object: string, where: unknown, - scopeId?: string, + scopeId: string | undefined, + asked: { isObjectPackageDisabled: (objectName: string) => boolean; exposureGated: boolean }, ): Promise { + const walk = async (schema: unknown, condition: unknown, prefix: string, depth: number): Promise => { + if (condition == null || typeof condition !== 'object' || depth > RELATION_CONDITION_WALK_DEPTH) return; + const fields = (schema as { fields?: Record } | undefined)?.fields; + for (const site of relationConditionSites(fields, condition)) { + const param = `${prefix}.${site.field}`; + if (asked.isObjectPackageDisabled(site.target)) { + throw Object.assign(objectPackageDisabledError(site.target), { param }); + } + const target = await resolveWriteResponseSchema(deps, requestContext, engine, site.target, scopeId); + if (asked.exposureGated) { + const gate = checkApiExposure(target as ObjectApiDef | undefined, RELATION_CONDITION_TARGET_ACTION); + if (!gate.allowed) throw unservedRelationTargetError(site.target, param, gate); + } + await walk(target, site.condition, param, depth + 1); + } + }; if (where == null || typeof where !== 'object') return; - const schema = await resolveWriteResponseSchema(deps, requestContext, engine, object, scopeId); - const fields = (schema as { fields?: Record } | undefined)?.fields; - const isObjectPackageDisabled = registryObjectPackageDisabled((engine as { registry?: unknown } | null | undefined)?.registry); - for (const site of relationConditionSites(fields, where)) { - if (isObjectPackageDisabled(site.target)) { - throw Object.assign(objectPackageDisabledError(site.target), { param: `where.${site.field}` }); + await walk(await resolveWriteResponseSchema(deps, requestContext, engine, object, scopeId), where, 'where', 0); +} + +/** + * [#36393] A backstop against a self-referential in-process `where`, never the + * hop limit: the engine's own `RELATION_CONDITION_MAX_HOPS` decides what it + * lowers, and this walk asks at least every hop it serves. The protocol's twin + * walk and the engine's evaluate gate stop at the same depth. + */ +const RELATION_CONDITION_WALK_DEPTH = 8; + +/** + * [#36393] The engine registry's `isObjectPackageDisabled`, read once per + * {@link callData} call through {@link registryObjectPackageDisabled}, the one + * reading the data plane asks before it refuses an object `404 + * OBJECT_PACKAGE_DISABLED`. The engine is the one this door aggregates on + * (`getObjectQL`, then the `objectql` slot), never the raw driver an MCP + * multi-env caller threads through. An engine that cannot be resolved, or a + * registry without the member, disables nothing, as on the data route. + */ +async function packageDisabledPredicate( + deps: ActionExecutionDeps, + requestContext: HttpProtocolContext, + scopeId?: string, +): Promise<(objectName: string) => boolean> { + let engine = await resolveEngineQuietly(deps, requestContext, scopeId); + if (engine == null) { + try { + engine = (await deps.resolveService(requestContext, 'objectql', scopeId)) ?? undefined; + } catch { + engine = undefined; } - const target = await resolveWriteResponseSchema(deps, requestContext, engine, site.target, scopeId); - const gate = checkApiExposure(target as ObjectApiDef | undefined, RELATION_CONDITION_TARGET_ACTION); - if (!gate.allowed) throw unservedRelationTargetError(site.target, `where.${site.field}`, gate); } + return registryObjectPackageDisabled((engine as { registry?: unknown } | null | undefined)?.registry); } /** @@ -662,9 +716,19 @@ export async function callData(deps: ActionExecutionDeps, ): Promise { // The object-level API exposure gate ({@link refuseUnexposedDataAction}). // [#22823] Decided ONCE, here: the same bypass covers each nested-relation - // condition's target, asked below on the two arms that hand the engine a - // caller's `where` ({@link refuseUnservedRelationTargets}). + // condition's target's EXPOSURE question, asked below on the two arms that + // hand the engine a caller's `where` ({@link refuseUnservedRelationTargets}); + // [#36393] its disabled-package question is asked of every caller. const exposureGated = !executionContext?.isSystem; + // [#36393] The disabled-package question, asked of EVERY caller (a system + // context included, the #35526 ruling) before any exposure verdict: of the + // addressed object here, and of every nested-relation condition's target + // below. Read from the engine's registry, so a host with no protocol + // service, whose by-name read below cannot refuse, refuses too. + const isObjectPackageDisabled = await packageDisabledPredicate(deps, requestContext, scopeId); + if (typeof params?.object === 'string' && isObjectPackageDisabled(params.object)) { + throw objectPackageDisabledError(params.object); + } // [#25120] `'refuse'`: a disabled package's object is refused here, on // every arm, the `aggregate` arm that never reaches the protocol included. await refuseUnexposedDataAction(deps, requestContext, action, params?.object, scopeId, executionContext, 'refuse'); @@ -964,9 +1028,7 @@ export async function callData(deps: ActionExecutionDeps, // [#22823] …and each nested-relation condition's TARGET, before the // engine reads it — the protocol path asks the same of the same // sites (`refuseUnservedRelationTarget`). - if (exposureGated) { - await refuseUnservedRelationTargets(deps, requestContext, ql, params.object, bag.where, scopeId); - } + await refuseUnservedRelationTargets(deps, requestContext, ql, params.object, bag.where, scopeId, { isObjectPackageDisabled, exposureGated }); // …and the `internal: true` evaluate refusal for every caller, as // the protocol path asks it inside `findData` — the engine's one // definition (see the `aggregate` arm). A raw driver on the MCP @@ -1003,9 +1065,7 @@ export async function callData(deps: ActionExecutionDeps, // is asked before the engine aggregates, as the query fallback asks // it (the engine lowers relation conditions in `where` only, never // in an aggregation's own `filter`). - if (exposureGated) { - await refuseUnservedRelationTargets(deps, requestContext, engine, params.object, params.where, scopeId); - } + await refuseUnservedRelationTargets(deps, requestContext, engine, params.object, params.where, scopeId, { isObjectPackageDisabled, exposureGated }); // The `internal: true` evaluate refusal — a filter (`where`, an // aggregation's own `filter`), a group key or an aggregation operand // on such a field — asked of the ENGINE's one definition