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
14 changes: 14 additions & 0 deletions .changeset/28938-federation-pair-listed-only-when-callable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/runtime': patch
---

fix(runtime): an MCP grant that holds no federation capability is no longer listed `list_remote_tables` / `import_object` (#28938)

Clause-②: no — no call that passed before is refused now, and none that was refused passes: what changes is that a request whose every federation call would answer `403 PERMISSION_DENIED` is no longer listed the pair.
Metadata-protocol: none

The `/mcp` door hands an OAuth agent the delegating user's system capabilities only when the grant names `actions:execute`. A `metadata:write`-only grant therefore holds none, yet it was listed `list_remote_tables` and `import_object`, and every call answered `403 PERMISSION_DENIED`, even when the user is an administrator.

- **Now.** The runtime's MCP bridge carries the pair only when the request holds `manage_platform_settings` (the listing's capability) or `manage_metadata` (the import's). Without either, `tools/list` omits both, the way `list_actions` omits an action its caller may not run. The listing decision and the per-call check read the same capabilities, so they cannot disagree.
- **Unchanged.** A grant naming `metadata:write` and `actions:execute`, for a user who holds the capabilities, lists and calls both as before. A request holding one capability is still listed both, and the call that needs the other still answers `403`. API keys and sessions are still not listed the pair.
- **To use the pair from an MCP client:** connect with `metadata:write` and `actions:execute`, as a user who holds the capability.
111 changes: 111 additions & 0 deletions packages/runtime/src/domains/mcp-federation-bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import { describe, it, expect } from 'vitest';
import { FEDERATION_READ_CAPABILITY, FEDERATION_WRITE_CAPABILITY } from '@objectstack/rest';
import { buildMcpBridge } from './mcp.js';
import { resolveExecutionContext } from '../security/resolve-execution-context.js';
import { bindCatalogFromTables } from '../security/security-catalog.testkit.js';

function bridgeFor(systemPermissions: string[], service: unknown) {
const lookups: string[] = [];
Expand Down Expand Up @@ -78,3 +80,112 @@ describe('the MCP federation bridge gates on the federation capabilities', () =>
await expect(bridge.listRemoteTables('erp', {})).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
});
});

// ── [#28938] the pair is carried only where a call can pass ─────────────────
//
// The envelopes below are resolved by the real `/mcp` door
// (`resolveExecutionContext` with an OAuth token), not written by hand: what an
// agent holds is the door's derivation, and a hand-built envelope would pin the
// test's belief about it instead. The delegating user is an administrator whose
// set carries BOTH federation capabilities.
//
// The door hands an agent the user's system capabilities only under
// `actions:execute`; a `metadata:write`-only grant therefore holds none, and no
// federation call can ever pass for it. Listing the pair there served two tools
// whose every call answered 403 — so the bridge carries the pair only for an
// envelope holding a capability one of the two answers to. Nothing a grant can
// DO changes: every call that passed still passes.

function capableUserQl(systemPermissions: string[]) {
const tables: Record<string, any[]> = {
sys_member: [{ user_id: 'u1', organization_id: 'orgA', role: 'owner' }],
sys_organization: [{ id: 'org_default', slug: 'default' }],
sys_user_permission_set: [{ id: 'ups1', user_id: 'u1', permission_set_id: 'ps_admin', permission_set: 'admin_full_access', organization_id: 'org_default' }],
sys_permission_set: [{ id: 'ps_admin', name: 'admin_full_access', system_permissions: JSON.stringify(systemPermissions), object_permissions: '{}' }],
sys_position: [], sys_position_permission_set: [], sys_user_position: [],
};
return bindCatalogFromTables({
async find(object: string, opts: any) {
const rows = (tables[object] ?? []).filter((row) =>
Object.entries(opts?.where ?? {}).every(([k, v]) =>
v !== null && typeof v === 'object'
? (Array.isArray((v as any).$in) ? (v as any).$in.includes(row[k]) : true)
: (v ?? null) === (row[k] ?? null),
),
);
return typeof opts?.limit === 'number' ? rows.slice(0, opts.limit) : rows;
},
}, tables);
}

async function oauthEnvelope(scopes: string[], systemPermissions: string[]) {
return resolveExecutionContext({
acceptOAuthAccessToken: true,
getService: async (name: string) =>
name === 'auth' ? { verifyMcpAccessToken: async () => ({ userId: 'u1', scopes, clientId: 'c1' }) } : undefined,
getQl: async () => capableUserQl(systemPermissions),
request: { headers: { authorization: 'Bearer a.b.c' } },
} as never);
}

function bridgeOver(executionContext: unknown, service: unknown) {
const lookups: string[] = [];
const deps = {
resolveService: async (_ctx: unknown, name: string) => {
lookups.push(name);
return name === 'external-datasource' ? service : undefined;
},
};
const context = { environmentId: 'env_1', executionContext };
return { bridge: buildMcpBridge(deps as never, context as never), lookups };
}

const ADMIN_CAPS = [FEDERATION_READ_CAPABILITY, FEDERATION_WRITE_CAPABILITY, 'manage_users'];

