Skip to content

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

TypeScript

feat(control-api): serve generic credential manifest and POST /admin/oauth/discover

Diego Zacarias9ccd99bb4680
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index beaecc0fd..8fa990243 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.608",
+ "version": "0.1.609",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.608",
+ "version": "0.1.609",
"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 9919d7f2e..6b17fc92c 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.608",
+ "version": "0.1.609",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/oauth/providers.ts b/control-api/src/oauth/providers.ts
index 8a6976b51..15a793e4f 100644
--- a/control-api/src/oauth/providers.ts
+++ b/control-api/src/oauth/providers.ts
@@ -930,3 +930,37 @@ const CREDENTIAL_MANIFESTS: Record<OAuthProvider, ReadonlyArray<OAuthCredentialF
export function getCredentialManifest(provider: OAuthProvider): OAuthCredentialField[] {
return CREDENTIAL_MANIFESTS[provider].map(field => ({ ...field }))
}
+
+// ─── Generic self-hosted OAuth credential manifest (E-16.3, S3-B4) ───────────
+//
+// Kept OUT of `CREDENTIAL_MANIFESTS` (typed to the frozen `OAuthProvider` enum):
+// 'generic' is a sentinel, never a provider. The dynamic-manifest of E-16.3
+// materialises as: PUBLIC client ⇒ no credentials asked (the wizard shows no
+// credential fields and the client_id IS oauth.id, DA-1); CONFIDENTIAL client ⇒
+// this manifest. The public/confidential selector lives in the wizard and the
+// install saga arbitrates (tokenAuthMethod=basic forces confidential).
+const GENERIC_CREDENTIAL_MANIFEST: ReadonlyArray<OAuthCredentialField> = [
+ {
+ name: 'client_id',
+ label: 'Client ID',
+ secret: false,
+ required: true,
+ help: 'Confidential client only. In public mode no credentials are stored and the client_id is derived from the server name.',
+ },
+ {
+ name: 'client_secret',
+ label: 'Client Secret',
+ secret: true,
+ required: true,
+ help: 'Confidential client only (required when tokenAuthMethod is basic).',
+ },
+]
+
+/**
+ * The credential-form manifest for the generic carril (confidential mode). Defensive
+ * copy, same as {@link getCredentialManifest}. No `OAuthProvider` argument — 'generic'
+ * is not a baked provider.
+ */
+export function getGenericCredentialManifest(): OAuthCredentialField[] {
+ return GENERIC_CREDENTIAL_MANIFEST.map(field => ({ ...field }))
+}
diff --git a/control-api/src/routes/admin/oauthProviders.ts b/control-api/src/routes/admin/oauthProviders.ts
index 1b229247e..f7b2b6657 100644
--- a/control-api/src/routes/admin/oauthProviders.ts
+++ b/control-api/src/routes/admin/oauthProviders.ts
@@ -1,25 +1,54 @@
import { Router } from 'express'
+import { z } from 'zod'
import { asyncHandler } from '../../http/asyncHandler.js'
-import { getCredentialManifest, isKnownOAuthProvider } from '../../oauth/providers.js'
+import { validateOAuthEndpointUrl } from '../../http/validateMcpServerSpec.js'
+import {
+ buildGenericDiscoveryPrefill,
+ discoverAuthorizationServerMetadata,
+} from '../../oauth/discovery.js'
+import { discoveryHttpStatus } from '../../oauth/discoveryHttpStatus.js'
+import {
+ getCredentialManifest,
+ getGenericCredentialManifest,
+ isKnownOAuthProvider,
+} from '../../oauth/providers.js'
+import { rootLogger } from '../../observability/logger.js'
+
+const log = rootLogger.child({ module: 'admin-oauth-providers' })
+
+const discoverBodySchema = z.object({ url: z.string().min(1) })
+
+/**
+ * Injectable dependency for the generic discovery endpoint (test seam only).
+ * Production leaves it undefined → the real IP-pinned `discoverAuthorizationServerMetadata`
+ * is used; tests inject a wrapper that supplies a `transport`/`resolveDns` so the pin
+ * runs with no real network.
+ */
+export interface AdminOauthProvidersDeps {
+ discover?: typeof discoverAuthorizationServerMetadata
+}
/**
- * Admin router for OAuth provider metadata consumed by the install-from-UI
- * wizard (Slice 1, S1-U2). Today it serves only the per-provider credential
- * manifest; the `POST /admin/oauth/discover` prefill endpoint (D-A6) lands here
- * in Slice 3 alongside the `'generic'` adapter.
+ * Admin router for OAuth provider metadata consumed by the install-from-UI wizard.
+ * Serves the per-provider credential manifest (baked + generic) and the generic
+ * discovery-as-prefill endpoint (D-A6, E-19.5).
*/
-export function createAdminOauthProvidersRouter(): Router {
+export function createAdminOauthProvidersRouter(deps: AdminOauthProvidersDeps = {}): Router {
const router = Router()
+ const discover = deps.discover ?? discoverAuthorizationServerMetadata
// GET /admin/oauth/providers/:id/credential-manifest
- // Returns the credential-form field list for a baked provider so control-ui
- // can render the install form. 404 for an unknown provider id — Slice 1 only
- // serves the 8 baked adapters (isKnownOAuthProvider is the single source of
- // truth, derived from ADAPTERS).
+ // Returns the credential-form field list so control-ui can render the install form.
+ // 'generic' is served (confidential manifest) BEFORE the baked gate; every other
+ // unknown id 404s (isKnownOAuthProvider is the single source of truth for baked).
router.get(
'/admin/oauth/providers/:id/credential-manifest',
asyncHandler(async (req, res) => {
const id = req.params.id
+ if (id === 'generic') {
+ res.status(200).json({ provider: 'generic', fields: getGenericCredentialManifest() })
+ return
+ }
if (!isKnownOAuthProvider(id)) {
res.status(404).json({ error: `Unknown OAuth provider "${id}"` })
return
@@ -28,5 +57,38 @@ export function createAdminOauthProvidersRouter(): Router {
})
)
+ // POST /admin/oauth/discover — dry-run generic AS discovery, no writes (D-A6/E-19.5).
+ router.post(
+ '/admin/oauth/discover',
+ asyncHandler(async (req, res) => {
+ const parsed = discoverBodySchema.safeParse(req.body)
+ if (!parsed.success) {
+ res.status(400).json({ error: 'url is required' })
+ return
+ }
+ const { url } = parsed.data
+
+ // Kernel §4: the admin-typed URL is untrusted input of origin — validate before
+ // any fetch (discovery also kernel-guards internally, but a clean 400 here gives
+ // the wizard immediate, field-level feedback).
+ const kernelErrors = await validateOAuthEndpointUrl(url, 'url')
+ if (kernelErrors.length > 0) {
+ res.status(400).json({ error: kernelErrors[0].message, errors: kernelErrors })
+ return
+ }
+
+ const outcome = await discover(url, { logger: log })
+ if (!outcome.ok) {
+ log.warn({ discovery: outcome.error.kind }, 'generic discovery (dry-run) failed')
+ res
+ .status(discoveryHttpStatus(outcome.error))
+ .json({ error: 'discovery_failed', detail: outcome.error })
+ return
+ }
+
+ res.status(200).json(buildGenericDiscoveryPrefill(outcome.result))
+ })
+ )
+
return router
}
diff --git a/control-api/test/routes.oauthProviders.test.ts b/control-api/test/routes.oauthProviders.test.ts
index bff972772..5bf2373b1 100644
--- a/control-api/test/routes.oauthProviders.test.ts
+++ b/control-api/test/routes.oauthProviders.test.ts
@@ -1,12 +1,27 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
-import { createAdminOauthProvidersRouter } from '../src/routes/admin/oauthProviders.js'
+import type { PinnedTransport } from '../src/http/pinnedFetch.js'
+import { discoverAuthorizationServerMetadata } from '../src/oauth/discovery.js'
+import {
+ type AdminOauthProvidersDeps,
+ createAdminOauthProvidersRouter,
+} from '../src/routes/admin/oauthProviders.js'
+import { NOTION_AS_JSON } from './fixtures/remoteOAuthDiscovery.js'
-function makeApp() {
+// Route-level kernel §4 uses the default DNS resolver — mock it to a public IP so
+// syntactically-public hosts pass without a real lookup (internal hosts are rejected
+// pre-DNS regardless).
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn(async () => [{ address: '93.184.216.34', family: 4 }]),
+}))
+
+const PUBLIC_IP = ['93.184.216.34']
+
+function makeApp(deps: AdminOauthProvidersDeps = {}) {
const app = express()
app.use(express.json())
- app.use(createAdminOauthProvidersRouter())
+ app.use(createAdminOauthProvidersRouter(deps))
app.use(
(err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })
@@ -15,13 +30,32 @@ function makeApp() {
return app
}
+/** Transport that serves ONE AS well-known URL, 404 elsewhere. */
+function asOnlyTransport(asWellKnownUrl: string, json: string): PinnedTransport {
+ return async ({ url }: { url: string }) => {
+ if (url === asWellKnownUrl) {
+ return { status: 200, headers: { 'content-type': 'application/json' }, bodyText: json }
+ }
+ return { status: 404, headers: {}, bodyText: 'not found' }
+ }
+}
+
+/** A `discover` seam that supplies a transport + resolveDns so no real network runs. */
+function discoverWith(transport: PinnedTransport): AdminOauthProvidersDeps['discover'] {
+ return (url, d) =>
+ discoverAuthorizationServerMetadata(url, {
+ ...d,
+ transport,
+ resolveDns: vi.fn(async () => PUBLIC_IP),
+ })
+}
+
describe('GET /admin/oauth/providers/:id/credential-manifest', () => {
it('returns the manifest for a known baked provider', async () => {
const res = await request(makeApp())
.get('/admin/oauth/providers/google/credential-manifest')
.expect(200)
expect(res.body.provider).toBe('google')
- expect(Array.isArray(res.body.fields)).toBe(true)
const names = res.body.fields.map((f: { name: string }) => f.name)
expect(names).toContain('client_id')
expect(names).toContain('client_secret')
@@ -34,7 +68,72 @@ describe('GET /admin/oauth/providers/:id/credential-manifest', () => {
expect(res.body.error).toMatch(/Unknown OAuth provider/)
})
- it("404s for the 'generic' sentinel (Slice 1 serves only the 8 baked)", async () => {
- await request(makeApp()).get('/admin/oauth/providers/generic/credential-manifest').expect(404)
+ // S3-B4: the generic manifest is now served (confidential fields). Was 404.
+ it("returns the confidential manifest for the 'generic' carril", async () => {
+ const res = await request(makeApp())
+ .get('/admin/oauth/providers/generic/credential-manifest')
+ .expect(200)
+ expect(res.body.provider).toBe('generic')
+ const names = res.body.fields.map((f: { name: string }) => f.name)
+ expect(names).toEqual(['client_id', 'client_secret'])
+ // The public-mode hint is carried so the wizard can explain no-credential mode.
+ expect(res.body.fields[0].help).toMatch(/public mode/i)
+ })
+})
+
+describe('POST /admin/oauth/discover (E-19.5)', () => {
+ it('400s when url is missing', async () => {
+ const res = await request(makeApp()).post('/admin/oauth/discover').send({}).expect(400)
+ expect(res.body.error).toMatch(/url is required/)
+ })
+
+ it('kernel-rejects an internal URL before discovery (400, discover not called)', async () => {
+ const discover = vi.fn(discoverWith(asOnlyTransport('x', '{}')))
+ const res = await request(makeApp({ discover }))
+ .post('/admin/oauth/discover')
+ .send({ url: 'https://as.svc.cluster.local' })
+ .expect(400)
+ expect(res.body.errors?.[0]?.field).toBe('url')
+ expect(discover).not.toHaveBeenCalled()
+ })
+
+ it('200 with the generic prefill for a real AS issuer (notion, T1)', async () => {
+ const asWellKnown = 'https://mcp.notion.com/.well-known/oauth-authorization-server'
+ const res = await request(
+ makeApp({ discover: discoverWith(asOnlyTransport(asWellKnown, NOTION_AS_JSON)) })
+ )
+ .post('/admin/oauth/discover')
+ .send({ url: 'https://mcp.notion.com' })
+ .expect(200)
+ expect(res.body.issuer).toBe('https://mcp.notion.com')
+ expect(res.body.endpoints.authorization).toBe('https://mcp.notion.com/authorize')
+ expect(res.body.endpoints.token).toBe('https://mcp.notion.com/token')
+ expect(res.body.suggested.usePkce).toBe(true)
+ expect(res.body.suggested.tokenAuthMethod).toBe('body')
+ expect(res.body.suggested.supportsRefresh).toBe(true)
+ })
+
+ it('maps a transport failure to 502 (discoveryHttpStatus)', async () => {
+ const discover: AdminOauthProvidersDeps['discover'] = async () => ({
+ ok: false,
+ error: { kind: 'fetch_failed', url: 'https://mcp.notion.com', detail: 'boom' },
+ })
+ const res = await request(makeApp({ discover }))
+ .post('/admin/oauth/discover')
+ .send({ url: 'https://mcp.notion.com' })
+ .expect(502)
+ expect(res.body.error).toBe('discovery_failed')
+ expect(res.body.detail.kind).toBe('fetch_failed')
+ })
+
+ it('maps an invalid-metadata failure to 400', async () => {
+ const discover: AdminOauthProvidersDeps['discover'] = async () => ({
+ ok: false,
+ error: { kind: 'invalid_metadata', url: 'https://mcp.notion.com', detail: 'bad' },
+ })
+ await request(makeApp({ discover }))
+ .post('/admin/oauth/discover')
+ .send({ url: 'https://mcp.notion.com' })
+ .expect(400)
})
})