Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(mcp-host): lock user-flavor broker principal to the authenticated sender (#319 C2/H1)
Diego Zacariasa3e0adc13024
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 6353d567d..ef637436a 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.243",+ "version": "0.1.244","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.243",+ "version": "0.1.244","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 03504a1f5..579114d46 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.243",+ "version": "0.1.244","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts b/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.tsindex 31541097b..6f2416c87 100644--- a/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts+++ b/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts@@ -134,6 +134,83 @@ describe('McpToolRegistryAdapter', () => {})})+ // ─── Principal binding (PR #319 C2/H1) ──────────────────────────────────────+ //+ // The userId the adapter forwards to `manager.callTool` (which becomes the+ // oauth grantScope='user' broker grant subject) MUST be the authenticated task+ // sender baked into the adapter at construction (taskExecutor threads+ // `task.sourceMessage.sender`), NEVER a value the model can choose. These lock+ // that the principal is the constructor identity and cannot be spoofed by a+ // tool argument named `userId`, and that two per-user adapters never cross.+ describe('principal binding — broker userId is the authenticated sender, not a tool arg', () => {+ function capturingManager(): {+ manager: unknown+ calls: Array<{ tool: string; params: Record<string, unknown>; options: unknown }>+ } {+ const calls: Array<{ tool: string; params: Record<string, unknown>; options: unknown }> = []+ const manager = {+ getAllTools: () => [+ {+ name: 'gh__do',+ description: 'demo',+ inputSchema: { type: 'object' },+ serverName: 'gh',+ },+ ],+ callTool: vi.fn(async (tool: string, params: Record<string, unknown>, options: unknown) => {+ calls.push({ tool, params, options })+ return {+ toolName: tool,+ result: { content: [{ type: 'text', text: 'ok' }] },+ isError: false,+ }+ }),+ }+ return { manager, calls }+ }++ it('forwards the constructor userId as options.userId, ignoring a spoofed `userId` arg', async () => {+ const { manager, calls } = capturingManager()+ // Adapter built for the authenticated sender "alice".+ const registry = new McpToolRegistryAdapter(manager as never, 'alice')+ const tool = registry.get('gh__do')!++ // The model supplies its own `userId` arg trying to impersonate "bob".+ await tool.execute({ userId: 'bob', foo: 1 })++ expect(calls).toHaveLength(1)+ // The broker subject is the authenticated identity, never the arg.+ expect(calls[0].options).toEqual({ userId: 'alice' })+ // The arg is still forwarded verbatim as tool params (it is data, not identity).+ expect(calls[0].params).toEqual({ userId: 'bob', foo: 1 })+ })++ it('two per-user adapters never forward each other’s userId', async () => {+ const { manager, calls } = capturingManager()+ const aliceTool = new McpToolRegistryAdapter(manager as never, 'alice').get('gh__do')!+ const bobTool = new McpToolRegistryAdapter(manager as never, 'bob').get('gh__do')!++ await aliceTool.execute({})+ await bobTool.execute({})++ expect(calls.map(c => (c.options as { userId?: string }).userId)).toEqual(['alice', 'bob'])+ // Alice's identity is emitted exactly once, only from her own adapter.+ expect(calls.filter(c => (c.options as { userId?: string }).userId === 'alice')).toHaveLength(+ 1+ )+ })++ it('an absent authenticated sender forwards userId=undefined (manager fails closed)', async () => {+ const { manager, calls } = capturingManager()+ // No sender on the task → no userId (never a body/arg fallback).+ const tool = new McpToolRegistryAdapter(manager as never).get('gh__do')!++ await tool.execute({ userId: 'anyone' })++ expect(calls[0].options).toEqual({ userId: undefined })+ })+ })+it('uses a text summary when MCP content contains only images', async () => {const mockManager = {getAllTools: () => [diff --git a/mcp-host/src/core/adapters/toolRegistryAdapter.ts b/mcp-host/src/core/adapters/toolRegistryAdapter.tsindex 597cb675a..fb8eb25c9 100644--- a/mcp-host/src/core/adapters/toolRegistryAdapter.ts+++ b/mcp-host/src/core/adapters/toolRegistryAdapter.ts@@ -108,6 +108,13 @@ class McpToolAdapter implements Tool {async execute(params: Record<string, unknown>): Promise<ToolOutput> {const startTime = Date.now()try {+ // Principal binding (PR #319 C2/H1): the broker grant subject is ALWAYS+ // `this.userId` — the authenticated task sender baked in at construction+ // (taskExecutor threads `task.sourceMessage.sender`, itself bound to the+ // rpc-proxy edge `auth.sub` in handleMessageRoute). `params` is model /+ // tool-arg data and is forwarded as the call payload only; it can NEVER+ // become the identity, so a `userId` field inside `params` cannot spoof+ // another user's broker token.const result = await this.mcpManager.callTool(this.fullName, params, {userId: this.userId,})diff --git a/mcp-host/src/mcp/__tests__/managerPartition.test.ts b/mcp-host/src/mcp/__tests__/managerPartition.test.tsindex 4b088c4af..9817647e7 100644--- a/mcp-host/src/mcp/__tests__/managerPartition.test.ts+++ b/mcp-host/src/mcp/__tests__/managerPartition.test.ts@@ -13,6 +13,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest'import fc from 'fast-check'import type { McpServerInfo } from '../../types'+import { createBrokerTokenProvider } from '../brokerTokenProvider'import type { McpTokenProvider } from '../client'import {McpManager,@@ -242,6 +243,83 @@ describe('Identity isolation: A partition never serves B', () => {})})+// ─── Broker principal binding (PR #319 C2/H1) ────────────────────────────────+//+// End-to-end proof of the load-bearing invariant: the userId a tool call+// carries (options.userId — the authenticated task sender, see+// toolRegistryAdapter) is the SAME value the mcp-host POSTs to the control-api+// broker as the grant subject. Composes the REAL manager with the REAL+// brokerTokenProvider (only the network `fetch` is stubbed); the broker+// principal is NEVER a hand-minted fixture. control-api trusting that body+// userId is the documented seam — mcp-host's contract is that it only ever+// sends the caller's own identity.++describe('Broker principal binding: POST subject is the caller, never crossed', () => {+ /** Factory wiring the REAL broker provider for user principals, mirroring+ * main.ts createMcpTokenProviderFactory grantScope='user': user → broker+ * (server, userId); SHARED → token-less catalog representative. Captures every+ * broker POST body so the test asserts what identity actually left the host. */+ function brokerFactory(): {+ factory: McpTokenProviderFactory+ bodies: Array<{ mcpServerName?: string; userId?: string; contextId?: string }>+ } {+ const bodies: Array<{ mcpServerName?: string; userId?: string; contextId?: string }> = []+ const fetchImpl = vi.fn(async (_url: string, init: RequestInit) => {+ const body = JSON.parse(init.body as string) as { userId?: string }+ bodies.push(body)+ return {+ status: 200,+ json: async () => ({ token: `tok-for-${body.userId}`, expiresAt: null }),+ } as unknown as Response+ })+ const factory: McpTokenProviderFactory = (server, principal) =>+ principal.kind === 'user'+ ? createBrokerTokenProvider(+ server,+ { userId: principal.userId },+ {+ gatewayUrl: () => 'http://gateway:8092',+ controlToken: () => 'control-jwt',+ fetchImpl: fetchImpl as unknown as typeof fetch,+ }+ )+ : { resolve: async () => undefined, refresh: async () => undefined }+ return { factory, bodies }+ }++ it('the userId POSTed to the broker equals the callTool userId (per caller)', async () => {+ const { factory, bodies } = brokerFactory()+ const manager = new McpManager(undefined, undefined, factory)+ await manager.addServer(oauthUserServer())++ await manager.callTool('gh__do', {}, { userId: 'alice' })+ await manager.callTool('gh__do', {}, { userId: 'bob' })++ // Every broker exchange carries exactly the caller's own identity — no other.+ expect(bodies).toContainEqual({ mcpServerName: 'gh', userId: 'alice' })+ expect(bodies).toContainEqual({ mcpServerName: 'gh', userId: 'bob' })+ expect(bodies.every(b => b.userId === 'alice' || b.userId === 'bob')).toBe(true)+ // Alice's identity is emitted once; bob's connect never POSTs alice's userId.+ expect(bodies.filter(b => b.userId === 'alice')).toHaveLength(1)++ // And the resolved Bearer lands only on that caller's own connection.+ const authHeaders = sdk.transports.map(t => t.requestHeaders['Authorization'])+ expect(authHeaders).toContain('Bearer tok-for-alice')+ expect(authHeaders).toContain('Bearer tok-for-bob')+ expect(authHeaders.filter(h => h === 'Bearer tok-for-alice')).toHaveLength(1)+ })++ it('never POSTs a userId for the token-less SHARED catalog representative', async () => {+ const { factory, bodies } = brokerFactory()+ const manager = new McpManager(undefined, undefined, factory)+ // addServer opens the SHARED representative (catalog population) with no user.+ await manager.addServer(oauthUserServer())++ // No per-user call yet → the representative must not have brokered any grant.+ expect(bodies).toEqual([])+ })+})+// ─── Revocation purge ────────────────────────────────────────────────────────describe('Revocation: detachServer purges every ClientKey of the serverName', () => {