Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .changeset/35526-calldata-relation-disabled-package.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
---
'@objectstack/runtime': patch
'@objectstack/metadata-protocol': patch
Expand All @@ -5,16 +5,16 @@

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

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: the moved answer is what the data route already answers for a relation condition on a disabled package's object. A caller that needs those records re-enables the package. -->

**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.
18 changes: 18 additions & 0 deletions .changeset/36393-calldata-disabled-package-every-hop.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: every moved answer is what the protocol's data route already answers for the same object and the same condition. A caller that needs those records re-enables the package or exposes the object. -->

**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.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> = {
...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<string>; 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<typeof makeHopBridge>['bridge'], where: Record<string, unknown>) => b.query('rcx_hop_source', { where }),
aggregate: (b: ReturnType<typeof makeHopBridge>['bridge'], where: Record<string, unknown>) =>
b.aggregate!('rcx_hop_source', { where, aggregations: [{ function: 'count', alias: 'n' }] }),
};
const refusal = async (run: () => Promise<unknown>) => {
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);
});
}
});
25 changes: 21 additions & 4 deletions packages/mcp/src/stdio-data-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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
Expand All @@ -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
// ---------------------------------------------------------------------------
Expand Down
Loading
Loading