Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): accept DCR confidential->public downgrade from the authorization server
Diego Zacarias1721a1f6a022
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 46b5a4117..32b011270 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.613",+ "version": "0.1.614","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.613",+ "version": "0.1.614","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.jsonindex 65faa571e..d212d7c77 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.613",+ "version": "0.1.614","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/dcr.ts b/control-api/src/oauth/dcr.tsindex e7cbe6faa..d3e06e9be 100644--- a/control-api/src/oauth/dcr.ts+++ b/control-api/src/oauth/dcr.ts@@ -93,7 +93,19 @@ export type DcrError =| { kind: 'content_encoding_rejected'; url: string; encoding: string }export type DcrOutcome =- | { ok: true; response: DcrRegistrationResponse }+ | {+ ok: true+ response: DcrRegistrationResponse+ /**+ * The auth method that actually governs the minted client — the AS's+ * assignment when it overrode our request, else what we asked for. The AS is+ * the final authority (RFC 7591), so a confidential request the AS downgrades+ * to `none` yields `effectiveAuthMethod: 'none'` here, NOT what we requested.+ */+ effectiveAuthMethod: 'none' | 'client_secret_post'+ /** `public` iff `effectiveAuthMethod` is `none`; the caller persists THIS mode. */+ effectiveClientMode: 'public' | 'confidential'+ }| { ok: false; error: DcrError }export interface DcrDeps {@@ -248,11 +260,15 @@ export async function registerDynamicClient(const assigned = parsed as DcrRegistrationResponse// Fail-closed on an auth method we cannot present. The AS's assignment wins over- // what we requested; a bare absence means it honored our request.+ // what we requested; a bare absence (undefined/null) means it honored our request.+ // The AS response is untrusted, so we reject anything that is NOT a presentable+ // string here — an un-presentable method (e.g. client_secret_basic) OR a non-string+ // the AS injected (e.g. a number/object). Both fail closed to `auth_method_unsupported`+ // so a garbage value never reaches the effective-mode cast/derivation below.const effectiveAuthMethod =assigned.token_endpoint_auth_method ?? request.token_endpoint_auth_methodif (- typeof effectiveAuthMethod === 'string' &&+ typeof effectiveAuthMethod !== 'string' ||!PRESENTABLE_AUTH_METHODS.has(effectiveAuthMethod)) {log.warn(@@ -272,12 +288,18 @@ export async function registerDynamicClient(}}- // A confidential registration MUST hand us a secret; otherwise we would persist- // a client_secret_post client we can never authenticate.- if (- request.token_endpoint_auth_method === 'client_secret_post' &&- typeof assigned.client_secret !== 'string'- ) {+ // Past the PRESENTABLE guard the effective method is one of the two we can present.+ // It — not what we requested — is the final authority on public vs confidential.+ const presentedAuthMethod = effectiveAuthMethod as 'none' | 'client_secret_post'+ const effectiveClientMode: 'public' | 'confidential' =+ presentedAuthMethod === 'none' ? 'public' : 'confidential'++ // A confidential-EFFECTIVE registration MUST hand us a secret; otherwise we would+ // persist a client_secret_post client we can never authenticate. Anchoring this on+ // the EFFECTIVE method (not what we requested) is deliberate: when the AS downgrades+ // a confidential request to public (`none`, no secret), that is a valid public+ // client per RFC 7591 — the AS owns the auth method — not an error (Vercel does this).+ if (effectiveClientMode === 'confidential' && typeof assigned.client_secret !== 'string') {return {ok: false,error: {@@ -292,5 +314,10 @@ export async function registerDynamicClient(}}- return { ok: true, response: assigned }+ return {+ ok: true,+ response: assigned,+ effectiveAuthMethod: presentedAuthMethod,+ effectiveClientMode,+ }}diff --git a/control-api/src/routes/admin/remoteMcp.ts b/control-api/src/routes/admin/remoteMcp.tsindex cc62bf39e..a59ad3724 100644--- a/control-api/src/routes/admin/remoteMcp.ts+++ b/control-api/src/routes/admin/remoteMcp.ts@@ -391,6 +391,13 @@ export function createAdminRemoteMcpRouter(? deriveDcrClientMode(discovery): 'public'+ // For DCR the AS is the final authority on the auth method and may downgrade a+ // confidential request to public. The EFFECTIVE mode — set from the registration+ // outcome below — is what we persist and write to the CR; `clientMode` above is+ // only the a-priori derivation used to shape the request. For non-DCR modes they+ // coincide.+ let effectiveClientMode: 'public' | 'confidential' = clientMode+const targetNs = config.mcpServersNamespaceconst serverName = body.serverNameconst contextRef = body.contextRef@@ -519,6 +526,9 @@ export function createAdminRemoteMcpRouter(}const registration = dcrOutcome.response+ // Honor the AS-assigned auth method end to end: a confidential→public+ // downgrade persists (and writes the CR) as a public client.+ effectiveClientMode = dcrOutcome.effectiveClientMode// Capture the RFC 7592 mint handle BEFORE the local persist. If the persist// throws (pool exhausted, transient, or an encryption error), the client is// already minted at the AS, and `dcrRegistered` has NOT flipped yet — so the@@ -531,8 +541,11 @@ export function createAdminRemoteMcpRouter(...dynamicClientKey,issuer: discovery.issuer,clientId: registration.client_id,- clientMode,- clientSecret: registration.client_secret,+ clientMode: effectiveClientMode,+ // A public client carries no secret; never persist one the AS may have+ // echoed alongside a `none` downgrade.+ clientSecret:+ effectiveClientMode === 'confidential' ? registration.client_secret : undefined,registrationAccessToken: registration.registration_access_token,registrationClientUri: registration.registration_client_uri,clientIdIssuedAtSec: registration.client_id_issued_at,@@ -579,7 +592,7 @@ export function createAdminRemoteMcpRouter(event: 'remote_oauth_dynamic_client_registered',serverName,namespace: targetNs,- clientMode,+ clientMode: effectiveClientMode,hasRegistrationClientUri: Boolean(dcrRegistrationClientUri),},'remote oauth dynamic client registered'@@ -617,7 +630,7 @@ export function createAdminRemoteMcpRouter(}const oauthSpec = buildRemoteOAuthSpec(discovery, {- clientMode,+ clientMode: effectiveClientMode,grantScope,clientSecretName,...(dcrClientId ? { dynamicClientId: dcrClientId } : {}),@@ -652,7 +665,7 @@ export function createAdminRemoteMcpRouter(// ── Saga step 1: create the client Secret (confidential only) ─────────let secretCreated = false- if (clientMode === 'confidential' && clientSecretName) {+ if (effectiveClientMode === 'confidential' && clientSecretName) {try {await gateway.createSecret({name: clientSecretName,@@ -768,7 +781,7 @@ export function createAdminRemoteMcpRouter(serverName,namespace: targetNs,contextRef,- clientMode,+ clientMode: effectiveClientMode,registrationMode: discovery.registrationMode,},'remote oauth mcp server installed'@@ -780,7 +793,7 @@ export function createAdminRemoteMcpRouter(namespace: targetNs,contextRef,contextUpdated: true,- clientMode,+ clientMode: effectiveClientMode,registrationMode: discovery.registrationMode,...(clientSecretName ? { clientSecretName } : {}),})diff --git a/control-api/test/fixtures/remoteOAuthDiscovery.ts b/control-api/test/fixtures/remoteOAuthDiscovery.tsindex 618da961f..d24571aa3 100644--- a/control-api/test/fixtures/remoteOAuthDiscovery.ts+++ b/control-api/test/fixtures/remoteOAuthDiscovery.ts@@ -222,6 +222,46 @@ export const DCR_BASIC_REGISTRATION_RESPONSE = {token_endpoint_auth_method: 'client_secret_basic',} as const+/**+ * The EXACT RFC 7591 §3.2.1 body Vercel returned (HTTP 201) to a confidential+ * (`client_secret_post`) DCR request, captured live from+ * `https://api.vercel.com/login/oauth/register`. Vercel DOWNGRADES the client to+ * public — `token_endpoint_auth_method: "none"`, NO `client_secret` — which is+ * legitimate per RFC 7591 (the AS is the final authority on the auth method): clerum+ * requested confidential only because Vercel's AS metadata omits `none` from+ * `token_endpoint_auth_methods_supported`. Kept as the VERBATIM wire string (not a+ * hand-shaped object) so `registerDynamicClient`'s parse path sees exactly what+ * Vercel emits — the downgrade shape is observed, never invented.+ */+export const DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON =+ '{"client_id":"cl_WbdtcToDrMR4ZHvXLGAmbfoYCsQjMeS8","token_endpoint_auth_method":"none","grant_types":["authorization_code","refresh_token"],"response_types":["code"],"client_name":"Evenfire","redirect_uris":["http://127.0.0.1:8090/api/v1/oauth-callback/remote"]}'++export const DCR_VERCEL_DOWNGRADE_REGISTRATION_RESPONSE = JSON.parse(+ DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON+) as { client_id: string; token_endpoint_auth_method: string; [k: string]: unknown }++/**+ * Adversarial 2xx: a PUBLIC assignment (`token_endpoint_auth_method: "none"`) that+ * ALSO echoes a `client_secret`. The wire shape is the Vercel downgrade body plus an+ * injected `client_secret` — kept as the VERBATIM string, not a hand-shaped object.+ * A public client has no secret, so control-api must classify it public and DISCARD+ * the echoed secret (never persist or log it).+ */+export const DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON =+ '{"client_id":"cl_PublicWithEchoedSecret_x91","token_endpoint_auth_method":"none","client_secret":"echoed-secret-must-be-discarded","grant_types":["authorization_code","refresh_token"],"response_types":["code"],"client_name":"Evenfire","redirect_uris":["http://127.0.0.1:8090/api/v1/oauth-callback/remote"]}'++export const DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_RESPONSE = JSON.parse(+ DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON+) as { client_id: string; token_endpoint_auth_method: string; client_secret: string }++/**+ * Adversarial 2xx: a NON-STRING `token_endpoint_auth_method` (a number) injected by+ * an untrusted AS. Verbatim wire string. Must fail closed to `auth_method_unsupported`+ * rather than let the garbage value flow to the effective-mode derivation.+ */+export const DCR_NONSTRING_AUTH_METHOD_REGISTRATION_JSON =+ '{"client_id":"cl_NonStringAuthMethod","token_endpoint_auth_method":42,"registration_client_uri":"https://mcp.notion.com/register/cl_NonStringAuthMethod","registration_access_token":"fixture-reg-access-token-not-probed"}'+export interface RecordedDcrCall {url: stringmethod: stringdiff --git a/control-api/test/oauth.dcr.test.ts b/control-api/test/oauth.dcr.test.tsindex 644f55b67..1479a4ff2 100644--- a/control-api/test/oauth.dcr.test.ts+++ b/control-api/test/oauth.dcr.test.ts@@ -5,8 +5,11 @@ import type { DiscoveryResult } from '../src/oauth/discovery.js'import {DCR_BASIC_REGISTRATION_RESPONSE,DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,+ DCR_NONSTRING_AUTH_METHOD_REGISTRATION_JSON,DCR_PUBLIC_REGISTRATION_RESPONSE,+ DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON,DCR_REGISTRATION_ENDPOINT,+ DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON,makeDcrTransport,} from './fixtures/remoteOAuthDiscovery.js'@@ -109,6 +112,71 @@ describe('registerDynamicClient (RFC 7591, effectful via injected pinned transpoif (outcome.ok) {expect(outcome.response.client_secret).toBe('fixture-client-secret-not-probed')expect(outcome.response.registration_access_token).toBe('fixture-reg-access-token-not-probed')+ // The AS echoed `client_secret_post` WITH a secret → effective confidential.+ expect(outcome.effectiveAuthMethod).toBe('client_secret_post')+ expect(outcome.effectiveClientMode).toBe('confidential')+ }+ })++ it('DOWNGRADE: confidential request, AS returns `none` + no client_secret (Vercel) → ok as public', async () => {+ // Regression for the real Vercel DCR: a confidential (`client_secret_post`)+ // request that the AS downgrades to a public client. The guard must anchor on the+ // EFFECTIVE auth method, not the requested one — this returned `invalid_response`+ // before the fix (rejecting a perfectly usable PKCE public client).+ const { transport } = makeDcrTransport({+ responseJson: DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON,+ })+ const outcome = await registerDynamicClient(+ { transport, resolveDns: PUBLIC_IP },+ DCR_REGISTRATION_ENDPOINT,+ confReq+ )+ expect(outcome.ok).toBe(true)+ if (outcome.ok) {+ expect(outcome.effectiveAuthMethod).toBe('none')+ expect(outcome.effectiveClientMode).toBe('public')+ expect(outcome.response.client_id).toBe('cl_WbdtcToDrMR4ZHvXLGAmbfoYCsQjMeS8')+ // A downgraded public client carries NO secret.+ expect(outcome.response.client_secret).toBeUndefined()+ }+ })++ it('ADVERSARIAL: AS returns `none` but ALSO echoes a client_secret → classified public', async () => {+ const { transport } = makeDcrTransport({+ responseJson: DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON,+ })+ const outcome = await registerDynamicClient(+ { transport, resolveDns: PUBLIC_IP },+ DCR_REGISTRATION_ENDPOINT,+ confReq+ )+ expect(outcome.ok).toBe(true)+ if (outcome.ok) {+ // The auth method is the authority: `none` ⇒ public, regardless of an echoed secret.+ expect(outcome.effectiveAuthMethod).toBe('none')+ expect(outcome.effectiveClientMode).toBe('public')+ }+ })++ it('FAIL-CLOSED: AS assigns a NON-STRING token_endpoint_auth_method → auth_method_unsupported', async () => {+ const { transport } = makeDcrTransport({+ responseJson: DCR_NONSTRING_AUTH_METHOD_REGISTRATION_JSON,+ })+ const outcome = await registerDynamicClient(+ { transport, resolveDns: PUBLIC_IP },+ DCR_REGISTRATION_ENDPOINT,+ confReq+ )+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) {+ expect(outcome.error.kind).toBe('auth_method_unsupported')+ // Minted-but-rejected: the RFC 7592 handle is exposed so the caller can clean up.+ if (outcome.error.kind === 'auth_method_unsupported') {+ expect(outcome.error.registrationClientUri).toBe(+ 'https://mcp.notion.com/register/cl_NonStringAuthMethod'+ )+ expect(outcome.error.registrationAccessToken).toBe('fixture-reg-access-token-not-probed')+ }}})diff --git a/control-api/test/routes.adminRemoteMcp.test.ts b/control-api/test/routes.adminRemoteMcp.test.tsindex 92d7b1020..e86731c6d 100644--- a/control-api/test/routes.adminRemoteMcp.test.ts+++ b/control-api/test/routes.adminRemoteMcp.test.ts@@ -17,7 +17,11 @@ import {DCR_BASIC_REGISTRATION_RESPONSE,DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,DCR_PUBLIC_REGISTRATION_RESPONSE,+ DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON,+ DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_RESPONSE,DCR_REGISTRATION_ENDPOINT,+ DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON,+ DCR_VERCEL_DOWNGRADE_REGISTRATION_RESPONSE,PILOTS,dcrPilot,makeDcrTransport,@@ -495,6 +499,89 @@ describe('POST /admin/mcp-servers/remote — DCR install saga (C2)', () => {expect(cr.spec.oauth.clientSecretRef).toBeUndefined()})+ // Regression: the AS DOWNGRADES a confidential request to public (Vercel). The+ // effective auth method (`none`, no secret) must win end to end — persisted and+ // written to the CR as a PUBLIC client. Fails at parent 054c62c7: the DCR guard+ // anchored on the REQUESTED method, so this returned 400 dcr_registration_failed.+ it('confidential-requested DCR that the AS downgrades to public (Vercel) → 201 as PUBLIC, no secret persisted', async () => {+ // `dcrConfidentialResult` has no `none` in its AS auth methods, so the install+ // derives confidential a-priori and requests `client_secret_post` — exactly what+ // triggered the Vercel downgrade in production.+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const { transport } = makeDcrTransport({+ responseJson: DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON,+ })+ const gw = gatewayWithContext('ctx-a')+ const res = await request(+ makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })+ )+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'vercel-downgrade-dcr',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'dcr',+ })+ expect(res.status).toBe(201)+ // The AS is authoritative: the client persists and reports as PUBLIC.+ expect(res.body.clientMode).toBe('public')++ // A public client stores NO secret envelope.+ const stored = [...rows.values()][0]+ expect(stored.client_mode).toBe('public')+ expect(stored.client_id).toBe(DCR_VERCEL_DOWNGRADE_REGISTRATION_RESPONSE.client_id)+ expect(stored.client_secret_encrypted).toBeNull()++ // No DCR-confidential K8s Secret exists (there is no Secret for DCR at all).+ await expect(gw.getSecret('vercel-downgrade-dcr-oauth-client', NS)).rejects.toThrow()++ const cr = (await gw.getResource('mcpservers', 'vercel-downgrade-dcr', NS)) as {+ spec: { oauth: Record<string, unknown> }+ }+ expect(cr.spec.oauth.clientMode).toBe('public')+ expect(cr.spec.oauth.id).toBe(DCR_VERCEL_DOWNGRADE_REGISTRATION_RESPONSE.client_id)+ // Public → resolves via PKCE + `oauth.id`, no Secret refs (mirrors ClickUp).+ expect(cr.spec.oauth.clientIdRef).toBeUndefined()+ expect(cr.spec.oauth.clientSecretRef).toBeUndefined()+ })++ // Security: a PUBLIC assignment (`none`) that ALSO echoes a client_secret must+ // classify public and DISCARD the secret — never persist it. Observable result:+ // the stored row is public with a NULL secret envelope.+ it('public DCR where the AS echoes a stray client_secret → 201 public, secret DISCARDED (not persisted)', async () => {+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrPublicResult })+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const { transport } = makeDcrTransport({+ responseJson: DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON,+ })+ const gw = gatewayWithContext('ctx-a')+ const res = await request(+ makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })+ )+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'echoed-secret-dcr',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'dcr',+ })+ expect(res.status).toBe(201)+ expect(res.body.clientMode).toBe('public')++ const stored = [...rows.values()][0]+ expect(stored.client_mode).toBe('public')+ expect(stored.client_id).toBe(DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_RESPONSE.client_id)+ // The echoed secret is discarded — no envelope persisted.+ expect(stored.client_secret_encrypted).toBeNull()++ const cr = (await gw.getResource('mcpservers', 'echoed-secret-dcr', NS)) as {+ spec: { oauth: Record<string, unknown> }+ }+ expect(cr.spec.oauth.clientMode).toBe('public')+ expect(cr.spec.oauth.clientSecretRef).toBeUndefined()+ })+// T3(b) — fails at parent ffb2005: the minted-but-rejected auth_method_unsupported// error carried no RFC 7592 handle there, so NO cleanup DELETE was attempted.it('confidential DCR where the AS assigns client_secret_basic → 400 auth_method_unsupported, cleans up the minted client', async () => {