describe('the federation pair rides the bridge only for an envelope that can call it', () => {
it('a metadata:write-only grant for an administrator carries neither member: no call of it could pass', async () => {
const ec = await oauthEnvelope(['metadata:write'], ADMIN_CAPS);
expect(ec.principalKind).toBe('agent');
expect(ec.oauthScopes).toEqual(['metadata:write']);
// The door's derivation, measured: no `actions:execute`, no capability.
expect(ec.systemPermissions).toEqual([]);
const service = fakeService();
const { bridge, lookups } = bridgeOver(ec, service);
// `wireBridgeTools` registers the pair only on a bridge carrying both
// members, so absence here is `tools/list` omitting them.
expect(typeof bridge.listRemoteTables).toBe('undefined');
expect(typeof bridge.importObject).toBe('undefined');
expect(lookups).not.toContain('external-datasource');
expect(service.calls).toEqual([]);
});

it('the same administrator under metadata:write + actions:execute keeps the pair, and both calls reach the service', async () => {
const ec = await oauthEnvelope(['metadata:write', 'actions:execute'], ADMIN_CAPS);
expect(ec.systemPermissions).toEqual(expect.arrayContaining([FEDERATION_READ_CAPABILITY, FEDERATION_WRITE_CAPABILITY]));
const service = fakeService();
const { bridge } = bridgeOver(ec, service);
await expect(bridge.listRemoteTables('erp', {})).resolves.toEqual([{ name: 'Products', columnCount: 6 }]);
await bridge.importObject('erp', 'Products', {});
expect(service.calls).toEqual([
['listRemoteTables', 'erp', {}],
['importObject', 'erp', 'Products', {}],
]);
});

it('a delegating user holding only the write capability keeps the pair, and the listing still refuses 403', async () => {
const ec = await oauthEnvelope(['metadata:write', 'actions:execute'], [FEDERATION_WRITE_CAPABILITY]);
const service = fakeService();
const { bridge, lookups } = bridgeOver(ec, service);
await expect(bridge.listRemoteTables('erp', {})).rejects.toMatchObject({ code: 'PERMISSION_DENIED', status: 403 });
expect(lookups).not.toContain('external-datasource');
expect(service.calls).toEqual([]);
});

it('a delegating user holding neither capability is carried neither member', async () => {
const ec = await oauthEnvelope(['metadata:write', 'actions:execute'], ['manage_users']);
expect(ec.systemPermissions).toEqual(['manage_users']);
const { bridge } = bridgeOver(ec, fakeService());
expect(typeof bridge.listRemoteTables).toBe('undefined');
expect(typeof bridge.importObject).toBe('undefined');
});
});
39 changes: 33 additions & 6 deletions packages/runtime/src/domains/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -920,13 +920,41 @@ export function buildMcpBridge(deps: DomainHandlerDeps, context: HttpProtocolCon
// The `external-datasource` service Studio's datasource page reaches
// through `…/external/tables` and `…/tables/:remote/import`, refused
// on the same two capabilities those routes gate on.
listRemoteTables: async (datasource: string, opts: { schema?: string }) =>
(await federationService(deps, context, ec, 'read')).listRemoteTables(datasource, opts),
importObject: async (datasource: string, remoteName: string, opts: { name?: string; writable?: boolean }) =>
(await federationService(deps, context, ec, 'write')).importObject(datasource, remoteName, opts),
//
// [#28938] Carried only for an envelope holding one of those two
// capabilities. `wireBridgeTools` (`@objectstack/mcp`) registers the
// pair only on a bridge carrying both members, so without them
// `tools/list` omits the pair —
// the shape `list_actions` already has, which hides an action its
// caller may not run. The case that made this matter: the `/mcp` door
// hands an OAuth agent the user's system capabilities only under
// `actions:execute`, so a `metadata:write`-only grant holds none and
// was listed two tools whose every call answered 403, for an
// administrator too. Read off the SAME envelope the per-call gate
// reads ({@link heldFederationCapabilities}), so listing and calling
// cannot disagree; nothing a grant can do changes.
...(heldFederationCapabilities(ec).length > 0
? {
listRemoteTables: async (datasource: string, opts: { schema?: string }) =>
(await federationService(deps, context, ec, 'read')).listRemoteTables(datasource, opts),
importObject: async (datasource: string, remoteName: string, opts: { name?: string; writable?: boolean }) =>
(await federationService(deps, context, ec, 'write')).importObject(datasource, remoteName, opts),
}
: {}),
};
}

/**
* [#28938] The federation capabilities this request's envelope holds — the
* one read both the bridge's listing decision and {@link federationService}'s
* per-call gate make, so a tool is listed exactly where some call of the pair
* can pass.
*/
function heldFederationCapabilities(ec: any): string[] {
const held: unknown[] = Array.isArray(ec?.systemPermissions) ? ec.systemPermissions : [];
return [FEDERATION_READ_CAPABILITY, FEDERATION_WRITE_CAPABILITY].filter((cap) => held.includes(cap));
}

/**
* [#27745] The `external-datasource` service for one federation tool call, or
* the refusal the REST twin answers: `403 PERMISSION_DENIED` without the
Expand All @@ -941,8 +969,7 @@ async function federationService(
kind: 'read' | 'write',
): Promise<IExternalDatasourceService> {
const required = kind === 'write' ? FEDERATION_WRITE_CAPABILITY : FEDERATION_READ_CAPABILITY;
const held: unknown[] = Array.isArray(ec?.systemPermissions) ? ec.systemPermissions : [];
if (!held.includes(required)) {
if (!heldFederationCapabilities(ec).includes(required)) {
throw Object.assign(
new Error(
kind === 'write'
Expand Down
Loading