Skip to content

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

TypeScript

fix(oauth): map remote discovery network failures to 5xx (H-5)

Diego Zacariasa5b354ce9a8e
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 6ae781fe2..7f6ce4328 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.594",
+ "version": "0.1.595",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.594",
+ "version": "0.1.595",
"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 5b35eb47d..860e1b21b 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.594",
+ "version": "0.1.595",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.ts b/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.ts
new file mode 100644
index 000000000..8633824a9
--- /dev/null
+++ b/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.ts
@@ -0,0 +1,128 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import type { DiscoveryError } from '../../../oauth/discovery.js'
+
+// The discover route runs the kernel §4 pre-check (validateOAuthEndpointUrl) before
+// reaching discovery, and that check does a REAL DNS lookup with no injectable
+// resolver. This finding is about the discovery-error → HTTP-status mapping, not the
+// kernel check, so stub the kernel to pass and drive discovery through the injected
+// `discover` seam — keeping the test fully offline.
+vi.mock('../../../http/validateMcpServerSpec.js', () => ({
+ validateOAuthEndpointUrl: async () => [],
+}))
+
+// Auth is enforced by requireAuthForControlUI; stub it the same way the neighbouring
+// admin-router tests do (mock path is resolved relative to THIS file).
+vi.mock('../../../middleware/controlUIAuth.js', () => ({
+ requireAuthForControlUI: (req: any, _res: any, next: any) => {
+ req.adminAuth = { sub: 'test-admin', jti: 'test-jti' }
+ next()
+ },
+}))
+
+// Import AFTER vi.mock so the mocked modules wire up.
+const { createAdminRemoteMcpRouter, discoveryHttpStatus } = await import('../remoteMcp.js')
+
+// A public URL that passes the (stubbed) kernel §4 pre-check.
+const BASE_URL = 'https://as.example.test'
+
+function fetchFailedDiscover() {
+ return vi.fn().mockResolvedValue({
+ ok: false,
+ error: {
+ kind: 'fetch_failed',
+ url: 'https://as.example.test/.well-known/oauth-protected-resource',
+ detail: 'connect ECONNREFUSED',
+ },
+ })
+}
+
+function buildApp(discover: ReturnType<typeof fetchFailedDiscover>) {
+ const app = express()
+ app.use(express.json({ limit: '1mb' }))
+ const gateway = {} as any
+ app.use(
+ '/api/v1',
+ createAdminRemoteMcpRouter(gateway, {
+ // Inject a fixed encryption key so router construction never touches config.
+ encryptionKey: Buffer.alloc(32),
+ discover: discover as any,
+ })
+ )
+ return app
+}
+
+describe('discoveryHttpStatus — DiscoveryError → HTTP status decision table', () => {
+ // One entry per DiscoveryError.kind. 502 = upstream transport failure (AS gave no
+ // usable HTTP response); 400 = operator-actionable (bad input or reachable-but-
+ // incompatible AS).
+ const cases: Array<{ error: DiscoveryError; status: number }> = [
+ {
+ error: { kind: 'fetch_failed', url: 'https://as.example.test/x', detail: 'ECONNREFUSED' },
+ status: 502,
+ },
+ {
+ error: {
+ kind: 'content_encoding_rejected',
+ url: 'https://as.example.test/x',
+ encoding: 'br',
+ },
+ status: 502,
+ },
+ { error: { kind: 'kernel_rejected', field: 'baseUrl', errors: [] }, status: 400 },
+ {
+ error: { kind: 'invalid_metadata', url: 'https://as.example.test/x', detail: 'bad json' },
+ status: 400,
+ },
+ { error: { kind: 'no_s256', detail: 'S256 not advertised' }, status: 400 },
+ {
+ error: { kind: 'no_authorization_server', detail: 'no authorization_servers[0]' },
+ status: 400,
+ },
+ {
+ error: {
+ kind: 'redirect_blocked',
+ url: 'https://as.example.test/x',
+ detail: 'missing Location',
+ },
+ status: 400,
+ },
+ {
+ error: {
+ kind: 'prm_resource_mismatch',
+ url: 'https://as.example.test/x',
+ detail: 'resource mismatch',
+ },
+ status: 400,
+ },
+ { error: { kind: 'issuer_mismatch', detail: 'issuer != base' }, status: 400 },
+ ]
+
+ for (const { error, status } of cases) {
+ it(`maps ${error.kind} → ${status}`, () => {
+ expect(discoveryHttpStatus(error)).toBe(status)
+ })
+ }
+})
+
+describe('POST /admin/mcp-servers/remote/discover — discovery error mapping', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('returns 502 (not 400) when discovery fails with fetch_failed (upstream transport)', async () => {
+ const discover = fetchFailedDiscover()
+ const app = buildApp(discover)
+
+ const res = await request(app)
+ .post('/api/v1/admin/mcp-servers/remote/discover')
+ .send({ baseUrl: BASE_URL })
+
+ expect(res.status).toBe(502)
+ expect(res.body.error).toBe('discovery_failed')
+ expect(res.body.detail.kind).toBe('fetch_failed')
+ // Never hit the real network: the discovery seam was the only source of the outcome.
+ expect(discover).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/control-api/src/routes/admin/remoteMcp.ts b/control-api/src/routes/admin/remoteMcp.ts
index 5bf3d6291..9a87a9826 100644
--- a/control-api/src/routes/admin/remoteMcp.ts
+++ b/control-api/src/routes/admin/remoteMcp.ts
@@ -17,7 +17,11 @@ import {
registerDynamicClient,
} from '../../oauth/dcr.js'
import { bestEffortRfc7592Delete } from '../../oauth/dcrCleanup.js'
-import { type DiscoveryResult, discoverRemoteOAuth } from '../../oauth/discovery.js'
+import {
+ type DiscoveryError,
+ type DiscoveryResult,
+ discoverRemoteOAuth,
+} from '../../oauth/discovery.js'
import {
type DynamicClientKey,
deleteDynamicClient,
@@ -59,6 +63,38 @@ const BASE = '/admin/mcp-servers/remote'
const log = rootLogger.child({ module: 'admin-remote-mcp' })
+/**
+ * Map a discovery failure to an HTTP status for the remote-OAuth admin endpoints.
+ *
+ * `fetch_failed` and `content_encoding_rejected` are upstream transport failures —
+ * the AS never returned a usable HTTP response — so they surface as 502, the same
+ * way the callback maps provider fetch failures (`provider_token_exchange_failed` /
+ * `provider_response_invalid` → 502). Every other kind is either bad operator input
+ * (`kernel_rejected`) or a reachable-but-incompatible/misconfigured AS: retrying will
+ * not help, and the returned `detail.kind` tells the operator what to fix, so 400 is
+ * the operator-actionable signal. The switch is exhaustive over `DiscoveryError` so a
+ * newly added kind fails to compile until its status is decided here.
+ */
+export function discoveryHttpStatus(error: DiscoveryError): number {
+ switch (error.kind) {
+ case 'fetch_failed':
+ case 'content_encoding_rejected':
+ return 502
+ case 'kernel_rejected':
+ case 'invalid_metadata':
+ case 'no_s256':
+ case 'no_authorization_server':
+ case 'redirect_blocked':
+ case 'prm_resource_mismatch':
+ case 'issuer_mismatch':
+ return 400
+ default: {
+ const _exhaustive: never = error
+ return 400
+ }
+ }
+}
+
const discoverBodySchema = z.object({
baseUrl: z.string().min(1),
})
@@ -219,6 +255,12 @@ export interface AdminRemoteMcpDeps {
db?: DbClient
encryptionKey?: Buffer
dcr?: DcrDeps
+ /**
+ * Injectable discovery function (test seam only). Production leaves it undefined
+ * and the real `discoverRemoteOAuth` (real IP-pinned network) is used; tests stub
+ * it to drive a specific `DiscoveryOutcome` (e.g. a `fetch_failed`) with no network.
+ */
+ discover?: typeof discoverRemoteOAuth
}
export function createAdminRemoteMcpRouter(
@@ -229,6 +271,7 @@ export function createAdminRemoteMcpRouter(
const db: DbClient = deps.db ?? pool
const encryptionKey = deps.encryptionKey ?? deriveOAuthEncryptionKey(config.oauthEncryptionKey)
const dcrDeps: DcrDeps = deps.dcr ?? { logger: log }
+ const discover = deps.discover ?? discoverRemoteOAuth
// ── POST /admin/mcp-servers/remote/discover — dry-run, no writes ──────────
router.post(
@@ -250,10 +293,12 @@ export function createAdminRemoteMcpRouter(
return
}
- const outcome = await discoverRemoteOAuth(baseUrl, { logger: log })
+ const outcome = await discover(baseUrl, { logger: log })
if (!outcome.ok) {
log.warn({ discovery: outcome.error.kind }, 'remote discovery (dry-run) failed')
- res.status(400).json({ error: 'discovery_failed', detail: outcome.error })
+ res
+ .status(discoveryHttpStatus(outcome.error))
+ .json({ error: 'discovery_failed', detail: outcome.error })
return
}
@@ -327,14 +372,16 @@ export function createAdminRemoteMcpRouter(
// D-4: re-run discovery SERVER-SIDE at install and pin the result — never trust
// the client-passed prefill as authoritative. Discovery kernel-guards baseUrl +
// every discovered endpoint internally before returning them.
- const outcome = await discoverRemoteOAuth(
+ const outcome = await discover(
body.baseUrl,
{ logger: log },
{ hasPreRegisteredClient: body.mode === 'pre-registered' }
)
if (!outcome.ok) {
log.warn({ discovery: outcome.error.kind }, 'remote install discovery failed')
- res.status(400).json({ error: 'discovery_failed', detail: outcome.error })
+ res
+ .status(discoveryHttpStatus(outcome.error))
+ .json({ error: 'discovery_failed', detail: outcome.error })
return
}
const discovery = outcome.result