Skip to content

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

TypeScript

feat(control-api): remote MCP-OAuth DCR fallback + encrypted dynamic-client store (C2)

Diego Zacarias88d2f1799681
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index fbc5590fc..2498af64c 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.590",
+ "version": "0.1.591",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.590",
+ "version": "0.1.591",
"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 c16ca492b..798e366f8 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.590",
+ "version": "0.1.591",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index e710d5d98..98a991cfb 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -6103,6 +6103,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
// freezing exactly the rows a test harness needs to be able to refresh.
},
},
+ {
+ version: '0116_dynamic_clients_table',
+ apply: applyDynamicClientsTable,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
@@ -6279,6 +6283,44 @@ async function applyOAuthGrantsOwnerGeneralization(db: DbClient): Promise<void>
`)
}
+async function applyDynamicClientsTable(db: DbClient): Promise<void> {
+ // DCR (RFC 7591) dynamic clients — sibling of `oauth_grants` (spec 02 C2,
+ // D-5, DEC-18). When an AS supports neither a pre-registered client nor CIMD,
+ // control-api registers a client dynamically and persists its credentials
+ // here, with the same at-rest guarantees as oauth_grants: client_secret and
+ // the RFC 7592 registration_access_token are AES-256-GCM encrypted via
+ // `encryptOAuthSecret` (never stored in the clear); client_id is the AS's
+ // public assignment and is mirrored into `spec.oauth.id` on the CR.
+ //
+ // Keyed per-server-CR: (owner_kind, server_namespace, server_name) mirror the
+ // exact coordinates of the pre-registered `${serverName}-oauth-client` Secret
+ // and of oauth_grants — the AS (untrusted) never names the primary key. The
+ // `issuer` column is indexed for audit and a possible additive per-issuer
+ // dedup later; it is deliberately NOT part of the uniqueness key.
+ //
+ // Additive + idempotent (CREATE TABLE IF NOT EXISTS): control-api-only, no CRD.
+ await db.query(`
+ CREATE TABLE IF NOT EXISTS dynamic_clients (
+ id BIGSERIAL PRIMARY KEY,
+ owner_kind TEXT NOT NULL DEFAULT 'mcpserver',
+ server_namespace TEXT NOT NULL,
+ server_name TEXT NOT NULL,
+ issuer TEXT NOT NULL,
+ client_id TEXT NOT NULL,
+ client_mode TEXT NOT NULL,
+ client_secret_encrypted TEXT,
+ registration_access_token_encrypted TEXT,
+ registration_client_uri TEXT,
+ client_id_issued_at TIMESTAMPTZ,
+ client_secret_expires_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ CONSTRAINT dynamic_clients_owner_unique UNIQUE (owner_kind, server_namespace, server_name)
+ );
+ CREATE INDEX IF NOT EXISTS dynamic_clients_issuer_idx ON dynamic_clients (issuer);
+ `)
+}
+
async function ensureSchemaMigrationsTable(db: DbClient): Promise<void> {
await db.query(`
CREATE TABLE IF NOT EXISTS schema_migrations (
diff --git a/control-api/src/http/pinnedFetch.ts b/control-api/src/http/pinnedFetch.ts
index 8075239bf..45c7a0585 100644
--- a/control-api/src/http/pinnedFetch.ts
+++ b/control-api/src/http/pinnedFetch.ts
@@ -37,7 +37,7 @@ const DEFAULT_MAX_BODY_BYTES = 1024 * 1024
/** What the transport receives: a single, already-validated hop with a pinned lookup. */
export interface PinnedTransportInput {
url: string
- method: 'GET' | 'POST'
+ method: 'GET' | 'POST' | 'DELETE'
headers: Record<string, string>
/**
* A `node:net` lookup that returns ONLY the pre-validated addresses and never
@@ -78,7 +78,7 @@ export type PinnedFetchResult =
| { ok: false; error: PinnedFetchError }
export interface PinnedFetchOptions {
- method?: 'GET' | 'POST'
+ method?: 'GET' | 'POST' | 'DELETE'
headers?: Record<string, string>
body?: string
resolveDns?: DnsResolver
diff --git a/control-api/src/oauth/cimd.ts b/control-api/src/oauth/cimd.ts
index 9d6a3f24b..5667ca33f 100644
--- a/control-api/src/oauth/cimd.ts
+++ b/control-api/src/oauth/cimd.ts
@@ -35,8 +35,12 @@ export const CIMD_ROUTE_PATH = '/.well-known/evenfire-mcp-client'
/** Full public path of the served document (what `client_id` must equal, minus origin). */
const CIMD_PUBLIC_PATH = `/api/v1${CIMD_ROUTE_PATH}`
-/** Stable remote-lane callback segment. C1.5 honours this exact oauthClientId. */
-const REMOTE_CALLBACK_PATH = '/api/v1/oauth-callback/remote'
+/**
+ * Stable remote-lane callback segment. C1.5 honours this exact oauthClientId, and
+ * C2 DCR (`dcr.ts`) derives its `redirect_uris` from the same constant so the CIMD
+ * document and a dynamically-registered client advertise a byte-identical callback.
+ */
+export const REMOTE_CALLBACK_PATH = '/api/v1/oauth-callback/remote'
/**
* Build the frozen CIMD document for a given public `origin` (scheme://host, no
diff --git a/control-api/src/oauth/dcr.ts b/control-api/src/oauth/dcr.ts
new file mode 100644
index 000000000..e7cbe6faa
--- /dev/null
+++ b/control-api/src/oauth/dcr.ts
@@ -0,0 +1,296 @@
+import { type PinnedFetchError, type PinnedTransport, pinnedFetch } from '../http/pinnedFetch.js'
+import type { DnsResolver, ValidationError } from '../http/validateMcpServerSpec.js'
+import { type Logger, rootLogger } from '../observability/logger.js'
+import type { DiscoveryResult } from './discovery.js'
+
+/**
+ * Dynamic Client Registration client (RFC 7591), spec 02 C2 / D-5 / DEC-18.
+ *
+ * When discovery (`discovery.ts`) resolves the registration mode to `dcr` — the
+ * AS offers neither a pre-registered client nor CIMD — control-api registers a
+ * client dynamically against the AS's registration endpoint and the caller
+ * persists the returned credentials in the encrypted `dynamic_clients` store.
+ *
+ * Mirrors `discovery.ts`: pure request builder, effectful register with a typed
+ * outcome and injectable deps. The registration endpoint was already kernel-
+ * validated during discovery; the POST here re-pins it through `pinnedFetch`
+ * (single hop, no redirect following) so it is re-validated at connect time too
+ * (S-1 structural). This module NEVER follows a 3xx to a `Location` (a redirect
+ * is fail-closed `redirect_blocked`) — an AS re-pointing the registration POST to
+ * an internal host is a classic SSRF, not a legitimate flow.
+ */
+
+const DCR_TIMEOUT_MS = 15_000
+
+/** Field name used when reporting a kernel rejection of the registration endpoint. */
+const REGISTRATION_ENDPOINT_FIELD = 'spec.oauth.registrationEndpoint'
+
+/**
+ * The auth methods control-api can actually present at the token endpoint. The
+ * generic remote token builders (`providers.ts`) emit `client_secret_post` only
+ * (never HTTP Basic), and a public client uses `none`. Any other assignment by
+ * the AS — notably `client_secret_basic` — is one we cannot honor, so we refuse
+ * to store a client we could never authenticate (fail-closed).
+ */
+const PRESENTABLE_AUTH_METHODS = new Set(['none', 'client_secret_post'])
+
+// ─── RFC 7591 shapes (request we send; response is third-party data) ────────
+
+export interface DcrRegistrationRequest {
+ redirect_uris: string[]
+ token_endpoint_auth_method: 'none' | 'client_secret_post'
+ grant_types: string[]
+ response_types: ['code']
+ client_name: 'Evenfire'
+ application_type: 'web'
+ scope?: string
+}
+
+/** RFC 7591 §3.2.1 registration response — every field is untrusted AS data. */
+export interface DcrRegistrationResponse {
+ client_id: string
+ client_secret?: string
+ /** NumericDate (epoch seconds). */
+ client_id_issued_at?: number
+ /** NumericDate (epoch seconds); 0 ⇒ non-expiring. */
+ client_secret_expires_at?: number
+ /** RFC 7592 management bearer — as sensitive as the secret. */
+ registration_access_token?: string
+ /** RFC 7592 management endpoint. */
+ registration_client_uri?: string
+ token_endpoint_auth_method?: string
+ [k: string]: unknown
+}
+
+/**
+ * RFC 7592 mint handle carried on the *minted-but-rejected* error variants: a 2xx
+ * response that DID assign a `client_id` (a real client exists at the AS) but is
+ * unusable to us. It lets the caller run the best-effort RFC 7592 cleanup DELETE so
+ * the orphaned client does not linger (DEC-18). Present ONLY on those variants and
+ * ONLY when the AS returned a management endpoint + token; never on non-2xx errors
+ * (`fetch_failed`/`redirect_blocked`/`kernel_rejected`) where nothing was minted.
+ * In-memory only — used solely for the cleanup DELETE, never persisted or logged.
+ */
+export interface DcrMintHandle {
+ registrationClientUri?: string
+ registrationAccessToken?: string
+}
+
+export type DcrError =
+ | { kind: 'kernel_rejected'; field: string; errors: ValidationError[] }
+ | { kind: 'fetch_failed'; url: string; status?: number; detail: string }
+ /** A 3xx from the registration POST — never re-POSTed to `Location` (SSRF fail-closed). */
+ | { kind: 'redirect_blocked'; url: string; detail: string }
+ /**
+ * 2xx but the body is not a usable RFC 7591 registration (missing client_id, etc.).
+ * Carries a mint handle ONLY for the confidential-without-`client_secret` case,
+ * where a real `client_id` was assigned; the parse/no-client_id cases mint nothing.
+ */
+ | ({ kind: 'invalid_response'; url: string; detail: string } & DcrMintHandle)
+ /** The AS assigned a token_endpoint_auth_method we cannot present (e.g. client_secret_basic). */
+ | ({ kind: 'auth_method_unsupported'; detail: string } & DcrMintHandle)
+ /** Response arrived with a non-identity content-encoding (fail-closed, never mis-parse). */
+ | { kind: 'content_encoding_rejected'; url: string; encoding: string }
+
+export type DcrOutcome =
+ | { ok: true; response: DcrRegistrationResponse }
+ | { ok: false; error: DcrError }
+
+export interface DcrDeps {
+ transport?: PinnedTransport
+ resolveDns?: DnsResolver
+ logger?: Logger
+}
+
+/**
+ * Build the RFC 7591 registration request (pure). `token_endpoint_auth_method` is
+ * `none` for a public client (AS lists `none`) or `client_secret_post` for a
+ * confidential one. `refresh_token` is added to `grant_types` ONLY when the AS
+ * advertised it (invariant §6 #8, fail-closed) — never register a refresh grant
+ * against an AS that did not advertise it. `redirect_uris` is the single source of
+ * truth passed in by the caller (the CIMD remote callback), never re-hardcoded.
+ */
+export function buildDcrRequest(
+ discovery: DiscoveryResult,
+ opts: { clientMode: 'public' | 'confidential'; redirectUris: string[]; scopes?: string[] }
+): DcrRegistrationRequest {
+ const grantTypes = ['authorization_code']
+ if (discovery.quirks.supportsRefresh) grantTypes.push('refresh_token')
+
+ const request: DcrRegistrationRequest = {
+ redirect_uris: opts.redirectUris,
+ token_endpoint_auth_method: opts.clientMode === 'public' ? 'none' : 'client_secret_post',
+ grant_types: grantTypes,
+ response_types: ['code'],
+ client_name: 'Evenfire',
+ application_type: 'web',
+ }
+ if (opts.scopes && opts.scopes.length > 0) request.scope = opts.scopes.join(' ')
+ return request
+}
+
+function isRedirectStatus(status: number): boolean {
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
+}
+
+function isRecord(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
+}
+
+/** Map a pinned-fetch error onto DCR's typed error union. */
+function mapPinnedError(error: PinnedFetchError, url: string): DcrError {
+ switch (error.kind) {
+ case 'kernel_rejected':
+ return { kind: 'kernel_rejected', field: error.field, errors: error.errors }
+ case 'transport_failed':
+ return { kind: 'fetch_failed', url, detail: error.detail }
+ case 'content_encoding_rejected':
+ return { kind: 'content_encoding_rejected', url, encoding: error.encoding }
+ }
+}
+
+/** Compose a human-readable detail from an RFC 6749-style error body, if present. */
+function errorBodyDetail(status: number, bodyText: string): string {
+ try {
+ const parsed = JSON.parse(bodyText)
+ if (isRecord(parsed) && typeof parsed.error === 'string') {
+ const description =
+ typeof parsed.error_description === 'string' ? `: ${parsed.error_description}` : ''
+ return `${parsed.error}${description}`
+ }
+ } catch {
+ // Non-JSON error body — fall through to the bare status.
+ }
+ return `HTTP ${status}`
+}
+
+/**
+ * Register a dynamic client (RFC 7591) at `endpoint`. Single-hop POST through
+ * `pinnedFetch` (re-validates + pins the endpoint); a 3xx is `redirect_blocked`
+ * and never followed. The AS response is untrusted: a missing `client_id` or an
+ * un-presentable `token_endpoint_auth_method` is a typed, fail-closed error, so we
+ * never persist a client we cannot use.
+ */
+export async function registerDynamicClient(
+ deps: DcrDeps,
+ endpoint: string,
+ request: DcrRegistrationRequest
+): Promise<DcrOutcome> {
+ const log = (deps.logger ?? rootLogger).child({ module: 'oauth-dcr' })
+ const body = JSON.stringify(request)
+
+ const fetched = await pinnedFetch(endpoint, REGISTRATION_ENDPOINT_FIELD, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'content-length': String(Buffer.byteLength(body)),
+ },
+ body,
+ resolveDns: deps.resolveDns,
+ transport: deps.transport,
+ timeoutMs: DCR_TIMEOUT_MS,
+ })
+ if (!fetched.ok) {
+ const error = mapPinnedError(fetched.error, endpoint)
+ log.warn({ dcr: error.kind }, 'dynamic client registration transport failed')
+ return { ok: false, error }
+ }
+
+ const response = fetched.response
+ if (isRedirectStatus(response.status)) {
+ // Never re-POST to a Location: an AS redirecting the registration is a
+ // fail-closed SSRF vector (H2), not a flow to follow.
+ log.warn({ dcr: 'redirect_blocked', status: response.status }, 'dcr registration redirected')
+ return {
+ ok: false,
+ error: {
+ kind: 'redirect_blocked',
+ url: endpoint,
+ detail: `HTTP ${response.status} redirect on the registration POST`,
+ },
+ }
+ }
+
+ const isSuccess = response.status >= 200 && response.status < 300
+ if (!isSuccess) {
+ const detail = errorBodyDetail(response.status, response.bodyText)
+ log.warn({ dcr: 'fetch_failed', status: response.status }, 'dcr registration rejected')
+ return {
+ ok: false,
+ error: { kind: 'fetch_failed', url: endpoint, status: response.status, detail },
+ }
+ }
+
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(response.bodyText)
+ } catch (e) {
+ return {
+ ok: false,
+ error: {
+ kind: 'invalid_response',
+ url: endpoint,
+ detail: e instanceof Error ? e.message : String(e),
+ },
+ }
+ }
+ if (!isRecord(parsed) || typeof parsed.client_id !== 'string' || parsed.client_id.length === 0) {
+ return {
+ ok: false,
+ error: {
+ kind: 'invalid_response',
+ url: endpoint,
+ detail: 'registration response has no client_id',
+ },
+ }
+ }
+
+ 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.
+ const effectiveAuthMethod =
+ assigned.token_endpoint_auth_method ?? request.token_endpoint_auth_method
+ if (
+ typeof effectiveAuthMethod === 'string' &&
+ !PRESENTABLE_AUTH_METHODS.has(effectiveAuthMethod)
+ ) {
+ log.warn(
+ { dcr: 'auth_method_unsupported', assigned: effectiveAuthMethod },
+ 'dcr registration assigned an un-presentable token_endpoint_auth_method'
+ )
+ return {
+ ok: false,
+ error: {
+ kind: 'auth_method_unsupported',
+ detail: `authorization server assigned token_endpoint_auth_method "${effectiveAuthMethod}", which control-api cannot present`,
+ // A client WAS minted (2xx + client_id) but is unusable — expose the RFC 7592
+ // handle so the caller can clean it up.
+ registrationClientUri: assigned.registration_client_uri,
+ registrationAccessToken: assigned.registration_access_token,
+ },
+ }
+ }
+
+ // 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'
+ ) {
+ return {
+ ok: false,
+ error: {
+ kind: 'invalid_response',
+ url: endpoint,
+ detail: 'confidential registration returned no client_secret',
+ // A client WAS minted (2xx + client_id) but is unusable — expose the RFC 7592
+ // handle so the caller can clean it up.
+ registrationClientUri: assigned.registration_client_uri,
+ registrationAccessToken: assigned.registration_access_token,
+ },
+ }
+ }
+
+ return { ok: true, response: assigned }
+}
diff --git a/control-api/src/oauth/dynamicClientStore.ts b/control-api/src/oauth/dynamicClientStore.ts
new file mode 100644
index 000000000..8eb2f8f6b
--- /dev/null
+++ b/control-api/src/oauth/dynamicClientStore.ts
@@ -0,0 +1,208 @@
+import type { DbClient } from '../db.js'
+import { decryptOAuthSecret, encryptOAuthSecret } from './encryption.js'
+
+/**
+ * Store for DCR (RFC 7591) dynamic clients — sibling of `store.ts` (spec 02 C2,
+ * D-5, DEC-18). When an Authorization Server supports neither a pre-registered
+ * client nor CIMD, control-api registers a client dynamically and persists its
+ * credentials here with the same at-rest guarantees as `oauth_grants`.
+ *
+ * Every function takes `(db, encryptionKey, input)` (or `(db, key)` for the
+ * key-only delete): the store owns no pool and no key. The `client_secret` and
+ * the RFC 7592 `registration_access_token` are AES-256-GCM encrypted with
+ * `encryptOAuthSecret` and never stored or returned in the clear except through
+ * an explicit decrypt on read. `client_id` is the AS's public assignment and is
+ * stored (and mirrored to `spec.oauth.id`) in plaintext by design.
+ *
+ * Keyed per-server-CR: `(owner_kind, server_namespace, server_name)` mirror the
+ * pre-registered `${serverName}-oauth-client` Secret coordinates and
+ * `oauth_grants` — the untrusted AS never names the primary key (DEC-18).
+ */
+
+/**
+ * Identifies one `dynamic_clients` row. `ownerKind` defaults to `'mcpserver'`
+ * (mirrors `resolveOwnerKind` in store.ts); remote OAuth servers are the only
+ * dynamic-client owners today.
+ */
+export interface DynamicClientKey {
+ ownerKind?: 'mcpserver'
+ serverNamespace: string
+ serverName: string
+}
+
+/** Resolve the owner domain of a key, defaulting to the mcpserver domain. */
+function resolveOwnerKind(input: { ownerKind?: 'mcpserver' }): 'mcpserver' {
+ return input.ownerKind ?? 'mcpserver'
+}
+
+/** One decrypted row of `dynamic_clients`. */
+export interface DynamicClientRow {
+ ownerKind: 'mcpserver'
+ serverNamespace: string
+ serverName: string
+ issuer: string
+ /** AS-assigned public client identifier (never encrypted). */
+ clientId: string
+ clientMode: 'public' | 'confidential'
+ /** Plaintext client secret; undefined for a public client or when absent. */
+ clientSecret?: string
+ /** Plaintext RFC 7592 registration-management bearer; undefined when absent. */
+ registrationAccessToken?: string
+ /** RFC 7592 management endpoint; undefined when the AS returned none. */
+ registrationClientUri?: string
+ clientIdIssuedAt?: Date
+ /** RFC 7591; null (non-expiring) is mapped to undefined. */
+ clientSecretExpiresAt?: Date
+ createdAt: Date
+ updatedAt: Date
+}
+
+export type UpsertDynamicClientInput = DynamicClientKey & {
+ issuer: string
+ clientId: string
+ clientMode: 'public' | 'confidential'
+ /** Encrypted before storage; omit for a public client. */
+ clientSecret?: string
+ /** Encrypted before storage; omit when the AS returned none. */
+ registrationAccessToken?: string
+ registrationClientUri?: string
+ /** RFC 7591 NumericDate (epoch seconds); absent → NULL. */
+ clientIdIssuedAtSec?: number
+ /** RFC 7591 NumericDate (epoch seconds); 0/absent (non-expiring) → NULL. */
+ clientSecretExpiresAtSec?: number
+}
+
+/**
+ * RFC 7591 NumericDate (absolute epoch seconds) → Date. `0` means "does not
+ * expire" (RFC 7591 §3.2.1) and, like an absent value, maps to NULL.
+ */
+function numericDateToDate(seconds: number | undefined): Date | null {
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) return null
+ return new Date(seconds * 1000)
+}
+
+/**
+ * Insert (or replace) the dynamic client for a server CR. Re-registration
+ * overwrites in place (INSERT … ON CONFLICT DO UPDATE), which is also the only
+ * rotation path in C2 — there is no dedicated rotate fn (no caller; avoids dead
+ * code, DEC-18). `client_secret` and `registration_access_token` are encrypted
+ * at rest; a public client stores NULL for the secret.
+ */
+export async function upsertDynamicClient(
+ db: DbClient,
+ encryptionKey: Buffer,
+ input: UpsertDynamicClientInput
+): Promise<void> {
+ const ownerKind = resolveOwnerKind(input)
+ const clientSecretEncrypted = input.clientSecret
+ ? encryptOAuthSecret(encryptionKey, input.clientSecret)
+ : null
+ const registrationAccessTokenEncrypted = input.registrationAccessToken
+ ? encryptOAuthSecret(encryptionKey, input.registrationAccessToken)
+ : null
+
+ await db.query(
+ `INSERT INTO dynamic_clients (
+ owner_kind, server_namespace, server_name, issuer, client_id, client_mode,
+ client_secret_encrypted, registration_access_token_encrypted,
+ registration_client_uri, client_id_issued_at, client_secret_expires_at,
+ updated_at
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NOW())
+ ON CONFLICT (owner_kind, server_namespace, server_name)
+ DO UPDATE SET
+ issuer = EXCLUDED.issuer,
+ client_id = EXCLUDED.client_id,
+ client_mode = EXCLUDED.client_mode,
+ client_secret_encrypted = EXCLUDED.client_secret_encrypted,
+ registration_access_token_encrypted = EXCLUDED.registration_access_token_encrypted,
+ registration_client_uri = EXCLUDED.registration_client_uri,
+ client_id_issued_at = EXCLUDED.client_id_issued_at,
+ client_secret_expires_at = EXCLUDED.client_secret_expires_at,
+ updated_at = NOW()`,
+ [
+ ownerKind,
+ input.serverNamespace,
+ input.serverName,
+ input.issuer,
+ input.clientId,
+ input.clientMode,
+ clientSecretEncrypted,
+ registrationAccessTokenEncrypted,
+ input.registrationClientUri ?? null,
+ numericDateToDate(input.clientIdIssuedAtSec),
+ numericDateToDate(input.clientSecretExpiresAtSec),
+ ]
+ )
+}
+
+interface DynamicClientDbRow {
+ owner_kind: 'mcpserver'
+ server_namespace: string
+ server_name: string
+ issuer: string
+ client_id: string
+ client_mode: 'public' | 'confidential'
+ client_secret_encrypted: string | null
+ registration_access_token_encrypted: string | null
+ registration_client_uri: string | null
+ client_id_issued_at: Date | null
+ client_secret_expires_at: Date | null
+ created_at: Date
+ updated_at: Date
+}
+
+const SELECT_COLUMNS = `owner_kind, server_namespace, server_name, issuer, client_id, client_mode,
+ client_secret_encrypted, registration_access_token_encrypted,
+ registration_client_uri, client_id_issued_at, client_secret_expires_at,
+ created_at, updated_at`
+
+/** Read one dynamic client, decrypting its secret and registration token. */
+export async function getDynamicClient(
+ db: DbClient,
+ encryptionKey: Buffer,
+ key: DynamicClientKey
+): Promise<DynamicClientRow | null> {
+ const ownerKind = resolveOwnerKind(key)
+ const result = await db.query(
+ `SELECT ${SELECT_COLUMNS}
+ FROM dynamic_clients
+ WHERE owner_kind = $1 AND server_namespace = $2 AND server_name = $3`,
+ [ownerKind, key.serverNamespace, key.serverName]
+ )
+ if (result.rows.length === 0) return null
+ const row = result.rows[0] as DynamicClientDbRow
+ return {
+ ownerKind: row.owner_kind,
+ serverNamespace: row.server_namespace,
+ serverName: row.server_name,
+ issuer: row.issuer,
+ clientId: row.client_id,
+ clientMode: row.client_mode,
+ clientSecret: row.client_secret_encrypted
+ ? decryptOAuthSecret(encryptionKey, row.client_secret_encrypted)
+ : undefined,
+ registrationAccessToken: row.registration_access_token_encrypted
+ ? decryptOAuthSecret(encryptionKey, row.registration_access_token_encrypted)
+ : undefined,
+ registrationClientUri: row.registration_client_uri ?? undefined,
+ clientIdIssuedAt: row.client_id_issued_at ?? undefined,
+ clientSecretExpiresAt: row.client_secret_expires_at ?? undefined,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ }
+}
+
+/**
+ * Hard-delete the dynamic client for a server CR (idempotent). Returns the
+ * number of rows removed so a caller can audit whether anything was revoked
+ * (0 ⇒ already gone). Mirrors `deleteOAuthGrant`.
+ */
+export async function deleteDynamicClient(db: DbClient, key: DynamicClientKey): Promise<number> {
+ const ownerKind = resolveOwnerKind(key)
+ const result = await db.query(
+ `DELETE FROM dynamic_clients
+ WHERE owner_kind = $1 AND server_namespace = $2 AND server_name = $3`,
+ [ownerKind, key.serverNamespace, key.serverName]
+ )
+ return result.rowCount ?? 0
+}
diff --git a/control-api/src/routes/admin/remoteMcp.ts b/control-api/src/routes/admin/remoteMcp.ts
index cc878e29d..980db2b92 100644
--- a/control-api/src/routes/admin/remoteMcp.ts
+++ b/control-api/src/routes/admin/remoteMcp.ts
@@ -1,16 +1,32 @@
import { Router } from 'express'
import { z } from 'zod'
import { config } from '../../config.js'
+import { type DbClient, pool } from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import { extractK8sError } from '../../http/k8sError.js'
import { enforceNamespace } from '../../http/namespaceAudit.js'
+import { pinnedFetch } from '../../http/pinnedFetch.js'
import { RFC1123_RE } from '../../http/rfc1123.js'
import { validateOAuthEndpointUrl } from '../../http/validateMcpServerSpec.js'
import { K8sGateway } from '../../k8s.js'
import { type UiAuthedRequest } from '../../middleware/controlUIAuth.js'
+import { REMOTE_CALLBACK_PATH } from '../../oauth/cimd.js'
+import {
+ type DcrDeps,
+ type DcrMintHandle,
+ buildDcrRequest,
+ registerDynamicClient,
+} from '../../oauth/dcr.js'
import { type DiscoveryResult, discoverRemoteOAuth } from '../../oauth/discovery.js'
+import {
+ type DynamicClientKey,
+ deleteDynamicClient,
+ upsertDynamicClient,
+} from '../../oauth/dynamicClientStore.js'
+import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'
import { rootLogger } from '../../observability/logger.js'
import { K8sNotFoundError } from '../../services/resourceService.js'
+import { normalizeConfiguredOrigin } from '../external/oauthCallback.js'
/**
* Admin "C-install" routes for the remote MCP-OAuth carril (spec 02 C1.5, DEC-12).
@@ -31,8 +47,12 @@ import { K8sNotFoundError } from '../../services/resourceService.js'
* legalizes `remote`×`oauth` — so this route's LIVE admission only works after C3.
* Until then the saga is unit-tested against a mocked K8sGateway.
*
- * The engine (discovery, kernel §4) is C1; DCR (RFC 7591) lands in C2 — a DCR-mode
- * install is rejected here with a clear message.
+ * The engine (discovery, kernel §4) is C1; DCR (RFC 7591) is C2: a DCR-mode install
+ * registers a dynamic client against the AS (`dcr.ts`), persists its credentials in
+ * the encrypted `dynamic_clients` store (`dynamicClientStore.ts`) as saga step 0,
+ * and — for DCR-confidential — keeps the secret in that store rather than a K8s
+ * Secret (DEC-8). Registration is compensated (local delete + best-effort RFC 7592
+ * DELETE) if a later saga step fails.
*/
const BASE = '/admin/mcp-servers/remote'
@@ -77,6 +97,12 @@ export interface RemoteOAuthClientSecretRef {
export interface RemoteOAuthSpec {
/** Discriminator for the remote-discovered carril — never the baked `provider` enum. */
source: 'remote'
+ /**
+ * AS-assigned client_id, set ONLY for the DCR branch (mirrors the
+ * `dynamic_clients` row; C4 keys grant resolution by `oauth.id`). Omitted for
+ * CIMD/pre-registered in this phase — CIMD's `id` backfill is C3 (DEC-18, R0/F5).
+ */
+ id?: string
clientMode: 'public' | 'confidential'
authorizationEndpoint: string
tokenEndpoint: string
@@ -105,7 +131,10 @@ function buildRemoteOAuthSpec(
opts: {
clientMode: 'public' | 'confidential'
grantScope: 'user' | 'context'
+ /** Set for pre-registered confidential (K8s Secret name); mutually exclusive with dynamicClientId. */
clientSecretName?: string
+ /** Set for DCR (AS-assigned client_id); mirrored to `oauth.id`. Omits Secret refs. */
+ dynamicClientId?: string
}
): RemoteOAuthSpec {
const oauth: RemoteOAuthSpec = {
@@ -122,13 +151,57 @@ function buildRemoteOAuthSpec(
}
if (result.endpoints.registration) oauth.registrationEndpoint = result.endpoints.registration
if (result.issForCallback) oauth.issForCallback = result.issForCallback
- if (opts.clientMode === 'confidential' && opts.clientSecretName) {
+ // C4 discriminator (DEC-18): Secret refs present ⇒ read the secret from the K8s
+ // Secret (pre-registered). No refs + clientMode 'confidential' + `id` set ⇒ read
+ // the secret from the encrypted `dynamic_clients` store (DCR). The two sources
+ // are mutually exclusive per install mode, so we set at most one here.
+ if (opts.dynamicClientId) {
+ oauth.id = opts.dynamicClientId
+ } else if (opts.clientMode === 'confidential' && opts.clientSecretName) {
oauth.clientIdRef = { name: opts.clientSecretName, key: 'client_id' }
oauth.clientSecretRef = { name: opts.clientSecretName, key: 'client_secret' }
}
return oauth
}
+/**
+ * DCR client mode is derived from the AS metadata, NOT the operator body: a public
+ * client when the AS lists `none` in `token_endpoint_auth_methods_supported`, else
+ * confidential (`client_secret_post`). The registration RESPONSE is the final
+ * authority on the auth method (fail-closed in `registerDynamicClient`).
+ */
+function deriveDcrClientMode(result: DiscoveryResult): 'public' | 'confidential' {
+ const methods = result.as.token_endpoint_auth_methods_supported
+ return Array.isArray(methods) && methods.includes('none') ? 'public' : 'confidential'
+}
+
+const DCR_TIMEOUT_MS = 15_000
+
+/**
+ * Best-effort RFC 7592 client-delete against the AS's management endpoint, so a
+ * dynamic client we minted but then failed to fully install does not linger at the
+ * AS. Single-hop pinned DELETE with the registration bearer; any failure is
+ * swallowed (the local `deleteDynamicClient` is the reliable revocation, this is
+ * courtesy cleanup). Never logs the bearer.
+ */
+async function bestEffortRfc7592Delete(
+ dcrDeps: DcrDeps,
+ registrationClientUri: string,
+ registrationAccessToken: string
+): Promise<void> {
+ try {
+ await pinnedFetch(registrationClientUri, 'spec.oauth.registrationClientUri', {
+ method: 'DELETE',
+ headers: { authorization: `Bearer ${registrationAccessToken}` },
+ resolveDns: dcrDeps.resolveDns,
+ transport: dcrDeps.transport,
+ timeoutMs: DCR_TIMEOUT_MS,
+ })
+ } catch {
+ // Best-effort; the local store delete is the reliable revocation.
+ }
+}
+
const REMOTE_MCP_EGRESS_PROXY_IMAGE =
process.env.CONTROL_API_REMOTE_MCP_EGRESS_PROXY_IMAGE || 'clerum/nginx-egress-proxy:0.1.0'
const REMOTE_MCP_PROXY_PORT = 3000
@@ -152,8 +225,26 @@ async function waitForDeletion(readCurrent: () => Promise<unknown>, label: strin
throw new Error(`Timed out waiting for ${label} deletion`)
}
-export function createAdminRemoteMcpRouter(gateway: K8sGateway): Router {
+/**
+ * Injectable dependencies for the DCR saga (test seam). Production leaves them
+ * undefined: `db` defaults to the core `pool`, `encryptionKey` is derived from
+ * config, and `dcr` uses the real `node:https` pinned transport. Tests inject an
+ * in-memory `db` and a `PinnedTransport` stub so the saga runs with zero network.
+ */
+export interface AdminRemoteMcpDeps {
+ db?: DbClient
+ encryptionKey?: Buffer
+ dcr?: DcrDeps
+}
+
+export function createAdminRemoteMcpRouter(
+ gateway: K8sGateway,
+ deps: AdminRemoteMcpDeps = {}
+): Router {
const router = Router()
+ const db: DbClient = deps.db ?? pool
+ const encryptionKey = deps.encryptionKey ?? deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+ const dcrDeps: DcrDeps = deps.dcr ?? { logger: log }
// ── POST /admin/mcp-servers/remote/discover — dry-run, no writes ──────────
router.post(
@@ -186,12 +277,15 @@ export function createAdminRemoteMcpRouter(gateway: K8sGateway): Router {
res.status(200).json({
detected: {
registrationMode: r.registrationMode,
- // DCR is not available until C2 — surfaced, not failed (spec C1.5).
+ // DCR is available in C2. Echo the resolved client mode (derived from the
+ // AS auth methods, not the operator) + supportsRefresh so the C5 wizard can
+ // prefill the confirm step.
...(r.registrationMode === 'dcr'
? {
dcr: {
- available: false,
- message: 'requires DCR (not available until C2)',
+ available: true,
+ clientMode: deriveDcrClientMode(r),
+ supportsRefresh: r.quirks.supportsRefresh,
},
}
: {}),
@@ -230,29 +324,15 @@ export function createAdminRemoteMcpRouter(gateway: K8sGateway): Router {
return
}
- // DCR lands in C2 — reject clearly rather than half-install.
- if (body.mode === 'dcr') {
+ // A pre-registered install must carry the operator-supplied credentials up
+ // front (they become the K8s Secret). CIMD/DCR carry none here.
+ if (body.mode === 'pre-registered' && (!body.clientId || !body.clientSecret)) {
res.status(400).json({
- error: 'dcr_not_available',
- message: 'dynamic client registration is not yet available (lands in C2)',
+ error: 'pre-registered confidential client requires clientId and clientSecret',
})
return
}
- let clientMode: 'public' | 'confidential'
- if (body.mode === 'pre-registered') {
- if (!body.clientId || !body.clientSecret) {
- res.status(400).json({
- error: 'pre-registered confidential client requires clientId and clientSecret',
- })
- return
- }
- clientMode = 'confidential'
- } else {
- // CIMD → public client, no secret.
- clientMode = 'public'
- }
-
// Kernel §4 on the admin-typed baseUrl (explicit 400 before discovery).
const kernelErrors = await validateOAuthEndpointUrl(body.baseUrl, 'baseUrl')
if (kernelErrors.length > 0) {
@@ -266,7 +346,7 @@ export function createAdminRemoteMcpRouter(gateway: K8sGateway): Router {
const outcome = await discoverRemoteOAuth(
body.baseUrl,
{ logger: log },
- { hasPreRegisteredClient: clientMode === 'confidential' }
+ { hasPreRegisteredClient: body.mode === 'pre-registered' }
)
if (!outcome.ok) {
log.warn({ discovery: outcome.error.kind }, 'remote install discovery failed')
@@ -275,13 +355,15 @@ export function createAdminRemoteMcpRouter(gateway: K8sGateway): Router {
}
const discovery = outcome.result
- // CIMD-mode install requires the AS to actually support the public CIMD carril.
- if (clientMode === 'public' && discovery.registrationMode !== 'cimd') {
+ // The requested mode must match what server-side discovery actually resolved
+ // (D-4: discovery is authoritative). CIMD ⇒ AS must offer CIMD; DCR ⇒ AS must
+ // offer a registration endpoint (registrationMode 'dcr').
+ if (body.mode === 'cimd' && discovery.registrationMode !== 'cimd') {
if (discovery.registrationMode === 'dcr') {
res.status(400).json({
- error: 'dcr_not_available',
+ error: 'mode_unsupported',
message:
- 'this authorization server requires dynamic client registration, not yet available (C2)',
+ 'this authorization server requires dynamic client registration; install with mode "dcr"',
})
return
}
@@ -291,6 +373,22 @@ export function createAdminRemoteMcpRouter(gateway: K8sGateway): Router {
})
return
}
+ if (body.mode === 'dcr' && discovery.registrationMode !== 'dcr') {
+ res.status(400).json({
+ error: 'mode_unsupported',
+ message: `authorization server does not offer dynamic client registration (detected mode: ${discovery.registrationMode})`,
+ })
+ return
+ }
+
+ // Client mode: pre-registered/CIMD are fixed by the mode; DCR derives it from
+ // the AS auth methods (public iff `none`, else confidential) — NOT the body.
+ const clientMode: 'public' | 'confidential' =
+ body.mode === 'pre-registered'
+ ? 'confidential'
+ : body.mode === 'dcr'
+ ? deriveDcrClientMode(discovery)
+ : 'public'
const targetNs = config.mcpServersNamespace
const serverName = body.serverName
@@ -302,16 +400,205 @@ export function createAdminRemoteMcpRouter(gateway: K8sGateway): Router {
'clerum.io/server-mode': 'remote',
}
+ // ── Saga step 0 (DCR only): register a dynamic client against the AS and
+ // persist its credentials in the encrypted store BEFORE any K8s writes. The
+ // registration endpoint was kernel-validated during discovery and is re-pinned
+ // by the POST. Compensated by `rollbackDynamicClient` if a later step fails.
+ const dynamicClientKey: DynamicClientKey = {
+ ownerKind: 'mcpserver',
+ serverNamespace: targetNs,
+ serverName,
+ }
+ let dcrRegistered = false
+ let dcrClientId: string | undefined
+ let dcrRegistrationClientUri: string | undefined
+ let dcrRegistrationAccessToken: string | undefined
+ const rollbackDynamicClient = async (): Promise<void> => {
+ if (!dcrRegistered) return
+ try {
+ await deleteDynamicClient(db, dynamicClientKey)
+ } catch {
+ // Best-effort local revocation; preserve the original saga error.
+ }
+ if (dcrRegistrationClientUri && dcrRegistrationAccessToken) {
+ await bestEffortRfc7592Delete(
+ dcrDeps,
+ dcrRegistrationClientUri,
+ dcrRegistrationAccessToken
+ )
+ } else {
+ // AS returned no RFC 7592 management endpoint — local delete is all we can do.
+ log.info(
+ { event: 'remote_oauth_dcr_rollback_local_only', serverName, namespace: targetNs },
+ 'dcr rollback: no RFC 7592 registration_client_uri, local store delete only'
+ )
+ }
+ }
+
+ if (body.mode === 'dcr') {
+ // Cheap read-only precheck so a bad contextRef does not mint a throwaway
+ // client at the AS. The attach step re-reads and remains authoritative.
+ try {
+ await gateway.getResource('contexts', contextRef)
+ } catch (err) {
+ const k8sErr = extractK8sError(err)
+ const notFound = err instanceof K8sNotFoundError
+ if (notFound || k8sErr?.status === 404) {
+ res.status(404).json({ error: `context "${contextRef}" not found` })
+ return
+ }
+ throw err
+ }
+
+ const registrationEndpoint = discovery.endpoints.registration
+ if (!registrationEndpoint) {
+ res.status(400).json({
+ error: 'mode_unsupported',
+ message: 'authorization server advertised no registration endpoint',
+ })
+ return
+ }
+
+ // redirect_uris single source of truth: the CIMD remote callback (never a
+ // re-hardcoded path). Fail closed if no public callback origin is configured.
+ const origin = normalizeConfiguredOrigin(config.oauthCallbackBaseUrl)
+ if (origin === null) {
+ log.error(
+ { event: 'remote_oauth_dcr_callback_unconfigured', serverName },
+ 'dcr install requires a configured public callback base URL'
+ )
+ res.status(503).json({ error: 'callback_base_url_unconfigured' })
+ return
+ }
+
+ const dcrRequest = buildDcrRequest(discovery, {
+ clientMode,
+ redirectUris: [`${origin}${REMOTE_CALLBACK_PATH}`],
+ scopes: derivedScopes(discovery),
+ })
+ const dcrOutcome = await registerDynamicClient(dcrDeps, registrationEndpoint, dcrRequest)
+ if (!dcrOutcome.ok) {
+ const dcrError = dcrOutcome.error
+ // Minted-but-rejected: a 2xx that assigned a real client_id we cannot use
+ // (un-presentable auth method, or confidential without a secret). The client
+ // exists at the AS but we abort — clean it up (DEC-18) before failing. Only
+ // these variants carry the handle; non-2xx errors mint nothing.
+ if (
+ (dcrError.kind === 'auth_method_unsupported' || dcrError.kind === 'invalid_response') &&
+ dcrError.registrationClientUri &&
+ dcrError.registrationAccessToken
+ ) {
+ await bestEffortRfc7592Delete(
+ dcrDeps,
+ dcrError.registrationClientUri,
+ dcrError.registrationAccessToken
+ )
+ }
+ if (dcrError.kind === 'auth_method_unsupported') {
+ log.warn(
+ { event: 'remote_oauth_dcr_auth_method_unsupported', serverName },
+ 'dcr registration assigned an un-presentable auth method'
+ )
+ res.status(400).json({ error: 'auth_method_unsupported' })
+ return
+ }
+ log.warn(
+ { event: 'remote_oauth_dcr_failed', serverName, dcr: dcrError.kind },
+ 'dynamic client registration failed'
+ )
+ // Strip the RFC 7592 mint handle before echoing: the registration_access_token
+ // is an AS management bearer and must never reach the response body or a log.
+ const {
+ registrationAccessToken: _t,
+ registrationClientUri: _u,
+ ...safeDetail
+ } = dcrError as typeof dcrError & Partial<DcrMintHandle>
+ res.status(400).json({ error: 'dcr_registration_failed', detail: safeDetail })
+ return
+ }
+
+ const registration = dcrOutcome.response
+ // 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
+ // saga rollback would skip it and orphan a (often confidential) client at the
+ // AS. Compensate here explicitly (DEC-18).
+ const mintedRegistrationClientUri = registration.registration_client_uri
+ const mintedRegistrationAccessToken = registration.registration_access_token
+ try {
+ await upsertDynamicClient(db, encryptionKey, {
+ ...dynamicClientKey,
+ issuer: discovery.issuer,
+ clientId: registration.client_id,
+ clientMode,
+ clientSecret: registration.client_secret,
+ registrationAccessToken: registration.registration_access_token,
+ registrationClientUri: registration.registration_client_uri,
+ clientIdIssuedAtSec: registration.client_id_issued_at,
+ clientSecretExpiresAtSec: registration.client_secret_expires_at,
+ })
+ } catch (err) {
+ // Local delete is idempotent (the row may never have landed); the pinned
+ // RFC 7592 DELETE is the courtesy revocation at the AS. Both best-effort —
+ // neither must mask the persist failure we report.
+ try {
+ await deleteDynamicClient(db, dynamicClientKey)
+ } catch {
+ // Best-effort local revocation; the row may not exist.
+ }
+ if (mintedRegistrationClientUri && mintedRegistrationAccessToken) {
+ await bestEffortRfc7592Delete(
+ dcrDeps,
+ mintedRegistrationClientUri,
+ mintedRegistrationAccessToken
+ )
+ }
+ // Names-only: never echo the persist error body (may carry secret material).
+ log.error(
+ {
+ event: 'remote_oauth_dcr_persist_failed',
+ serverName,
+ namespace: targetNs,
+ errName: err instanceof Error ? err.name : 'unknown',
+ },
+ 'dcr client persist failed after AS registration; ran best-effort cleanup'
+ )
+ // 503: transient/server-side (DB), not a client error.
+ res.status(503).json({ error: 'dcr_persist_failed' })
+ return
+ }
+ dcrRegistered = true
+ dcrClientId = registration.client_id
+ dcrRegistrationClientUri = registration.registration_client_uri
+ dcrRegistrationAccessToken = registration.registration_access_token
+ // Names-only audit: never echo client_secret, registration_access_token, or
+ // even the client_id value here.
+ log.info(
+ {
+ event: 'remote_oauth_dynamic_client_registered',
+ serverName,
+ namespace: targetNs,
+ clientMode,
+ hasRegistrationClientUri: Boolean(dcrRegistrationClientUri),
+ },
+ 'remote oauth dynamic client registered'
+ )
+ }
+
// Build the McpServer spec. transport routes through the HCC nginx egress proxy
// (D-2); the pinned oauth block is the C3 CRD contract.
const upstreamPath = new URL(body.baseUrl).pathname || '/'
+ // A K8s Secret is created ONLY for pre-registered confidential clients. A
+ // DCR-confidential client's secret lives in the encrypted store (DEC-8), so it
+ // never gets a Secret name and never references one on the CR.
const clientSecretName =
- clientMode === 'confidential' ? `${serverName}-oauth-client` : undefined
+ body.mode === 'pre-registered' ? `${serverName}-oauth-client` : undefined
const oauthSpec = buildRemoteOAuthSpec(discovery, {
clientMode,
grantScope,
clientSecretName,
+ ...(dcrClientId ? { dynamicClientId: dcrClientId } : {}),
})
const mcpServerSpec: Record<string, unknown> = {
@@ -388,6 +675,8 @@ export function createAdminRemoteMcpRouter(gateway: K8sGateway): Router {
// Best-effort rollback; preserve the original CR-create error.
}
}
+ // Compensate a DCR registration made in step 0 (local delete + best-effort 7592).
+ await rollbackDynamicClient()
const k8sErr = extractK8sError(err)
if (k8sErr) {
res.status(k8sErr.status).json({ error: k8sErr.message })
@@ -432,6 +721,8 @@ export function createAdminRemoteMcpRouter(gateway: K8sGateway): Router {
// Best-effort rollback; preserve the original attach error.
}
}
+ // Compensate a DCR registration made in step 0 (local delete + best-effort 7592).
+ await rollbackDynamicClient()
const k8sErr = extractK8sError(err)
const notFound = err instanceof K8sNotFoundError
const message =
diff --git a/control-api/src/utils/log/redact.ts b/control-api/src/utils/log/redact.ts
index e8d7e9d57..895fbe201 100644
--- a/control-api/src/utils/log/redact.ts
+++ b/control-api/src/utils/log/redact.ts
@@ -28,6 +28,8 @@ export const TOKEN_LEAK_REDACT_PATHS: readonly string[] = [
'idToken',
'pkceVerifier',
'refresh_token',
+ 'registration_access_token',
+ 'registrationAccessToken',
'deviceCode',
'device_code',
'userCode',
@@ -61,6 +63,8 @@ export const REQUIRED_REDACT_PATHS: readonly string[] = [
'idToken',
'pkceVerifier',
'refresh_token',
+ 'registration_access_token',
+ 'registrationAccessToken',
'deviceCode',
'device_code',
'userCode',
diff --git a/control-api/test/db.dynamicClientsTableMigration.test.ts b/control-api/test/db.dynamicClientsTableMigration.test.ts
new file mode 100644
index 000000000..8360e306f
--- /dev/null
+++ b/control-api/test/db.dynamicClientsTableMigration.test.ts
@@ -0,0 +1,74 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const clientQuery = vi.fn()
+const clientRelease = vi.fn()
+const mockConnect = vi.fn()
+const mockPoolCtor = vi.fn(function MockPool() {
+ return { connect: mockConnect, query: vi.fn() }
+})
+
+vi.mock('pg', () => ({ Pool: mockPoolCtor }))
+
+describe('0116_dynamic_clients_table migration', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ mockConnect.mockResolvedValue({ query: clientQuery, release: clientRelease })
+ clientQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ })
+
+ it('is registered LAST (the next free version after 0115)', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const versions = CONTROL_API_MIGRATIONS.map(m => m.version)
+ expect(versions).toContain('0116_dynamic_clients_table')
+ expect(versions.at(-1)).toBe('0116_dynamic_clients_table')
+ expect(versions.indexOf('0115_llm_allowed_models_image_input')).toBeLessThan(
+ versions.indexOf('0116_dynamic_clients_table')
+ )
+ })
+
+ it('creates the dynamic_clients table with the encrypted columns, owner-unique constraint and issuer index', async () => {
+ const { initDb } = await import('../src/db.js')
+ await initDb()
+ const sqls = clientQuery.mock.calls.map(([sql]) => String(sql))
+ const ddl = sqls.find(
+ sql => sql.includes('CREATE TABLE IF NOT EXISTS dynamic_clients') && sql.includes('client_id')
+ )
+ expect(ddl, 'the dynamic_clients DDL was applied').toBeDefined()
+ const sql = ddl as string
+
+ // Idempotent create.
+ expect(sql).toContain('CREATE TABLE IF NOT EXISTS dynamic_clients')
+
+ // Owner coordinates mirror oauth_grants / the pre-registered Secret (DEC-18).
+ expect(sql).toContain("owner_kind TEXT NOT NULL DEFAULT 'mcpserver'")
+ expect(sql).toContain('server_namespace TEXT NOT NULL')
+ expect(sql).toContain('server_name TEXT NOT NULL')
+ expect(sql).toContain('issuer TEXT NOT NULL')
+ expect(sql).toContain('client_id TEXT NOT NULL')
+ expect(sql).toContain('client_mode TEXT NOT NULL')
+
+ // Secret material is stored ENCRYPTED, never in the clear.
+ expect(sql).toContain('client_secret_encrypted TEXT')
+ expect(sql).toContain('registration_access_token_encrypted TEXT')
+ expect(sql).toContain('registration_client_uri TEXT')
+ expect(sql).toContain('client_id_issued_at TIMESTAMPTZ')
+ expect(sql).toContain('client_secret_expires_at TIMESTAMPTZ')
+
+ // One dynamic client per server CR.
+ expect(sql).toContain(
+ 'CONSTRAINT dynamic_clients_owner_unique UNIQUE (owner_kind, server_namespace, server_name)'
+ )
+
+ // Issuer index (audit + future additive per-issuer dedup).
+ expect(sql).toContain(
+ 'CREATE INDEX IF NOT EXISTS dynamic_clients_issuer_idx ON dynamic_clients (issuer)'
+ )
+ })
+
+ it('is idempotent — a second initDb re-runs the IF NOT EXISTS DDL without error', async () => {
+ const { initDb } = await import('../src/db.js')
+ await initDb()
+ await expect(initDb()).resolves.not.toThrow()
+ })
+})
diff --git a/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts b/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts
index e4759a7f0..dfe092c13 100644
--- a/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts
+++ b/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts
@@ -21,7 +21,7 @@ describe('0101 oauth_grants owner generalization migration', () => {
const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
const versions = CONTROL_API_MIGRATIONS.map(m => m.version)
expect(versions).toContain('0106_oauth_grants_owner_generalization')
- expect(versions.at(-1)).toBe('0115_llm_allowed_models_image_input')
+ expect(versions.at(-1)).toBe('0116_dynamic_clients_table')
expect(versions.indexOf('0100_seed_minimax_allowed_model')).toBeLessThan(
versions.indexOf('0106_oauth_grants_owner_generalization')
)
diff --git a/control-api/test/fixtures/remoteOAuthDiscovery.ts b/control-api/test/fixtures/remoteOAuthDiscovery.ts
index 085082738..618da961f 100644
--- a/control-api/test/fixtures/remoteOAuthDiscovery.ts
+++ b/control-api/test/fixtures/remoteOAuthDiscovery.ts
@@ -21,6 +21,7 @@
* Provenance: scratchpad/c1-fixtures-provenance.md (sondeo en vivo 2026-09-20,
* sección "EVIDENCIA GET").
*/
+import type { DbClient } from '../../src/db.js'
import type { PinnedTransport } from '../../src/http/pinnedFetch.js'
// ─── Notion (resource base sin path) ────────────────────────────────────────
@@ -137,6 +138,193 @@ export const PILOTS: Record<'notion' | 'linear' | 'sentry' | 'canva', PilotFixtu
* hand-invented one. Discovery now fetches through the IP-pinned `node:https`
* transport (H2), so the test double is a transport, not a `fetch`.
*/
+// ─── DCR fixtures (spec 02 C2, DEC-19) ──────────────────────────────────────
+//
+// The GET-able parts (PRM + AS metadata) are derived from the REAL Notion probe
+// (above) by DOCUMENTED SUBTRACTION, per DEC-19: removing
+// `client_id_metadata_document_supported` pushes the mode selector off CIMD onto
+// DCR (Notion advertises a `/register` endpoint). Dropping `none` from the auth
+// methods additionally forces DCR-CONFIDENTIAL. Nothing here is hand-invented —
+// the fields removed are the exact ones the real Notion AS emits.
+
+function subtractedNotionAs(mutate: (as: Record<string, unknown>) => void): string {
+ const as = JSON.parse(NOTION_AS_JSON) as Record<string, unknown>
+ mutate(as)
+ return JSON.stringify(as)
+}
+
+/** Real Notion probe minus CIMD support → DCR, and `none` kept → public client. */
+export const DCR_PUBLIC_AS_JSON = subtractedNotionAs(as => {
+ delete as.client_id_metadata_document_supported
+})
+
+/** Real Notion probe minus CIMD support AND minus `none` → DCR, confidential. */
+export const DCR_CONFIDENTIAL_AS_JSON = subtractedNotionAs(as => {
+ delete as.client_id_metadata_document_supported
+ as.token_endpoint_auth_methods_supported = ['client_secret_basic', 'client_secret_post']
+})
+
+/** A DCR-forced pilot (public or confidential) reusing Notion's real PRM + URLs. */
+export function dcrPilot(mode: 'public' | 'confidential'): PilotFixture {
+ return {
+ name: `dcr-${mode}`,
+ mcpUrl: 'https://mcp.notion.com/mcp',
+ prm: {
+ url: 'https://mcp.notion.com/.well-known/oauth-protected-resource',
+ json: NOTION_PRM_JSON,
+ },
+ prmNotFound: ['https://mcp.notion.com/.well-known/oauth-protected-resource/mcp'],
+ as: {
+ url: 'https://mcp.notion.com/.well-known/oauth-authorization-server',
+ json: mode === 'public' ? DCR_PUBLIC_AS_JSON : DCR_CONFIDENTIAL_AS_JSON,
+ },
+ }
+}
+
+/** The registration endpoint Notion advertises (target of the DCR POST). */
+export const DCR_REGISTRATION_ENDPOINT = 'https://mcp.notion.com/register'
+
+// The RFC 7591 §3.2.1 registration RESPONSE fixtures below are:
+// NOT probed — derived from RFC 7591 §3.2.1, not a live probe.
+// A DCR registration response can only be obtained by a side-effecting POST that
+// creates a persistent client at a third party (DEC-19) — not repeatable in CI and
+// an external-effect action. These encode the RFC 7591 SHAPE (the contract a real
+// AS honours), which is what makes `registerDynamicClient`'s parse path reachable;
+// the VALUES are illustrative and no POST is ever made to a third party.
+
+export const DCR_PUBLIC_REGISTRATION_RESPONSE = {
+ client_id: 'dyn-public-6f1c2a',
+ client_id_issued_at: 1_758_326_400,
+ token_endpoint_auth_method: 'none',
+ redirect_uris: ['https://control.example.com/api/v1/oauth-callback/remote'],
+ grant_types: ['authorization_code', 'refresh_token'],
+ response_types: ['code'],
+} as const
+
+export const DCR_CONFIDENTIAL_REGISTRATION_RESPONSE = {
+ client_id: 'dyn-conf-9b3d7e',
+ // fixture value, not a live secret — DEC-19
+ client_secret: 'fixture-client-secret-not-probed',
+ client_id_issued_at: 1_758_326_400,
+ client_secret_expires_at: 0, // RFC 7591: 0 ⇒ non-expiring ⇒ stored NULL
+ // fixture value, not a live RFC 7592 bearer — DEC-19
+ registration_access_token: 'fixture-reg-access-token-not-probed',
+ registration_client_uri: 'https://mcp.notion.com/register/dyn-conf-9b3d7e',
+ token_endpoint_auth_method: 'client_secret_post',
+ redirect_uris: ['https://control.example.com/api/v1/oauth-callback/remote'],
+ grant_types: ['authorization_code', 'refresh_token'],
+ response_types: ['code'],
+} as const
+
+/** Same confidential response but the AS overrides the method to one we cannot present. */
+export const DCR_BASIC_REGISTRATION_RESPONSE = {
+ ...DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,
+ token_endpoint_auth_method: 'client_secret_basic',
+} as const
+
+export interface RecordedDcrCall {
+ url: string
+ method: string
+ headers: Record<string, string>
+ body?: string
+}
+
+/**
+ * A {@link PinnedTransport} stub for the DCR POST (and the RFC 7592 rollback
+ * DELETE), recording every call so a test can assert the single-hop POST and the
+ * best-effort management DELETE happened. Zero network (DEC-19). The registration
+ * endpoint returns `responseJson` at `status`; the management URI answers 204 to a
+ * DELETE; anything else 404s.
+ */
+export function makeDcrTransport(opts: {
+ registrationEndpoint?: string
+ responseJson: string
+ status?: number
+ managementUri?: string
+}): { transport: PinnedTransport; calls: RecordedDcrCall[] } {
+ const registrationEndpoint = opts.registrationEndpoint ?? DCR_REGISTRATION_ENDPOINT
+ const status = opts.status ?? 201
+ const calls: RecordedDcrCall[] = []
+ const transport: PinnedTransport = async ({ url, method, headers, body }) => {
+ calls.push({ url, method, headers, body })
+ if (url === registrationEndpoint && method === 'POST') {
+ return {
+ status,
+ headers: { 'content-type': 'application/json' },
+ bodyText: opts.responseJson,
+ }
+ }
+ if (method === 'DELETE') {
+ return { status: 204, headers: {}, bodyText: '' }
+ }
+ return { status: 404, headers: {}, bodyText: 'unexpected url' }
+ }
+ return { transport, calls }
+}
+
+/**
+ * A minimal in-memory `dynamic_clients` DbClient for the store + saga tests. It is
+ * a TEST HARNESS (not a cross-layer fixture, T1): it mirrors the exact parameter
+ * order of `dynamicClientStore.ts`'s own INSERT/SELECT/DELETE, so a store round-trip
+ * (upsert → get) and the saga's rollback (delete) run end-to-end with zero real
+ * Postgres. The encrypted envelope it stores is produced by the real
+ * `encryptOAuthSecret` inside the store, never hand-written.
+ */
+export function makeInMemoryDynamicClientsDb(): {
+ db: DbClient
+ rows: Map<string, Record<string, unknown>>
+} {
+ const rows = new Map<string, Record<string, unknown>>()
+ const keyOf = (owner: unknown, ns: unknown, name: unknown) => `${owner}/${ns}/${name}`
+ const db = {
+ query: async (text: string, values: unknown[] = []) => {
+ if (text.includes('INSERT INTO dynamic_clients')) {
+ const [
+ owner_kind,
+ server_namespace,
+ server_name,
+ issuer,
+ client_id,
+ client_mode,
+ client_secret_encrypted,
+ registration_access_token_encrypted,
+ registration_client_uri,
+ client_id_issued_at,
+ client_secret_expires_at,
+ ] = values
+ rows.set(keyOf(owner_kind, server_namespace, server_name), {
+ owner_kind,
+ server_namespace,
+ server_name,
+ issuer,
+ client_id,
+ client_mode,
+ client_secret_encrypted,
+ registration_access_token_encrypted,
+ registration_client_uri,
+ client_id_issued_at,
+ client_secret_expires_at,
+ created_at: new Date(),
+ updated_at: new Date(),
+ })
+ return { rows: [], rowCount: 1 }
+ }
+ if (text.includes('DELETE FROM dynamic_clients')) {
+ const [owner_kind, server_namespace, server_name] = values
+ const existed = rows.delete(keyOf(owner_kind, server_namespace, server_name))
+ return { rows: [], rowCount: existed ? 1 : 0 }
+ }
+ if (text.includes('FROM dynamic_clients')) {
+ const [owner_kind, server_namespace, server_name] = values
+ const row = rows.get(keyOf(owner_kind, server_namespace, server_name))
+ return { rows: row ? [row] : [], rowCount: row ? 1 : 0 }
+ }
+ return { rows: [], rowCount: 0 }
+ },
+ } as unknown as DbClient
+ return { db, rows }
+}
+
export function makeDiscoveryTransport(pilot: PilotFixture): PinnedTransport {
const jsonByUrl = new Map<string, string>([
[pilot.prm.url, pilot.prm.json],
diff --git a/control-api/test/oauth.dcr.test.ts b/control-api/test/oauth.dcr.test.ts
new file mode 100644
index 000000000..644f55b67
--- /dev/null
+++ b/control-api/test/oauth.dcr.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import { buildDcrRequest, registerDynamicClient } from '../src/oauth/dcr.js'
+import type { DiscoveryResult } from '../src/oauth/discovery.js'
+import {
+ DCR_BASIC_REGISTRATION_RESPONSE,
+ DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,
+ DCR_PUBLIC_REGISTRATION_RESPONSE,
+ DCR_REGISTRATION_ENDPOINT,
+ makeDcrTransport,
+} from './fixtures/remoteOAuthDiscovery.js'
+
+const PUBLIC_IP = async () => ['93.184.216.34']
+
+function discoveryWith(supportsRefresh: boolean): DiscoveryResult {
+ return {
+ prm: { resource: 'https://mcp.notion.com' },
+ as: {
+ issuer: 'https://mcp.notion.com',
+ authorization_endpoint: 'https://mcp.notion.com/authorize',
+ token_endpoint: 'https://mcp.notion.com/token',
+ },
+ resource: 'https://mcp.notion.com',
+ issuer: 'https://mcp.notion.com',
+ endpoints: {
+ authorization: 'https://mcp.notion.com/authorize',
+ token: 'https://mcp.notion.com/token',
+ registration: DCR_REGISTRATION_ENDPOINT,
+ },
+ registrationMode: 'dcr',
+ quirks: { bearerInBody: false, supportsRefresh },
+ }
+}
+
+const REDIRECT_URIS = ['https://control.example.com/api/v1/oauth-callback/remote']
+
+describe('buildDcrRequest (RFC 7591, pure) — T2 property', () => {
+ it('always: response_types=[code], auth method by mode, redirect_uris passthrough, refresh iff advertised', () => {
+ fc.assert(
+ fc.property(
+ fc.constantFrom<'public' | 'confidential'>('public', 'confidential'),
+ fc.boolean(),
+ fc.array(fc.webUrl(), { minLength: 1, maxLength: 3 }),
+ fc.option(fc.array(fc.string({ minLength: 1 }), { maxLength: 4 }), { nil: undefined }),
+ (clientMode, supportsRefresh, redirectUris, scopes) => {
+ const req = buildDcrRequest(discoveryWith(supportsRefresh), {
+ clientMode,
+ redirectUris,
+ scopes,
+ })
+ expect(req.response_types).toEqual(['code'])
+ expect(req.client_name).toBe('Evenfire')
+ expect(req.application_type).toBe('web')
+ expect(req.token_endpoint_auth_method).toBe(
+ clientMode === 'public' ? 'none' : 'client_secret_post'
+ )
+ expect(req.redirect_uris).toEqual(redirectUris)
+ expect(req.grant_types).toContain('authorization_code')
+ expect(req.grant_types.includes('refresh_token')).toBe(supportsRefresh)
+ if (scopes && scopes.length > 0) {
+ expect(req.scope).toBe(scopes.join(' '))
+ } else {
+ expect(req.scope).toBeUndefined()
+ }
+ }
+ )
+ )
+ })
+})
+
+describe('registerDynamicClient (RFC 7591, effectful via injected pinned transport)', () => {
+ const publicReq = buildDcrRequest(discoveryWith(true), {
+ clientMode: 'public',
+ redirectUris: REDIRECT_URIS,
+ })
+ const confReq = buildDcrRequest(discoveryWith(true), {
+ clientMode: 'confidential',
+ redirectUris: REDIRECT_URIS,
+ })
+
+ it('public: parses the RFC 7591 response and returns the assigned client_id', async () => {
+ const { transport, calls } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
+ })
+ const outcome = await registerDynamicClient(
+ { transport, resolveDns: PUBLIC_IP },
+ DCR_REGISTRATION_ENDPOINT,
+ publicReq
+ )
+ expect(outcome.ok).toBe(true)
+ if (outcome.ok) expect(outcome.response.client_id).toBe('dyn-public-6f1c2a')
+ // Single hop POST with content-type + content-length.
+ expect(calls).toHaveLength(1)
+ expect(calls[0].method).toBe('POST')
+ expect(calls[0].headers['content-type']).toBe('application/json')
+ expect(calls[0].headers['content-length']).toBe(String(Buffer.byteLength(calls[0].body ?? '')))
+ })
+
+ it('confidential: returns the client_secret + registration_access_token', async () => {
+ const { transport } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
+ })
+ const outcome = await registerDynamicClient(
+ { transport, resolveDns: PUBLIC_IP },
+ DCR_REGISTRATION_ENDPOINT,
+ confReq
+ )
+ expect(outcome.ok).toBe(true)
+ if (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')
+ }
+ })
+
+ it('FAIL-CLOSED: AS assigns client_secret_basic → auth_method_unsupported (nothing usable)', async () => {
+ const { transport } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_BASIC_REGISTRATION_RESPONSE),
+ })
+ 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')
+ })
+
+ it('a 3xx on the registration POST is redirect_blocked (never re-POSTed to Location)', async () => {
+ const { transport } = makeDcrTransport({ responseJson: '', status: 302 })
+ const outcome = await registerDynamicClient(
+ { transport, resolveDns: PUBLIC_IP },
+ DCR_REGISTRATION_ENDPOINT,
+ publicReq
+ )
+ expect(outcome.ok).toBe(false)
+ if (!outcome.ok) expect(outcome.error.kind).toBe('redirect_blocked')
+ })
+
+ it('a 4xx with an OAuth error body surfaces error/error_description', async () => {
+ const { transport } = makeDcrTransport({
+ responseJson: JSON.stringify({
+ error: 'invalid_redirect_uri',
+ error_description: 'unregistered uri',
+ }),
+ status: 400,
+ })
+ const outcome = await registerDynamicClient(
+ { transport, resolveDns: PUBLIC_IP },
+ DCR_REGISTRATION_ENDPOINT,
+ publicReq
+ )
+ expect(outcome.ok).toBe(false)
+ if (!outcome.ok) {
+ expect(outcome.error.kind).toBe('fetch_failed')
+ if (outcome.error.kind === 'fetch_failed') {
+ expect(outcome.error.status).toBe(400)
+ expect(outcome.error.detail).toContain('invalid_redirect_uri')
+ expect(outcome.error.detail).toContain('unregistered uri')
+ }
+ }
+ })
+
+ it('a 2xx body without client_id is invalid_response', async () => {
+ const { transport } = makeDcrTransport({ responseJson: JSON.stringify({ foo: 'bar' }) })
+ const outcome = await registerDynamicClient(
+ { transport, resolveDns: PUBLIC_IP },
+ DCR_REGISTRATION_ENDPOINT,
+ publicReq
+ )
+ expect(outcome.ok).toBe(false)
+ if (!outcome.ok) expect(outcome.error.kind).toBe('invalid_response')
+ })
+
+ it('a confidential registration that returns no client_secret is invalid_response', async () => {
+ const { transport } = makeDcrTransport({
+ responseJson: JSON.stringify({
+ client_id: 'x',
+ token_endpoint_auth_method: 'client_secret_post',
+ }),
+ })
+ 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('invalid_response')
+ })
+
+ it('a non-https registration endpoint is kernel_rejected before any POST', async () => {
+ const { transport, calls } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
+ })
+ const outcome = await registerDynamicClient(
+ { transport, resolveDns: PUBLIC_IP },
+ 'http://mcp.notion.com/register',
+ publicReq
+ )
+ expect(outcome.ok).toBe(false)
+ if (!outcome.ok) expect(outcome.error.kind).toBe('kernel_rejected')
+ // Fail-closed: the transport was never invoked.
+ expect(calls).toHaveLength(0)
+ })
+})
diff --git a/control-api/test/oauth.dynamicClientStore.test.ts b/control-api/test/oauth.dynamicClientStore.test.ts
new file mode 100644
index 000000000..c7b665c9f
--- /dev/null
+++ b/control-api/test/oauth.dynamicClientStore.test.ts
@@ -0,0 +1,174 @@
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import { config } from '../src/config.js'
+import type { DbClient } from '../src/db.js'
+import {
+ deleteDynamicClient,
+ getDynamicClient,
+ upsertDynamicClient,
+} from '../src/oauth/dynamicClientStore.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { makeInMemoryDynamicClientsDb } from './fixtures/remoteOAuthDiscovery.js'
+
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+
+function fakeDb(
+ rows: unknown[] = [],
+ rowCount?: number
+): { db: DbClient; calls: { text: string; values: unknown[] }[] } {
+ const calls: { text: string; values: unknown[] }[] = []
+ const db = {
+ query: async (text: string, values: unknown[] = []) => {
+ calls.push({ text, values })
+ return { rows, rowCount: rowCount ?? rows.length } as never
+ },
+ } as unknown as DbClient
+ return { db, calls }
+}
+
+const CONF_KEY = {
+ ownerKind: 'mcpserver' as const,
+ serverNamespace: 'mcp-server',
+ serverName: 'vercel-remote',
+}
+
+describe('dynamicClientStore — upsert SQL + encryption at rest', () => {
+ it('upsert INSERTs … ON CONFLICT DO UPDATE keyed by (owner_kind, server_namespace, server_name)', async () => {
+ const { db, calls } = fakeDb([], 1)
+ await upsertDynamicClient(db, KEY, {
+ ...CONF_KEY,
+ issuer: 'https://as.example.com',
+ clientId: 'cid-1',
+ clientMode: 'confidential',
+ clientSecret: 'shhh',
+ registrationAccessToken: 'reg-bearer',
+ registrationClientUri: 'https://as.example.com/register/cid-1',
+ clientIdIssuedAtSec: 1_758_326_400,
+ clientSecretExpiresAtSec: 0,
+ })
+ expect(calls[0].text).toContain('INSERT INTO dynamic_clients')
+ expect(calls[0].text).toContain('ON CONFLICT (owner_kind, server_namespace, server_name)')
+ expect(calls[0].text).toContain('DO UPDATE SET')
+ expect(calls[0].values.slice(0, 6)).toEqual([
+ 'mcpserver',
+ 'mcp-server',
+ 'vercel-remote',
+ 'https://as.example.com',
+ 'cid-1',
+ 'confidential',
+ ])
+ // The secret + registration token are stored as v1 envelopes, NEVER plaintext.
+ const [secretEnc, regEnc] = [calls[0].values[6], calls[0].values[7]] as [string, string]
+ expect(secretEnc).not.toBe('shhh')
+ expect(secretEnc.startsWith('v1.')).toBe(true)
+ expect(regEnc).not.toBe('reg-bearer')
+ expect(regEnc.startsWith('v1.')).toBe(true)
+ // client_secret_expires_at seconds 0 ⇒ NULL (non-expiring).
+ expect(calls[0].values[10]).toBeNull()
+ // client_id_issued_at seconds → Date.
+ expect(calls[0].values[9]).toBeInstanceOf(Date)
+ })
+
+ it('a public client stores NULL for the secret + registration token', async () => {
+ const { db, calls } = fakeDb([], 1)
+ await upsertDynamicClient(db, KEY, {
+ ...CONF_KEY,
+ issuer: 'https://as.example.com',
+ clientId: 'cid-public',
+ clientMode: 'public',
+ })
+ expect(calls[0].values[5]).toBe('public')
+ expect(calls[0].values[6]).toBeNull()
+ expect(calls[0].values[7]).toBeNull()
+ })
+
+ it('delete is a hard DELETE keyed by owner coordinates, returning rowCount (idempotent)', async () => {
+ const { db, calls } = fakeDb([], 0)
+ const removed = await deleteDynamicClient(db, CONF_KEY)
+ expect(removed).toBe(0)
+ expect(calls[0].text).toContain('DELETE FROM dynamic_clients')
+ expect(calls[0].values).toEqual(['mcpserver', 'mcp-server', 'vercel-remote'])
+ })
+
+ it('defaults ownerKind to mcpserver when omitted', async () => {
+ const { db, calls } = fakeDb([], 1)
+ await deleteDynamicClient(db, { serverNamespace: 'mcp-server', serverName: 'x' })
+ expect(calls[0].values[0]).toBe('mcpserver')
+ })
+})
+
+describe('dynamicClientStore — round-trip (T1: envelope from the real producer)', () => {
+ it('upsert → get returns the decrypted secret + registration token, expiry mapped', async () => {
+ const { db } = makeInMemoryDynamicClientsDb()
+ await upsertDynamicClient(db, KEY, {
+ ...CONF_KEY,
+ issuer: 'https://as.example.com',
+ clientId: 'cid-rt',
+ clientMode: 'confidential',
+ clientSecret: 'round-trip-secret',
+ registrationAccessToken: 'round-trip-bearer',
+ registrationClientUri: 'https://as.example.com/register/cid-rt',
+ clientIdIssuedAtSec: 1_758_326_400,
+ clientSecretExpiresAtSec: 1_758_412_800,
+ })
+ const row = await getDynamicClient(db, KEY, CONF_KEY)
+ expect(row).not.toBeNull()
+ expect(row?.clientId).toBe('cid-rt')
+ expect(row?.clientMode).toBe('confidential')
+ expect(row?.clientSecret).toBe('round-trip-secret')
+ expect(row?.registrationAccessToken).toBe('round-trip-bearer')
+ expect(row?.registrationClientUri).toBe('https://as.example.com/register/cid-rt')
+ expect(row?.clientSecretExpiresAt).toBeInstanceOf(Date)
+ })
+
+ it('a public client round-trips with undefined secret/registration token', async () => {
+ const { db } = makeInMemoryDynamicClientsDb()
+ await upsertDynamicClient(db, KEY, {
+ ...CONF_KEY,
+ issuer: 'https://as.example.com',
+ clientId: 'cid-pub',
+ clientMode: 'public',
+ })
+ const row = await getDynamicClient(db, KEY, CONF_KEY)
+ expect(row?.clientSecret).toBeUndefined()
+ expect(row?.registrationAccessToken).toBeUndefined()
+ expect(row?.clientSecretExpiresAt).toBeUndefined()
+ })
+
+ it('get returns null when no row exists', async () => {
+ const { db } = makeInMemoryDynamicClientsDb()
+ expect(await getDynamicClient(db, KEY, CONF_KEY)).toBeNull()
+ })
+
+ // T2 — property: for any secret/token strings, the store never persists plaintext
+ // and always round-trips; re-upserting the same input is idempotent on read.
+ it('round-trips arbitrary secret material without ever storing plaintext (T2)', () => {
+ fc.assert(
+ fc.asyncProperty(
+ fc.string({ minLength: 1 }),
+ fc.string({ minLength: 1 }),
+ async (clientSecret, registrationAccessToken) => {
+ const { db, rows } = makeInMemoryDynamicClientsDb()
+ const input = {
+ ...CONF_KEY,
+ issuer: 'https://as.example.com',
+ clientId: 'cid-prop',
+ clientMode: 'confidential' as const,
+ clientSecret,
+ registrationAccessToken,
+ }
+ await upsertDynamicClient(db, KEY, input)
+ // idempotent: a second identical upsert overwrites in place, still one row.
+ await upsertDynamicClient(db, KEY, input)
+ expect(rows.size).toBe(1)
+ const stored = [...rows.values()][0]
+ expect(stored.client_secret_encrypted).not.toBe(clientSecret)
+ expect(stored.registration_access_token_encrypted).not.toBe(registrationAccessToken)
+ const row = await getDynamicClient(db, KEY, CONF_KEY)
+ expect(row?.clientSecret).toBe(clientSecret)
+ expect(row?.registrationAccessToken).toBe(registrationAccessToken)
+ }
+ )
+ )
+ })
+})
diff --git a/control-api/test/routes.adminRemoteMcp.test.ts b/control-api/test/routes.adminRemoteMcp.test.ts
index 311d35b28..e6d85aecd 100644
--- a/control-api/test/routes.adminRemoteMcp.test.ts
+++ b/control-api/test/routes.adminRemoteMcp.test.ts
@@ -1,4 +1,4 @@
-import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
import { config } from '../src/config.js'
@@ -8,8 +8,22 @@ import {
type DiscoveryResult,
discoverRemoteOAuth,
} from '../src/oauth/discovery.js'
-import { createAdminRemoteMcpRouter } from '../src/routes/admin/remoteMcp.js'
-import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'
+import { decryptOAuthSecret, deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import {
+ type AdminRemoteMcpDeps,
+ createAdminRemoteMcpRouter,
+} from '../src/routes/admin/remoteMcp.js'
+import {
+ DCR_BASIC_REGISTRATION_RESPONSE,
+ DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,
+ DCR_PUBLIC_REGISTRATION_RESPONSE,
+ DCR_REGISTRATION_ENDPOINT,
+ PILOTS,
+ dcrPilot,
+ makeDcrTransport,
+ makeDiscoveryTransport,
+ makeInMemoryDynamicClientsDb,
+} from './fixtures/remoteOAuthDiscovery.js'
import { MockGateway } from './mockGateway.js'
/**
@@ -104,16 +118,18 @@ describe('POST /admin/mcp-servers/remote/discover (dry-run)', () => {
expect(res.body.detected.dcr).toBeUndefined()
})
- it('marks DCR mode unavailable (not failed) → 200 with dcr.available=false', async () => {
+ it('marks DCR mode available (C2) with resolved clientMode + supportsRefresh → 200', async () => {
mockDiscovery({ ...notionResult, registrationMode: 'dcr' })
const res = await request(makeApp(gatewayWithContext()))
.post('/admin/mcp-servers/remote/discover')
.send({ baseUrl: 'https://mcp.example.com/mcp' })
expect(res.status).toBe(200)
expect(res.body.detected.registrationMode).toBe('dcr')
+ // Notion's AS lists `none` in its auth methods → public DCR client.
expect(res.body.detected.dcr).toEqual({
- available: false,
- message: 'requires DCR (not available until C2)',
+ available: true,
+ clientMode: 'public',
+ supportsRefresh: true,
})
})
@@ -209,16 +225,18 @@ describe('POST /admin/mcp-servers/remote (install saga)', () => {
})
})
- it('rejects DCR mode → 400 dcr_not_available', async () => {
+ it('rejects mode "dcr" when server-side discovery resolves a non-DCR AS → 400 mode_unsupported', async () => {
+ // The AS actually offers CIMD (not DCR); the operator's "dcr" request loses.
+ mockDiscovery(notionResult)
const gw = gatewayWithContext('ctx-a')
const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
serverName: 'stripe-remote',
contextRef: 'ctx-a',
- baseUrl: 'https://mcp.example.com/mcp',
+ baseUrl: 'https://mcp.notion.com/mcp',
mode: 'dcr',
})
expect(res.status).toBe(400)
- expect(res.body.error).toBe('dcr_not_available')
+ expect(res.body.error).toBe('mode_unsupported')
// No CR written.
await expect(gw.getResource('mcpservers', 'stripe-remote', NS)).rejects.toThrow()
})
@@ -235,7 +253,7 @@ describe('POST /admin/mcp-servers/remote (install saga)', () => {
expect(res.status).toBe(400)
})
- it('CIMD requested but AS is DCR-only → 400 (server-side discovery is authoritative)', async () => {
+ it('CIMD requested but AS is DCR-only → 400 mode_unsupported (server-side discovery is authoritative)', async () => {
mockDiscovery({ ...notionResult, registrationMode: 'dcr' })
const gw = gatewayWithContext('ctx-a')
const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
@@ -245,7 +263,7 @@ describe('POST /admin/mcp-servers/remote (install saga)', () => {
mode: 'cimd',
})
expect(res.status).toBe(400)
- expect(res.body.error).toBe('dcr_not_available')
+ expect(res.body.error).toBe('mode_unsupported')
})
it('rolls back the Secret when the CR create fails', async () => {
@@ -316,3 +334,328 @@ describe('POST /admin/mcp-servers/remote (install saga)', () => {
expect(res.status).toBe(400)
})
})
+
+// ─── C2: DCR install saga (spec 02 C2, DEC-18/DEC-19) ───────────────────────
+describe('POST /admin/mcp-servers/remote — DCR install saga (C2)', () => {
+ const ENC_KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+ const PUBLIC_IP = async () => ['93.184.216.34']
+ // The DCR request needs a configured public callback origin for redirect_uris.
+ let savedCallbackBaseUrl: string
+
+ // Real DCR DiscoveryResults, DERIVED FROM THE REAL PRODUCER by documented
+ // subtraction (DEC-19): the actual discovery client is run against the Notion
+ // probe with CIMD support removed (→ DCR) and, for confidential, `none` dropped.
+ let dcrPublicResult: DiscoveryResult
+ let dcrConfidentialResult: DiscoveryResult
+
+ beforeAll(async () => {
+ const actual = await vi.importActual<typeof import('../src/oauth/discovery.js')>(
+ '../src/oauth/discovery.js'
+ )
+ for (const [mode, assign] of [
+ ['public', (r: DiscoveryResult) => (dcrPublicResult = r)],
+ ['confidential', (r: DiscoveryResult) => (dcrConfidentialResult = r)],
+ ] as const) {
+ const pilot = dcrPilot(mode)
+ const outcome = await actual.discoverRemoteOAuth(pilot.mcpUrl, {
+ transport: makeDiscoveryTransport(pilot),
+ resolveDns: PUBLIC_IP,
+ })
+ if (!outcome.ok) throw new Error(`dcr fixture discovery failed: ${outcome.error.kind}`)
+ expect(outcome.result.registrationMode).toBe('dcr')
+ assign(outcome.result)
+ }
+ })
+
+ beforeEach(() => {
+ vi.mocked(discoverRemoteOAuth).mockReset()
+ savedCallbackBaseUrl = config.oauthCallbackBaseUrl
+ config.oauthCallbackBaseUrl = 'https://control.example.com'
+ })
+
+ afterEach(() => {
+ config.oauthCallbackBaseUrl = savedCallbackBaseUrl
+ })
+
+ function makeAppWithDeps(gateway: MockGateway, deps: AdminRemoteMcpDeps) {
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminRemoteMcpRouter(gateway as unknown as K8sGateway, 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' })
+ }
+ )
+ return app
+ }
+
+ // T3(a) — fails at parent 9e4677652: DCR install returns 400 dcr_not_available there.
+ it('public DCR → 201, persists a dynamic_clients row, sets spec.oauth.id, no Secret refs', async () => {
+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrPublicResult })
+ const { db, rows } = makeInMemoryDynamicClientsDb()
+ const { transport } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
+ })
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(
+ makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
+ )
+ .post('/admin/mcp-servers/remote')
+ .send({
+ serverName: 'notion-dcr',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'dcr',
+ })
+ expect(res.status).toBe(201)
+ expect(res.body).toMatchObject({
+ serverName: 'notion-dcr',
+ clientMode: 'public',
+ registrationMode: 'dcr',
+ })
+ // A dynamic_clients row was persisted.
+ expect(rows.size).toBe(1)
+ const stored = [...rows.values()][0]
+ expect(stored.client_id).toBe(DCR_PUBLIC_REGISTRATION_RESPONSE.client_id)
+ // Public → no secret persisted.
+ expect(stored.client_secret_encrypted).toBeNull()
+
+ const cr = (await gw.getResource('mcpservers', 'notion-dcr', NS)) as {
+ spec: { oauth: Record<string, unknown> }
+ }
+ expect(cr.spec.oauth.id).toBe(DCR_PUBLIC_REGISTRATION_RESPONSE.client_id)
+ expect(cr.spec.oauth.clientMode).toBe('public')
+ // The C4 discriminator: DCR omits the K8s Secret refs.
+ expect(cr.spec.oauth.clientIdRef).toBeUndefined()
+ expect(cr.spec.oauth.clientSecretRef).toBeUndefined()
+ })
+
+ // T3(a)+T3(c) — fails at parent: no row, no encrypted envelope.
+ it('confidential DCR → 201, NO K8s Secret, secret persisted as an encrypted envelope', async () => {
+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
+ const { db, rows } = makeInMemoryDynamicClientsDb()
+ const { transport } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
+ })
+ 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-dcr',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'dcr',
+ })
+ expect(res.status).toBe(201)
+ expect(res.body.clientMode).toBe('confidential')
+
+ // DEC-8: a DCR-confidential client gets NO K8s Secret — the secret lives in the store.
+ await expect(gw.getSecret('vercel-dcr-oauth-client', NS)).rejects.toThrow()
+
+ // T3(c): the stored secret is an encrypted envelope, never plaintext, and it
+ // decrypts back to the registration secret.
+ const stored = [...rows.values()][0]
+ const secretEnc = stored.client_secret_encrypted as string
+ expect(secretEnc).not.toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.client_secret)
+ expect(secretEnc.startsWith('v1.')).toBe(true)
+ expect(decryptOAuthSecret(ENC_KEY, secretEnc)).toBe(
+ DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.client_secret
+ )
+ // The RFC 7592 registration_access_token is also stored encrypted.
+ const regEnc = stored.registration_access_token_encrypted as string
+ expect(regEnc.startsWith('v1.')).toBe(true)
+ expect(decryptOAuthSecret(ENC_KEY, regEnc)).toBe(
+ DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_access_token
+ )
+
+ const cr = (await gw.getResource('mcpservers', 'vercel-dcr', NS)) as {
+ spec: { oauth: Record<string, unknown> }
+ }
+ expect(cr.spec.oauth.id).toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.client_id)
+ expect(cr.spec.oauth.clientMode).toBe('confidential')
+ 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 () => {
+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
+ const { db, rows } = makeInMemoryDynamicClientsDb()
+ const { transport, calls } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_BASIC_REGISTRATION_RESPONSE),
+ })
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(
+ makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
+ )
+ .post('/admin/mcp-servers/remote')
+ .send({
+ serverName: 'basic-dcr',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'dcr',
+ })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('auth_method_unsupported')
+ // Fail-closed: no row persisted, no CR written.
+ expect(rows.size).toBe(0)
+ await expect(gw.getResource('mcpservers', 'basic-dcr', NS)).rejects.toThrow()
+ // The AS DID mint a client (2xx + client_id) before we rejected the auth method —
+ // a best-effort RFC 7592 DELETE against its management endpoint was attempted.
+ const deleteCall = calls.find(c => c.method === 'DELETE')
+ expect(deleteCall?.url).toBe(DCR_BASIC_REGISTRATION_RESPONSE.registration_client_uri)
+ expect(deleteCall?.headers.authorization).toBe(
+ `Bearer ${DCR_BASIC_REGISTRATION_RESPONSE.registration_access_token}`
+ )
+ })
+
+ it('rolls back the dynamic client (local delete + best-effort RFC 7592 DELETE) when the CR create fails', async () => {
+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
+ const { db, rows } = makeInMemoryDynamicClientsDb()
+ const { transport, calls } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
+ })
+ const gw = gatewayWithContext('ctx-a')
+ const k8sErr = Object.assign(new Error('already exists'), { code: 409 })
+ vi.spyOn(gw, 'createResource').mockRejectedValueOnce(k8sErr)
+ const res = await request(
+ makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
+ )
+ .post('/admin/mcp-servers/remote')
+ .send({
+ serverName: 'rollback-dcr',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'dcr',
+ })
+ expect(res.status).toBe(409)
+ // Local store row deleted.
+ expect(rows.size).toBe(0)
+ // Best-effort RFC 7592 DELETE against the management endpoint was attempted.
+ const deleteCall = calls.find(c => c.method === 'DELETE')
+ expect(deleteCall?.url).toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri)
+ expect(deleteCall?.headers.authorization).toBe(
+ `Bearer ${DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_access_token}`
+ )
+ })
+
+ // T3(a) — fails at parent ffb2005: the persist had no try/catch there, so the
+ // upsert throw unwound to a 500 with NO cleanup of the just-minted AS client.
+ it('cleans up the minted client and returns 503 when the local persist throws', async () => {
+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
+ const { db: baseDb, rows } = makeInMemoryDynamicClientsDb()
+ // Inject a store whose INSERT rejects (e.g. pool exhausted / encryption error).
+ // DELETE still routes to the in-memory store so the idempotent local revocation
+ // runs (the row never landed → 0 rows removed).
+ const db = {
+ query: async (text: string, values: unknown[] = []) => {
+ if (text.includes('INSERT INTO dynamic_clients')) throw new Error('pool exhausted')
+ return baseDb.query(text, values)
+ },
+ } as unknown as typeof baseDb
+ const { transport, calls } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
+ })
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(
+ makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
+ )
+ .post('/admin/mcp-servers/remote')
+ .send({
+ serverName: 'persistfail-dcr',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'dcr',
+ })
+ // Transient/server-side, not a client error.
+ expect(res.status).toBe(503)
+ expect(res.body.error).toBe('dcr_persist_failed')
+ // No dynamic_clients row remains (the INSERT rejected; nothing orphaned locally).
+ expect(rows.size).toBe(0)
+ // The AS client minted before the persist failed was cleaned up: a best-effort
+ // RFC 7592 DELETE against its management endpoint was attempted.
+ const deleteCall = calls.find(c => c.method === 'DELETE')
+ expect(deleteCall?.url).toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri)
+ expect(deleteCall?.headers.authorization).toBe(
+ `Bearer ${DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_access_token}`
+ )
+ // The CR was never created (we aborted before the saga's step-2).
+ await expect(gw.getResource('mcpservers', 'persistfail-dcr', NS)).rejects.toThrow()
+ })
+
+ it('rolls back the dynamic client when the Context attach fails', async () => {
+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
+ const { db, rows } = makeInMemoryDynamicClientsDb()
+ const { transport, calls } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
+ })
+ // Context exists at the step-0 precheck, then the ATTACH update fails.
+ const gw = gatewayWithContext('ctx-a')
+ vi.spyOn(gw, 'updateResource').mockRejectedValueOnce(new Error('attach boom'))
+ const res = await request(
+ makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
+ )
+ .post('/admin/mcp-servers/remote')
+ .send({
+ serverName: 'attach-dcr',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'dcr',
+ })
+ expect(res.status).toBeGreaterThanOrEqual(400)
+ expect(rows.size).toBe(0)
+ expect(calls.some(c => c.method === 'DELETE')).toBe(true)
+ // The CR minted before attach is rolled back too.
+ await expect(gw.getResource('mcpservers', 'attach-dcr', NS)).rejects.toThrow()
+ })
+
+ it('DCR with an unconfigured public callback base URL → 503, nothing registered', async () => {
+ config.oauthCallbackBaseUrl = ''
+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrPublicResult })
+ const { db, rows } = makeInMemoryDynamicClientsDb()
+ const { transport, calls } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
+ })
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(
+ makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
+ )
+ .post('/admin/mcp-servers/remote')
+ .send({
+ serverName: 'unconfigured-dcr',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'dcr',
+ })
+ expect(res.status).toBe(503)
+ expect(res.body.error).toBe('callback_base_url_unconfigured')
+ // Fail-closed BEFORE any registration POST.
+ expect(calls).toHaveLength(0)
+ expect(rows.size).toBe(0)
+ })
+
+ it('DCR against a missing Context → 404 before minting a throwaway client', async () => {
+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrPublicResult })
+ const { db, rows } = makeInMemoryDynamicClientsDb()
+ const { transport, calls } = makeDcrTransport({
+ responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
+ })
+ const gw = new MockGateway(NS) // no Context seeded
+ const res = await request(
+ makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
+ )
+ .post('/admin/mcp-servers/remote')
+ .send({
+ serverName: 'noctx-dcr',
+ contextRef: 'missing-ctx',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'dcr',
+ })
+ expect(res.status).toBe(404)
+ // No registration POST fired; no row persisted.
+ expect(calls).toHaveLength(0)
+ expect(rows.size).toBe(0)
+ })
+})
diff --git a/control-api/test/utils.log.redact.test.ts b/control-api/test/utils.log.redact.test.ts
index 9ec748f57..ce6597281 100644
--- a/control-api/test/utils.log.redact.test.ts
+++ b/control-api/test/utils.log.redact.test.ts
@@ -40,6 +40,13 @@ describe('token-leak redaction', () => {
}
})
+ it('redacts the RFC 7592 DCR registration_access_token in both snake and camel case', () => {
+ for (const p of ['registration_access_token', 'registrationAccessToken']) {
+ expect(TOKEN_LEAK_REDACT_PATHS).toContain(p)
+ expect(REQUIRED_REDACT_PATHS).toContain(p)
+ }
+ })
+
it('redacts the PKCE code_verifier (U2) in both snake and camel case', () => {
for (const p of ['code_verifier', 'codeVerifier']) {
expect(TOKEN_LEAK_REDACT_PATHS).toContain(p)