Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

test(control-api): pin owner check before remote spec coherence (BR-05)

Diego Zacarias5bb8e5783f9f
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 53a7da07a..27699aba0 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.822",
+ "version": "0.1.823",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.822",
+ "version": "0.1.823",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index f51260d32..96964cb2f 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.822",
+ "version": "0.1.823",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/test/routes.mcpOauth.brokerBinding.property.test.ts b/control-api/test/routes.mcpOauth.brokerBinding.property.test.ts
index 6503b494c..746e063a8 100644
--- a/control-api/test/routes.mcpOauth.brokerBinding.property.test.ts
+++ b/control-api/test/routes.mcpOauth.brokerBinding.property.test.ts
@@ -1,5 +1,4 @@
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
-import fc from 'fast-check'
import request from 'supertest'
import { createApp } from '../src/app.js'
import { config } from '../src/config.js'
@@ -95,28 +94,37 @@ function serverSpec(
}
}
-const caseArb = fc.oneof(
- fc.record({
- state: fc.constantFrom<State>('missing', 'outside_allowlist', 'deleting', 'disabled'),
- shape: fc.constantFrom<Shape>(
- 'oauth',
- 'remote_incoherent',
- 'not_oauth',
- 'unsupported_provider'
- ),
- grantScope: fc.constantFrom<'user' | 'context'>('user', 'context'),
- withUserId: fc.boolean(),
- withContextId: fc.boolean(),
- }),
+interface Case {
+ state: State
+ shape: Shape
+ grantScope: 'user' | 'context'
+ withUserId: boolean
+ withContextId: boolean
+}
+
+// The full cartesian product (144 cases) instead of a random sample, so an
+// ordering regression is caught on every run rather than only on a lucky seed.
+const BOOLS = [false, true] as const
+function enumerate(states: State[], shapes: Shape[], scopes: Array<'user' | 'context'>): Case[] {
+ return states.flatMap(state =>
+ shapes.flatMap(shape =>
+ scopes.flatMap(grantScope =>
+ BOOLS.flatMap(withUserId =>
+ BOOLS.map(withContextId => ({ state, shape, grantScope, withUserId, withContextId }))
+ )
+ )
+ )
+ )
+}
+const CASES: Case[] = [
+ ...enumerate(
+ ['missing', 'outside_allowlist', 'deleting', 'disabled'],
+ ['oauth', 'remote_incoherent', 'not_oauth', 'unsupported_provider'],
+ ['user', 'context']
+ ),
// The owner rule only applies to shared OAuth servers.
- fc.record({
- state: fc.constantFrom<State>('foreign_owner', 'no_owner'),
- shape: fc.constantFrom<Shape>('oauth', 'remote_incoherent'),
- grantScope: fc.constant<'user' | 'context'>('context'),
- withUserId: fc.boolean(),
- withContextId: fc.boolean(),
- })
-)
+ ...enumerate(['foreign_owner', 'no_owner'], ['oauth', 'remote_incoherent'], ['context']),
+]
describe('P-I5: uniform server_not_found across the Context boundary', () => {
const originalBrokerEnabled = config.mcpOauthBrokerEnabled
@@ -130,56 +138,55 @@ describe('P-I5: uniform server_not_found across the Context boundary', () => {
})
it('every hidden state answers 404 {"error":"server_not_found"} without reading grants or Secrets', async () => {
- await fc.assert(
- fc.asyncProperty(caseArb, async c => {
- mockPoolQuery.mockReset()
- membership(mockPoolQuery, { agents: { [USER]: [HOST] } })
- const gateway = new MockGateway(MCP_NS)
- const app = createApp(gateway as never)
- await seedAgentHost(gateway, HOST, HOST_CONTEXT)
- await seedAllowlistedContext(gateway, HOST_CONTEXT, [], config.contextsNamespace)
- await seedAllowlistedContext(gateway, OTHER_CONTEXT, [SERVER], config.contextsNamespace)
- const token = await mintHccControlToken(app, gateway, HOST)
-
- const owner =
- c.state === 'no_owner'
- ? undefined
- : c.state === 'foreign_owner' || c.state === 'outside_allowlist'
- ? OTHER_CONTEXT
- : HOST_CONTEXT
- if (c.state !== 'missing') {
- const spec = serverSpec(c.shape, c.grantScope, owner)
- if (c.state === 'disabled') spec.enabled = false
- await gateway.createResource('mcpservers', { metadata: { name: SERVER }, spec }, MCP_NS)
- if (c.state === 'deleting') gateway.markDeleting('mcpservers', SERVER, MCP_NS)
- }
- if (c.state !== 'outside_allowlist') {
- await attachServerToContext(
- gateway as never,
- { name: HOST_CONTEXT, namespace: config.contextsNamespace },
- SERVER
- )
- }
- const secretReads = vi.spyOn(gateway, 'getSecret')
-
- const res = await request(app)
- .post('/api/v1/mcp-oauth/user-token')
- .set('Authorization', `Bearer ${token}`)
- .send({
- mcpServerName: SERVER,
- ...(c.withUserId ? { userId: USER } : {}),
- ...(c.withContextId ? { contextId: HOST_CONTEXT } : {}),
- })
-
- expect(res.status).toBe(404)
- expect(res.text).toBe('{"error":"server_not_found"}')
- const grantReads = mockPoolQuery.mock.calls.filter(
- ([sql]) => typeof sql === 'string' && sql.includes('oauth_grants')
+ expect(CASES).toHaveLength(144)
+ for (const c of CASES) {
+ mockPoolQuery.mockReset()
+ membership(mockPoolQuery, { agents: { [USER]: [HOST] } })
+ const gateway = new MockGateway(MCP_NS)
+ const app = createApp(gateway as never)
+ await seedAgentHost(gateway, HOST, HOST_CONTEXT)
+ await seedAllowlistedContext(gateway, HOST_CONTEXT, [], config.contextsNamespace)
+ await seedAllowlistedContext(gateway, OTHER_CONTEXT, [SERVER], config.contextsNamespace)
+ const token = await mintHccControlToken(app, gateway, HOST)
+
+ const owner =
+ c.state === 'no_owner'
+ ? undefined
+ : c.state === 'foreign_owner' || c.state === 'outside_allowlist'
+ ? OTHER_CONTEXT
+ : HOST_CONTEXT
+ if (c.state !== 'missing') {
+ const spec = serverSpec(c.shape, c.grantScope, owner)
+ if (c.state === 'disabled') spec.enabled = false
+ await gateway.createResource('mcpservers', { metadata: { name: SERVER }, spec }, MCP_NS)
+ if (c.state === 'deleting') gateway.markDeleting('mcpservers', SERVER, MCP_NS)
+ }
+ if (c.state !== 'outside_allowlist') {
+ await attachServerToContext(
+ gateway as never,
+ { name: HOST_CONTEXT, namespace: config.contextsNamespace },
+ SERVER
)
- expect(grantReads).toHaveLength(0)
- expect(secretReads).not.toHaveBeenCalled()
- }),
- { numRuns: 200 }
- )
+ }
+ const secretReads = vi.spyOn(gateway, 'getSecret')
+
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .set('Authorization', `Bearer ${token}`)
+ .send({
+ mcpServerName: SERVER,
+ ...(c.withUserId ? { userId: USER } : {}),
+ ...(c.withContextId ? { contextId: HOST_CONTEXT } : {}),
+ })
+
+ const label = JSON.stringify(c)
+ expect(res.status, label).toBe(404)
+ expect(res.text, label).toBe('{"error":"server_not_found"}')
+ const grantReads = mockPoolQuery.mock.calls.filter(
+ ([sql]) => typeof sql === 'string' && sql.includes('oauth_grants')
+ )
+ expect(grantReads, label).toHaveLength(0)
+ expect(secretReads, label).not.toHaveBeenCalled()
+ }
})
})
diff --git a/control-api/test/routes.mcpOauth.test.ts b/control-api/test/routes.mcpOauth.test.ts
index 6eaade78e..4d6538031 100644
--- a/control-api/test/routes.mcpOauth.test.ts
+++ b/control-api/test/routes.mcpOauth.test.ts
@@ -2,8 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import request from 'supertest'
import { createApp } from '../src/app.js'
import { config } from '../src/config.js'
+import { discoverRemoteOAuth } from '../src/oauth/discovery.js'
import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryption.js'
import { registry } from '../src/observability/metrics.js'
+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
import { attachServerToContext } from '../src/services/contextAllowlist.js'
import { checkAndIncrement } from '../src/services/rateLimiterService.js'
import { verifyMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'
@@ -13,6 +15,7 @@ import {
signInternalControlJwt,
signLegacyControlToken,
} from './fixtures/hccControlToken.js'
+import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'
import { captureRequestLogs } from './helpers/requestLogCapture.js'
import { MockGateway } from './mockGateway.js'
@@ -598,6 +601,51 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {
expect(grantQueries()).toHaveLength(0)
})
+ it('R6: a foreign-owned context server with an incoherent remote spec → the same 404, not a 409', async () => {
+ // Derived from the real producer: the builder's confidential output with
+ // clientMode flipped to public, an in-place edit the coherence check refuses.
+ const outcome = await discoverRemoteOAuth(PILOTS.sentry.mcpUrl, {
+ transport: makeDiscoveryTransport(PILOTS.sentry),
+ resolveDns: async () => ['93.184.216.34'],
+ })
+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)
+ const incoherentOauth = {
+ ...(buildRemoteOAuthSpec(outcome.result, {
+ clientMode: 'confidential',
+ grantScope: 'context',
+ clientSecretName: 'gdrive-oauth-client',
+ preRegisteredClientId: 'client-abc',
+ }) as unknown as Record<string, unknown>),
+ clientMode: 'public',
+ }
+ const seed = (contextRef: string) =>
+ gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: 'gdrive' },
+ spec: { contextRef, auth: { type: 'oauth' }, oauth: incoherentOauth },
+ },
+ MCP_NS
+ )
+
+ // Control: owned by the Host Context, the same spec is refused as incoherent.
+ await seed(HOST_CONTEXT)
+ const own = await post({ mcpServerName: 'gdrive', userId: USER_1 })
+ expect(own.status).toBe(409)
+ expect(own.body.error).toBe('remote_oauth_spec_incoherent')
+
+ await gateway.deleteResource('mcpservers', 'gdrive', MCP_NS)
+ await seed('ctx-A')
+ const secretReads = vi.spyOn(gateway, 'getSecret')
+
+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })
+
+ expect(res.status).toBe(404)
+ expect(res.text).toBe('{"error":"server_not_found"}')
+ expect(grantQueries()).toHaveLength(0)
+ expect(secretReads).not.toHaveBeenCalled()
+ })
+
it('R6b: a body contextId is ignored — a foreign value neither denies nor redirects the key', async () => {
seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: HOST_CONTEXT })
grantRows = [sharedGrantRow(HOST_CONTEXT, new Date(Date.now() + 3600_000))]