Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(external-rest-api): mirror the per-server remote OAuth callback route
Diego Zacarias70655310f7e1
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.jsonindex 81c281065..c47638178 100644--- a/external-rest-api/package-lock.json+++ b/external-rest-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-external-rest-api",- "version": "0.1.85",+ "version": "0.1.86","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-external-rest-api",- "version": "0.1.85",+ "version": "0.1.86","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/external-rest-api/package.json b/external-rest-api/package.jsonindex ce716823a..01619c163 100644--- a/external-rest-api/package.json+++ b/external-rest-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-external-rest-api",- "version": "0.1.85",+ "version": "0.1.86","description": "External REST API for profile, team management, and RPC token brokerage","main": "dist/main.js","engines": {diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.tsindex 338f898a4..499d9d7fa 100644--- a/external-rest-api/src/releaseManifest.ts+++ b/external-rest-api/src/releaseManifest.ts@@ -8,7 +8,7 @@ export type ReleaseManifest = {export const releaseManifest: ReleaseManifest = {releaseId: 'v0.10.0',- externalRestApiVersion: '0.1.85',+ externalRestApiVersion: '0.1.86',rpcProxyVersion: '0.1.94',desktopVersion: '0.10.0',minimumDesktopVersion: '0.1.252',diff --git a/external-rest-api/src/routes/__tests__/oauthCallback.test.ts b/external-rest-api/src/routes/__tests__/oauthCallback.test.tsindex 98a69acf5..8d19b3809 100644--- a/external-rest-api/src/routes/__tests__/oauthCallback.test.ts+++ b/external-rest-api/src/routes/__tests__/oauthCallback.test.ts@@ -1,4 +1,6 @@-import { describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'+import http from 'node:http'+import type { AddressInfo } from 'node:net'import request from 'supertest'import { createApp } from '../../app.js'import * as client from '../../controlApiClient.js'@@ -67,3 +69,142 @@ describe('oauth-callback passthrough', () => {spy.mockRestore()})})++// supertest resolves the URL through WHATWG URL, which collapses `%2e%2e` dot+// segments before sending. A proxy or a hand-crafted request does not, so the+// rejection cases go out over a raw socket with the path exactly as written.+async function rawGet(path: string): Promise<{ status: number }> {+ const server = createApp().listen(0)+ try {+ await new Promise<void>(resolve => server.once('listening', resolve))+ const { port } = server.address() as AddressInfo+ return await new Promise((resolve, reject) => {+ const req = http.request({ host: '127.0.0.1', port, path, method: 'GET' }, res => {+ res.resume()+ res.on('end', () => resolve({ status: res.statusCode ?? 0 }))+ })+ req.on('error', reject)+ req.end()+ })+ } finally {+ await new Promise<void>(resolve => server.close(() => resolve()))+ }+}++describe('oauth-callback passthrough — per-server remote route', () => {+ const NONCE = '3f2b8c1e-9a4d-4e7f-8b21-5c6d7e8f9a0b'++ afterEach(() => {+ vi.restoreAllMocks()+ })++ function mockControlApi() {+ return vi+ .spyOn(client, 'controlApiPassthroughGet')+ .mockResolvedValue({ status: 200, contentType: 'text/html', body: 'ok' })+ }++ it('forwards a one-segment per-server callback to the exact path with the raw query', async () => {+ const spy = mockControlApi()++ const res = await request(createApp()).get(+ '/api/v1/oauth-callback/remote/atlassian?state=S&code=C&scope=a%20b'+ )++ expect(res.status).toBe(200)+ expect(res.text).toBe('ok')+ expect(spy).toHaveBeenCalledTimes(1)+ expect(spy).toHaveBeenCalledWith(+ '/oauth-callback/remote/atlassian',+ '?state=S&code=C&scope=a%20b'+ )+ spy.mockRestore()+ })++ it('forwards a two-segment (serverName + installNonce) callback to the exact path', async () => {+ const spy = mockControlApi()++ const res = await request(createApp()).get(+ `/api/v1/oauth-callback/remote/my-server-1/${NONCE}?state=S&code=C`+ )++ expect(res.status).toBe(200)+ expect(spy).toHaveBeenCalledTimes(1)+ expect(spy).toHaveBeenCalledWith(+ `/oauth-callback/remote/my-server-1/${NONCE}`,+ '?state=S&code=C'+ )+ spy.mockRestore()+ })++ it('preserves a repeated iss verbatim so control-api can reject it', async () => {+ const spy = mockControlApi()++ await request(createApp()).get(+ `/api/v1/oauth-callback/remote/atlassian/${NONCE}?code=C&state=S&iss=a&iss=b`+ )++ expect(spy).toHaveBeenCalledWith(+ `/oauth-callback/remote/atlassian/${NONCE}`,+ '?code=C&state=S&iss=a&iss=b'+ )+ spy.mockRestore()+ })++ it('accepts a 63-char server name (RFC 1123 label upper bound)', async () => {+ const spy = mockControlApi()+ const name = `a${'b'.repeat(61)}c`++ const res = await request(createApp()).get(`/api/v1/oauth-callback/remote/${name}?code=C`)++ expect(res.status).toBe(200)+ expect(spy).toHaveBeenCalledWith(`/oauth-callback/remote/${name}`, '?code=C')+ spy.mockRestore()+ })++ it('keeps the shared remote callback on the one-segment route', async () => {+ const spy = mockControlApi()++ await request(createApp()).get(+ '/api/v1/oauth-callback/remote?code=C&state=S&iss=https%3A%2F%2Fas'+ )++ expect(spy).toHaveBeenCalledWith(+ '/oauth-callback/remote',+ '?code=C&state=S&iss=https%3A%2F%2Fas'+ )+ spy.mockRestore()+ })++ const rejected: Array<[string, string]> = [+ ['encoded slash traversal', '/api/v1/oauth-callback/remote/..%2Fadmin?code=C'],+ [+ 'encoded slash traversal after a valid name',+ `/api/v1/oauth-callback/remote/foo/..%2F..%2Fadmin?code=C`,+ ],+ ['encoded dot-dot', '/api/v1/oauth-callback/remote/%2e%2e?code=C'],+ ['encoded dot-dot as nonce', '/api/v1/oauth-callback/remote/foo/%2e%2e?code=C'],+ ['double-encoded slash', '/api/v1/oauth-callback/remote/foo%252Fbar?code=C'],+ ['double-encoded slash as nonce', `/api/v1/oauth-callback/remote/foo/${NONCE}%252F?code=C`],+ ['uppercase UUID nonce', `/api/v1/oauth-callback/remote/foo/${NONCE.toUpperCase()}?code=C`],+ ['non-UUID nonce', '/api/v1/oauth-callback/remote/foo/not-a-uuid?code=C'],+ ['UUID without hyphens', `/api/v1/oauth-callback/remote/foo/${NONCE.replace(/-/g, '')}?code=C`],+ ['uppercase server name', '/api/v1/oauth-callback/remote/Atlassian?code=C'],+ ['leading hyphen', '/api/v1/oauth-callback/remote/-foo?code=C'],+ ['trailing hyphen', '/api/v1/oauth-callback/remote/foo-?code=C'],+ ['64-char server name', `/api/v1/oauth-callback/remote/${'a'.repeat(64)}?code=C`],+ ['empty server name before a nonce', `/api/v1/oauth-callback/remote//${NONCE}?code=C`],+ ['dot in server name', '/api/v1/oauth-callback/remote/foo.bar?code=C'],+ ['underscore in server name', '/api/v1/oauth-callback/remote/foo_bar?code=C'],+ ['extra third segment', `/api/v1/oauth-callback/remote/foo/${NONCE}/extra?code=C`],+ ]++ it.each(rejected)('404s without contacting control-api: %s', async (_label, url) => {+ const spy = mockControlApi()++ const res = await rawGet(url)++ expect(res.status).toBe(404)+ expect(spy).not.toHaveBeenCalled()+ })+})diff --git a/external-rest-api/src/routes/oauthCallback.ts b/external-rest-api/src/routes/oauthCallback.tsindex 354d21ad8..bd2f47f89 100644--- a/external-rest-api/src/routes/oauthCallback.ts+++ b/external-rest-api/src/routes/oauthCallback.ts@@ -1,6 +1,18 @@-import { Router } from 'express'+import { type Request, Router } from 'express'import { controlApiPassthroughGet } from '../controlApiClient.js'+// Same shape control-api accepts for a remote MCP server name (a K8s resource+// name): lowercase RFC 1123 label, 1-63 chars, no leading/trailing hyphen.+const REMOTE_SERVER_NAME_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/+// Lowercase only: control-api mints the nonce with crypto.randomUUID(), which is+// always lowercase, so any other casing is not a redirect URI it ever registered.+const INSTALL_NONCE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/++function rawQueryOf(req: Request): string {+ const queryStart = req.originalUrl.indexOf('?')+ return queryStart >= 0 ? req.originalUrl.slice(queryStart) : ''+}+/*** PUBLIC OAuth callback. The provider (Google, …) redirects the user's browser* here after consent — there is no Clerum session or bearer token; authentication@@ -10,19 +22,43 @@ import { controlApiPassthroughGet } from '../controlApiClient.js'* response, including the HTML success page that bounces to clerum://oauth-completed.** This is the only public, unauthenticated route in this gateway, so it MUST stay a- * thin passthrough: never read or trust anything beyond the path oauthClientId and- * the opaque query string.+ * thin passthrough: never read or trust anything beyond the validated path segments+ * and the opaque query string.*/export function createOauthCallbackRouter(): Router {const router = Router()+ // Per-server remote callback (/remote/<serverName>[/<installNonce>]). The forward+ // carries this gateway's service token, so an unvalidated segment (e.g. a decoded+ // `../admin`) would turn a public URL into an authenticated GET against any+ // control-api path. Segments are therefore allow-listed before anything is sent,+ // and the forwarded path is rebuilt only from them.+ router.get('/oauth-callback/remote/:serverName/:installNonce?', async (req, res, next) => {+ const serverName = String(req.params.serverName)+ const installNonce = req.params.installNonce+ if (+ !REMOTE_SERVER_NAME_RE.test(serverName) ||+ (installNonce !== undefined && !INSTALL_NONCE_RE.test(installNonce))+ ) {+ res.status(404).json({ error: 'Not Found' })+ return+ }+ try {+ const path =+ `/oauth-callback/remote/${encodeURIComponent(serverName)}` ++ (installNonce !== undefined ? `/${encodeURIComponent(installNonce)}` : '')+ const result = await controlApiPassthroughGet(path, rawQueryOf(req))+ res.status(result.status).type(result.contentType).send(result.body)+ } catch (err) {+ next(err)+ }+ })+router.get('/oauth-callback/:oauthClientId', async (req, res, next) => {try {- const queryStart = req.originalUrl.indexOf('?')- const rawQueryString = queryStart >= 0 ? req.originalUrl.slice(queryStart) : ''const result = await controlApiPassthroughGet(`/oauth-callback/${encodeURIComponent(String(req.params.oauthClientId))}`,- rawQueryString+ rawQueryOf(req))res.status(result.status).type(result.contentType).send(result.body)} catch (err) {