Skip to content

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

TypeScript

feat(rpc-proxy): u5 forward mcp-oauth authorize-url mint

Diego Zacariasd79f380872c7
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index 28b697415..0ae0271d3 100644
--- a/external-rest-api/src/releaseManifest.ts
+++ b/external-rest-api/src/releaseManifest.ts
@@ -9,7 +9,7 @@ export type ReleaseManifest = {
export const releaseManifest: ReleaseManifest = {
releaseId: 'v0.6.0',
externalRestApiVersion: '0.1.63',
- rpcProxyVersion: '0.1.62',
+ rpcProxyVersion: '0.1.63',
desktopVersion: '0.6.0',
minimumDesktopVersion: '0.1.252',
}
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index 3df46e144..f7c851d59 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.62",
+ "version": "0.1.63",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.62",
+ "version": "0.1.63",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index 0434e0acc..1a04ed372 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.62",
+ "version": "0.1.63",
"description": "External-facing RPC proxy for tenant-scoped MCP access",
"main": "dist/main.js",
"engines": {
diff --git a/rpc-proxy/src/app.ts b/rpc-proxy/src/app.ts
index 178b45ea7..5cb5bf351 100644
--- a/rpc-proxy/src/app.ts
+++ b/rpc-proxy/src/app.ts
@@ -3,6 +3,7 @@ import cors from 'cors'
import { config } from './config.js'
import { createDesktopRouter } from './routes/desktopProxy.js'
import { createHealthRouter } from './routes/health.js'
+import { createMcpOauthRouter } from './routes/mcpOauth.js'
import { createRpcRouter } from './routes/rpc.js'
import { createRpcHostActivityStreamRouter } from './routes/rpcHostActivityStream.js'
import { createRpcHostProgressStreamRouter } from './routes/rpcHostProgressStream.js'
@@ -40,6 +41,7 @@ export function createApp() {
api.use(createRpcHostProgressStreamRouter())
api.use(createDesktopRouter())
api.use(createSandboxUiSessionRouter())
+ api.use(createMcpOauthRouter())
app.use('/api/v1', api)
app.use((_req, res) => {
diff --git a/rpc-proxy/src/routes/mcpOauth.test.ts b/rpc-proxy/src/routes/mcpOauth.test.ts
new file mode 100644
index 000000000..6c2869d18
--- /dev/null
+++ b/rpc-proxy/src/routes/mcpOauth.test.ts
@@ -0,0 +1,142 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { createMcpOauthRouter } from './mcpOauth.js'
+
+const authTokenMock = vi.hoisted(() => ({ verifyRpcToken: vi.fn() }))
+vi.mock('../authToken.js', () => authTokenMock)
+
+const VALID_CLAIMS = {
+ sub: 'user-uuid-123',
+ typ: 'user' as const,
+ accessScope: 'team' as const,
+ teamId: 'team-1',
+ scopes: ['mcp:server:invoke'],
+ hostRefs: ['h'],
+ jti: 'j1',
+ iat: 1,
+ exp: 9999999999,
+}
+
+const fetchSpy = vi.fn()
+
+function makeApp() {
+ const app = express()
+ app.use(express.json())
+ app.use('/api/v1', createMcpOauthRouter())
+ return app
+}
+
+function jsonResponse(status: number, body: unknown): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json' },
+ })
+}
+
+const PATH = '/api/v1/mcp-oauth/gdrive/authorize-url'
+
+beforeEach(() => {
+ authTokenMock.verifyRpcToken.mockReset()
+ authTokenMock.verifyRpcToken.mockReturnValue({ ...VALID_CLAIMS })
+ fetchSpy.mockReset()
+ vi.stubGlobal('fetch', fetchSpy)
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('POST /api/v1/mcp-oauth/:mcpServerName/authorize-url', () => {
+ it('401 without a valid RPC JWT', async () => {
+ authTokenMock.verifyRpcToken.mockReturnValue(null)
+ await request(makeApp()).post(PATH).expect(401)
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+
+ it('403 when the token lacks the mcp:server:invoke scope', async () => {
+ authTokenMock.verifyRpcToken.mockReturnValue({ ...VALID_CLAIMS, scopes: ['sandbox:ui:view'] })
+ await request(makeApp()).post(PATH).set('Authorization', 'Bearer t').expect(403)
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+
+ it('400 for a malformed (non-k8s) server name, before any forward', async () => {
+ const res = await request(makeApp())
+ .post('/api/v1/mcp-oauth/Foo_Bar/authorize-url')
+ .set('Authorization', 'Bearer t')
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('invalid_request')
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+
+ it('forwards userId=auth.sub (NOT the body) and returns { authorizeUrl } on 200', async () => {
+ fetchSpy.mockResolvedValue(
+ jsonResponse(200, { authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth?state=x' })
+ )
+ const res = await request(makeApp())
+ .post(PATH)
+ .set('Authorization', 'Bearer t')
+ // A body userId MUST be ignored — identity comes from auth.sub.
+ .send({ userId: 'attacker', contextId: 'ctx-A' })
+
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual({
+ authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth?state=x',
+ })
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
+ expect(url).toContain('/internal/mcp-oauth/authorize-url')
+ const headers = init.headers as Record<string, string>
+ expect(headers['x-service-token']).toBeTruthy()
+ expect(headers.authorization).toMatch(/^Bearer /)
+ const forwarded = JSON.parse(String(init.body))
+ expect(forwarded.mcpServerName).toBe('gdrive')
+ expect(forwarded.userId).toBe('user-uuid-123') // auth.sub, NOT 'attacker'
+ expect(forwarded.contextId).toBe('ctx-A')
+ })
+
+ it('omits contextId from the forward when the body has none', async () => {
+ fetchSpy.mockResolvedValue(jsonResponse(200, { authorizeUrl: 'https://accounts.google.com/x' }))
+ await request(makeApp()).post(PATH).set('Authorization', 'Bearer t').send({})
+ const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
+ const forwarded = JSON.parse(String(init.body))
+ expect('contextId' in forwarded).toBe(false)
+ })
+
+ it('propagates a 403 context_membership_denied from control-api verbatim', async () => {
+ fetchSpy.mockResolvedValue(jsonResponse(403, { error: 'context_membership_denied' }))
+ const res = await request(makeApp()).post(PATH).set('Authorization', 'Bearer t').send({})
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('context_membership_denied')
+ expect(res.body.authorizeUrl).toBeUndefined()
+ })
+
+ it('propagates a 404 server_not_found from control-api verbatim', async () => {
+ fetchSpy.mockResolvedValue(jsonResponse(404, { error: 'server_not_found' }))
+ const res = await request(makeApp()).post(PATH).set('Authorization', 'Bearer t').send({})
+ expect(res.status).toBe(404)
+ expect(res.body.error).toBe('server_not_found')
+ })
+
+ it('coerces a control-api 401 (service-token misconfig) to 502, not the user auth failure', async () => {
+ fetchSpy.mockResolvedValue(jsonResponse(401, { error: 'Unauthorized' }))
+ const res = await request(makeApp()).post(PATH).set('Authorization', 'Bearer t').send({})
+ expect(res.status).toBe(502)
+ expect(res.body.error).toBe('control_api_auth_failed')
+ })
+
+ it('returns 502 when control-api is unreachable', async () => {
+ fetchSpy.mockRejectedValue(new Error('ECONNREFUSED'))
+ const res = await request(makeApp()).post(PATH).set('Authorization', 'Bearer t').send({})
+ expect(res.status).toBe(502)
+ expect(res.body.error).toBe('control_api_unreachable')
+ })
+
+ it('returns 502 when control-api 200 body lacks a usable authorizeUrl', async () => {
+ fetchSpy.mockResolvedValue(jsonResponse(200, { authorizeUrl: '' }))
+ const res = await request(makeApp()).post(PATH).set('Authorization', 'Bearer t').send({})
+ expect(res.status).toBe(502)
+ expect(res.body.error).toBe('control_api_invalid_response')
+ })
+})
diff --git a/rpc-proxy/src/routes/mcpOauth.ts b/rpc-proxy/src/routes/mcpOauth.ts
new file mode 100644
index 000000000..4b972d8a6
--- /dev/null
+++ b/rpc-proxy/src/routes/mcpOauth.ts
@@ -0,0 +1,120 @@
+import { Response, Router } from 'express'
+import { config } from '../config.js'
+import { AuthedRequest, requireRpcAuth, requireScope } from '../middleware/auth.js'
+
+/**
+ * POST /api/v1/mcp-oauth/:mcpServerName/authorize-url
+ *
+ * Desktop "Connect <server>" surface (U5 reactive OAuth). After a tool-call
+ * against an OAuth mcp-server returns `connect_required`, the desktop main
+ * process calls this to mint a fresh provider authorize-URL, then
+ * `shell.openExternal`s it so the user consents in the OS browser.
+ *
+ * Auth chain:
+ * 1. `requireRpcAuth` — RPC JWT (RS256, iss=control-api, aud=rpc-proxy).
+ * 2. `requireScope('mcp:server:invoke')` — the SAME capability the desktop
+ * already holds to invoke mcp tools (rpc.ts). Connecting is a precondition
+ * of invoking, so no new scope is issued (would be a token-issuance change
+ * in control-api).
+ *
+ * rpc-proxy forwards IDENTITY only. control-api owns the server→context
+ * resolution and the Context-membership rule (D4, one source of truth); this
+ * route never resolves a server's Context on its own. The `userId` is taken
+ * from `req.auth.sub`, never the body. An optional body `{ contextId? }` is
+ * forwarded for control-api to cross-check against the server's authoritative
+ * `spec.contextRef`.
+ *
+ * Error propagation from control-api's internal mint endpoint:
+ * - 401 → rpc-proxy↔control-api service-token misconfig (control-api answers
+ * 401 on a bad/absent service token) → coerce to 502 so the user does not
+ * read it as their own credential failure;
+ * - 403 → legitimate `context_membership_denied` → propagate verbatim;
+ * - 404 (`server_not_found`) / 400 (`not_oauth_server`, `context_mismatch`,
+ * `server_missing_context`) / 503 (`integration_not_configured`) →
+ * propagate verbatim;
+ * - 200 → `{ authorizeUrl }`.
+ */
+
+// DNS-1123 subdomain — the shape a k8s resource name takes.
+const K8S_NAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/
+function isValidK8sName(name: string): boolean {
+ return name.length > 0 && name.length <= 253 && K8S_NAME_RE.test(name)
+}
+
+export function createMcpOauthRouter(): Router {
+ const router = Router()
+
+ router.post(
+ '/mcp-oauth/:mcpServerName/authorize-url',
+ requireRpcAuth,
+ requireScope('mcp:server:invoke'),
+ async (req: AuthedRequest, res: Response) => {
+ const { mcpServerName } = req.params
+ if (!isValidK8sName(mcpServerName)) {
+ res.status(400).json({ error: 'invalid_request' })
+ return
+ }
+ const userId = req.auth!.sub
+ const contextId =
+ typeof req.body?.contextId === 'string' && req.body.contextId.trim().length > 0
+ ? String(req.body.contextId).trim()
+ : undefined
+
+ const upstreamUrl = `${config.controlApiBaseUrl.replace(/\/+$/, '')}/internal/mcp-oauth/authorize-url`
+ let upstream: globalThis.Response
+ try {
+ upstream = await fetch(upstreamUrl, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${config.controlApiServiceToken}`,
+ 'x-service-token': config.controlApiServiceName,
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({
+ mcpServerName,
+ userId, // from req.auth.sub — never the body
+ ...(contextId ? { contextId } : {}),
+ }),
+ signal: AbortSignal.timeout(config.upstreamTimeoutMs),
+ })
+ } catch {
+ res.status(502).json({ error: 'control_api_unreachable' })
+ return
+ }
+
+ // 401 = service-token misconfig (control-api's requireInternalToken /
+ // requireInternalService both answer 401). Do NOT surface as the user's
+ // own auth failure. 403 IS a legitimate membership denial → propagate.
+ if (upstream.status === 401) {
+ res.status(502).json({ error: 'control_api_auth_failed' })
+ return
+ }
+
+ const upstreamText = await upstream.text().catch(() => '')
+
+ if (upstream.ok) {
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(upstreamText)
+ } catch {
+ parsed = null
+ }
+ const authorizeUrl = (parsed as { authorizeUrl?: unknown } | null)?.authorizeUrl
+ if (typeof authorizeUrl !== 'string' || !authorizeUrl) {
+ res.status(502).json({ error: 'control_api_invalid_response' })
+ return
+ }
+ res.status(200).json({ authorizeUrl })
+ return
+ }
+
+ // Forward the upstream JSON error verbatim.
+ res
+ .status(upstream.status)
+ .type(upstream.headers.get('content-type') ?? 'application/json')
+ .send(upstreamText)
+ }
+ )
+
+ return router
+}