Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): install remote servers without RFC 9207 via a per-server callback
Diego Zacariasd7c00ac51756
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 9d353c859..3562756f7 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.681",+ "version": "0.1.682","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.681",+ "version": "0.1.682","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 d8e807591..08002c0c1 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.681",+ "version": "0.1.682","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/callback.ts b/control-api/src/oauth/callback.tsindex 1b867df37..c6c590ca9 100644--- a/control-api/src/oauth/callback.ts+++ b/control-api/src/oauth/callback.ts@@ -63,6 +63,11 @@ export interface RemoteClientRouting {supportsRefresh: boolean/** RFC 9207 issuer to validate the callback `iss` against, when advertised. */issForCallback?: string+ /**+ * The pinned AS issuer. Without RFC 9207 an AS may still send `iss`; when it does,+ * it must match this value rather than being ignored.+ */+ issuer?: string}/**diff --git a/control-api/src/oauth/cimd.ts b/control-api/src/oauth/cimd.tsindex 1a03248e4..d5f6d5387 100644--- a/control-api/src/oauth/cimd.ts+++ b/control-api/src/oauth/cimd.ts@@ -2,6 +2,7 @@ import { Router } from 'express'import { config } from '../config.js'import { type Logger, rootLogger } from '../observability/logger.js'import { normalizeConfiguredOrigin } from '../routes/external/oauthCallback.js'+import { CIMD_PUBLIC_PATH, CIMD_ROUTE_PATH } from './cimdIdentity.js'import { REMOTE_CALLBACK_PATH, buildRemoteRedirectUri } from './remoteCallback.js'/**@@ -35,11 +36,7 @@ export interface CimdDocument {application_type: 'web'}-/** Path the CIMD document is served at, relative to the `/api/v1` mount in app.ts. */-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}`+export { CIMD_ROUTE_PATH }// The shared remote callback path, defined by the single redirect-URI builder// (`remoteCallback.ts`). Re-exported for the existing importers of this module.@@ -48,8 +45,8 @@ export { REMOTE_CALLBACK_PATH }/*** Build the frozen CIMD document for a given public `origin` (scheme://host, no* trailing slash — as produced by `normalizeConfiguredOrigin`). `client_id` is the- * document's own URL (SEP-991); `redirect_uris` carries the stable remote callback- * segment. The result is `Object.freeze`d so no caller can mutate the served+ * document's own URL (SEP-991); `redirect_uris` carries only the shared remote+ * callback, never a per-server URI (see {@link CimdDocument.redirect_uris}). The result is `Object.freeze`d so no caller can mutate the served* identity in place (S-6).*/export function buildCimdDocument(origin: string): Readonly<CimdDocument> {diff --git a/control-api/src/oauth/cimdIdentity.ts b/control-api/src/oauth/cimdIdentity.tsnew file mode 100644index 000000000..37c34c89b--- /dev/null+++ b/control-api/src/oauth/cimdIdentity.ts@@ -0,0 +1,43 @@+/**+ * The platform CIMD client identity, without the router. Kept import-free so the+ * coherence reader (`mcpServerOAuthSpec.ts`) can recognise the CIMD client_id without+ * importing `cimd.ts`, which reaches the callback route and would close an import+ * cycle back to the reader.+ */++/** Path the CIMD document is served at, relative to the `/api/v1` mount in app.ts. */+export const CIMD_ROUTE_PATH = '/.well-known/evenfire-mcp-client'++/** Full public path of the served document (what `client_id` must equal, minus origin). */+export const CIMD_PUBLIC_PATH = `/api/v1${CIMD_ROUTE_PATH}`++// The CRD caps `spec.oauth.id` at 512: a longer client_id could never be written to the+// McpServer, so an install would only discover it after minting a client at the AS.+// Refusing it up front also bounds the work spent on attacker-supplied input.+export const MAX_CLIENT_ID_LENGTH = 512++const CIMD_PUBLIC_PATH_LOWER = CIMD_PUBLIC_PATH.toLowerCase()++/**+ * Whether a client_id names the platform CIMD document, on ANY origin.+ *+ * Matching the path rather than the currently configured origin is deliberate: a CR+ * written under an earlier public origin, or one that reaches us through an alias host,+ * still carries the one platform-wide identity whose document lists only the shared+ * callback. Express routes this path case-insensitively and with a trailing slash, so+ * those spellings are matched too. A false positive only rejects an id nobody but us+ * (or an attacker imitating us) would mint. Plain comparisons only: the input is+ * third-party data, and a backtracking pattern over a long run of `/` is quadratic.+ */+export function isCimdClientId(value: unknown): boolean {+ if (typeof value !== 'string' || value.length === 0) return false+ if (value.length > MAX_CLIENT_ID_LENGTH) return false+ let parsed: URL+ try {+ parsed = new URL(value)+ } catch {+ return false+ }+ const path = parsed.pathname.toLowerCase()+ return path === CIMD_PUBLIC_PATH_LOWER || path === `${CIMD_PUBLIC_PATH_LOWER}/`+}diff --git a/control-api/src/oauth/dcr.ts b/control-api/src/oauth/dcr.tsindex 30128b7dc..1de458b21 100644--- a/control-api/src/oauth/dcr.ts+++ b/control-api/src/oauth/dcr.ts@@ -1,6 +1,7 @@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 { MAX_CLIENT_ID_LENGTH } from './cimdIdentity.js'import type { DiscoveryResult } from './discovery.js'import type { RemoteCallbackVariant } from './remoteCallback.js'@@ -78,6 +79,11 @@ export interface DcrRegistrationResponse {* In-memory only — used solely for the cleanup DELETE, never persisted or logged.*/export interface DcrMintHandle {+ /**+ * Set when a client WAS minted at the AS, with or without a management handle, so+ * the caller can tell "cleaned up" from "left behind" when the handle is missing.+ */+ minted?: trueregistrationClientUri?: stringregistrationAccessToken?: string}@@ -265,6 +271,22 @@ export async function registerDynamicClient(const assigned = parsed as DcrRegistrationResponse+ // An oversized client_id is refused before anything compares, stores or logs it. A+ // client WAS minted, so the RFC 7592 handle goes back for cleanup.+ if (Buffer.byteLength(assigned.client_id, 'utf8') > MAX_CLIENT_ID_LENGTH) {+ return {+ ok: false,+ error: {+ kind: 'invalid_response',+ url: endpoint,+ detail: `registration response client_id exceeds ${MAX_CLIENT_ID_LENGTH} bytes`,+ minted: true,+ registrationClientUri: stringOrUndefined(assigned.registration_client_uri),+ registrationAccessToken: stringOrUndefined(assigned.registration_access_token),+ },+ }+ }+// Fail-closed on an auth method we cannot present. The AS's assignment wins over// 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@@ -288,6 +310,7 @@ export async function registerDynamicClient(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.+ minted: true,registrationClientUri: assigned.registration_client_uri,registrationAccessToken: assigned.registration_access_token,},@@ -314,6 +337,7 @@ export async function registerDynamicClient(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.+ minted: true,registrationClientUri: assigned.registration_client_uri,registrationAccessToken: assigned.registration_access_token,},@@ -328,6 +352,10 @@ export async function registerDynamicClient(}}+function stringOrUndefined(value: unknown): string | undefined {+ return typeof value === 'string' && value.length > 0 ? value : undefined+}+export type DcrRedirectUrisCheck =| { ok: true }| { ok: false; reason: 'redirect_uris_missing' | 'redirect_uris_mismatch' }diff --git a/control-api/src/oauth/discovery.ts b/control-api/src/oauth/discovery.tsindex 2b15a380c..761be26c2 100644--- a/control-api/src/oauth/discovery.ts+++ b/control-api/src/oauth/discovery.ts@@ -110,6 +110,24 @@ export function selectRegistrationMode(input: SelectRegistrationModeInput): Regireturn 'manual'}+/**+ * The metadata-derived inputs of {@link selectRegistrationMode}, in one place so a+ * caller asking "what would this AS resolve to" reads the metadata exactly as+ * discovery does.+ */+export function registrationModeInputs(+ as: AuthorizationServerMetadata,+ opts: { hasPreRegisteredClient: boolean }+): SelectRegistrationModeInput {+ return {+ hasPreRegisteredClient: opts.hasPreRegisteredClient,+ cimdSupported: as.client_id_metadata_document_supported === true,+ tokenEndpointAuthMethods: as.token_endpoint_auth_methods_supported ?? [],+ hasRegistrationEndpoint: typeof as.registration_endpoint === 'string',+ issBindingSupported: advertisesIssBinding(as),+ }+}+/*** RFC 9207: the AS advertises that it returns `iss` on the authorization response.* The ONE expression behind both `issForCallback` and the registration-mode choice, so@@ -758,13 +776,11 @@ export async function discoverRemoteOAuth(}}- const registrationMode = selectRegistrationMode({- hasPreRegisteredClient: opts.hasPreRegisteredClient ?? false,- cimdSupported: as.client_id_metadata_document_supported === true,- tokenEndpointAuthMethods: as.token_endpoint_auth_methods_supported ?? [],- hasRegistrationEndpoint: typeof as.registration_endpoint === 'string',- issBindingSupported,- })+ const registrationMode = selectRegistrationMode(+ registrationModeInputs(as, {+ hasPreRegisteredClient: opts.hasPreRegisteredClient ?? false,+ })+ )return {ok: true,diff --git a/control-api/src/oauth/dynamicClientStore.ts b/control-api/src/oauth/dynamicClientStore.tsindex 6f7212777..ee272edc7 100644--- a/control-api/src/oauth/dynamicClientStore.ts+++ b/control-api/src/oauth/dynamicClientStore.ts@@ -246,6 +246,25 @@ export async function getDynamicClient(}}+/**+ * Whether any dynamic client in this server namespace carries `clientId`, pending,+ * bound or legacy alike: every row stands for a client that may still be live at its+ * AS (teardown deletes the row). Reads no encrypted column.+ */+export async function isDynamicClientIdRegistered(+ db: DbClient,+ input: { serverNamespace: string; clientId: string; ownerKind?: 'mcpserver' }+): Promise<boolean> {+ const result = await db.query(+ `SELECT 1+ FROM dynamic_clients+ WHERE owner_kind = $1 AND server_namespace = $2 AND client_id = $3+ LIMIT 1`,+ [resolveOwnerKind(input), input.serverNamespace, input.clientId]+ )+ return result.rows.length > 0+}+/*** Metadata-only view of a `dynamic_clients` row whose confidential secret is at* or near expiry — enough for the DCR lifecycle decision (§5) without touchingdiff --git a/control-api/src/oauth/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.tsindex 07727e1ba..0cf1b9810 100644--- a/control-api/src/oauth/mcpServerOAuthSpec.ts+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts@@ -18,7 +18,10 @@ import type {RemoteClientRouting,ServerOAuthSecretSource,} from './callback.js'+import { isCimdClientId } from './cimdIdentity.js'+import { checkAsEndpointsSameSite } from './discovery.js'import { MAX_EXTRA_AUTHORIZE_PARAMS, MAX_EXTRA_AUTHORIZE_PARAM_VALUE_LEN } from './genericKnobs.js'+import { remoteCallbackVariant } from './remoteCallback.js'import type { OAuthGrantKey } from './store.js'const log = rootLogger.child({ module: 'mcp-server-oauth-spec' })@@ -37,6 +40,8 @@ export interface McpServerOAuthDecl {clientMode?: unknownauthorizationEndpoint?: unknowntokenEndpoint?: unknown+ registrationEndpoint?: unknown+ issuer?: unknownresource?: unknownbearerInBody?: unknownsupportsRefresh?: unknown@@ -230,13 +235,20 @@ export interface ResolvedServerOAuthSubject {crUid?: string}-export type RemoteOAuthSpecIncoherence = 'public_client_with_secret_refs' | 'bearer_in_body'+export type RemoteOAuthSpecIncoherence =+ | 'public_client_with_secret_refs'+ | 'bearer_in_body'+ | 'cimd_without_issuer_binding'+ | 'as_endpoints_cross_site'/*** A remote `spec.oauth` the admission rules reject but that reached the apiserver- * anyway (CRD applied after the object, or a write that bypassed validation). The- * runtime cannot honor it, so consent, authorize-URL minting and token issuance- * refuse it with this specific error instead of degrading to a generic failure.+ * anyway (CRD applied after the object, or a write that bypassed validation, e.g. by+ * kubectl/GitOps). The phase using it refuses it with this specific error instead of+ * degrading to a generic failure: the CRD-mirror reasons (`public_client_with_secret_refs`,+ * `bearer_in_body`) in consent and token issuance alike; the per-server callback+ * reasons (`cimd_without_issuer_binding`, `as_endpoints_cross_site`) only in consent+ * (authorize-URL minting and the callback), so grants already obtained keep serving.*/export class RemoteOAuthSpecIncoherentError extends Error {readonly code = 'remote_oauth_spec_incoherent'@@ -246,7 +258,20 @@ export class RemoteOAuthSpecIncoherentError extends Error {}}-function remoteOAuthSpecIncoherence(oauth: McpServerOAuthDecl): RemoteOAuthSpecIncoherence | null {+/**+ * Where a remote server's `spec.oauth` is being used:+ * - `consent` — authorize-URL minting and the OAuth callback, where a new code is+ * issued and redeemed;+ * - `token` — serving and refreshing a grant already obtained (user-token, the+ * reactive refresh and the proactive cron).+ * Required at every call site, with no default, so no reader silently picks a phase.+ */+export type RemoteOAuthCoherencePhase = 'consent' | 'token'++function remoteOAuthSpecIncoherence(+ oauth: McpServerOAuthDecl,+ phase: RemoteOAuthCoherencePhase+): RemoteOAuthSpecIncoherence | null {if (oauth.clientMode === 'public' &&(oauth.clientIdRef != null || oauth.clientSecretRef != null)@@ -254,23 +279,64 @@ function remoteOAuthSpecIncoherence(oauth: McpServerOAuthDecl): RemoteOAuthSpecIreturn 'public_client_with_secret_refs'}if (oauth.bearerInBody === true) return 'bearer_in_body'+ // The per-server rules defend the authorization response (which AS minted a code, and+ // where it is redeemed). A grant already obtained is sealed to this CR's uid and its+ // endpoints are immutable, so a refresh only ever returns to the token endpoint that+ // issued it: blocking it would strand existing grants without closing any mix-up.+ if (phase === 'consent' && remoteCallbackVariant(oauth) === 'per-server') {+ // The CIMD document lists only the shared callback, so its client can never be+ // bound to one server's redirect URI; without `iss` nothing else ties its codes to+ // this server.+ if (isCimdClientId(oauth.id)) return 'cimd_without_issuer_binding'+ if (!asEndpointsOnIssuerSite(oauth)) return 'as_endpoints_cross_site'+ }return null}+/**+ * The install-time same-site rule, re-applied to the endpoints pinned on a per-server+ * CR. The install already enforces it, but a CR written straight to the apiserver+ * skips the install, and without `iss` a token endpoint off the issuer's site would+ * redeem our codes. An endpoint that is not a string is left to the routing reader,+ * which fails closed on it; a missing issuer fails here, since per-server consent+ * cannot be anchored without one.+ */+function asEndpointsOnIssuerSite(oauth: McpServerOAuthDecl): boolean {+ const optional = (value: unknown): string | undefined =>+ typeof value === 'string' && value.length > 0 ? value : undefined+ const authorization = optional(oauth.authorizationEndpoint)+ const token = optional(oauth.tokenEndpoint)+ if (authorization === undefined || token === undefined) return true+ const registration = optional(oauth.registrationEndpoint)+ return checkAsEndpointsSameSite({+ issuer: typeof oauth.issuer === 'string' ? oauth.issuer : '',+ authorization,+ token,+ ...(registration ? { registration } : {}),+ }).ok+}+/*** Runtime mirror of the remote-carril coherence rules of the McpServer CRD- * (REMOTE-SECRET-PAIRING for `public`, REMOTE-BEARER-HEADER). Throws+ * (REMOTE-SECRET-PAIRING for `public`, REMOTE-BEARER-HEADER) and of the install's+ * per-server callback rules (no CIMD client and same-site AS endpoints when the AS+ * does not return `iss`, which the CRD cannot express). Throws* {@link RemoteOAuthSpecIncoherentError} for a remote server whose shape no- * install path produces; a no-op for every other lane.+ * install path produces; a no-op for every other lane. The CRD mirrors apply in both+ * phases; the per-server callback rules only in `consent` (see+ * {@link RemoteOAuthCoherencePhase}).** Deliberately NOT applied by {@link resolveServerOAuth}: that coordinate backs* revoke and the grant-existence sweep, and an incoherent server must still be* disconnectable and must not push the sweep into its fail-open branch.*/-export function assertRemoteOAuthSpecCoherent(server: McpServerOAuthSpecInput): void {+export function assertRemoteOAuthSpecCoherent(+ server: McpServerOAuthSpecInput,+ phase: RemoteOAuthCoherencePhase+): void {const oauth = server.spec?.oauthif (!oauth || readOAuthLane(oauth) !== 'remote') return- const reason = remoteOAuthSpecIncoherence(oauth)+ const reason = remoteOAuthSpecIncoherence(oauth, phase)if (!reason) returnconst name = server.metadata?.namelog.warn(@@ -278,8 +344,9 @@ export function assertRemoteOAuthSpecCoherent(server: McpServerOAuthSpecInput):event: 'remote_oauth_spec_incoherent',mcpServerName: typeof name === 'string' ? name : undefined,reason,+ phase,},- 'remote mcp-server oauth spec is incoherent; refusing consent and token issuance'+ 'remote mcp-server oauth spec is incoherent; refusing it in this phase')throw new RemoteOAuthSpecIncoherentError(reason)}@@ -298,6 +365,8 @@ function extractRemoteRouting(oauth: McpServerOAuthDecl): RemoteClientRouting |typeof oauth.issForCallback === 'string' && oauth.issForCallback.length > 0? oauth.issForCallback: undefined+ const issuer =+ typeof oauth.issuer === 'string' && oauth.issuer.length > 0 ? oauth.issuer : undefinedreturn {authorizationEndpoint,tokenEndpoint,@@ -306,6 +375,7 @@ function extractRemoteRouting(oauth: McpServerOAuthDecl): RemoteClientRouting |bearerInBody: oauth.bearerInBody === true,supportsRefresh: oauth.supportsRefresh === true,issForCallback,+ ...(issuer ? { issuer } : {}),}}@@ -435,7 +505,8 @@ function normalizeScopes(scopes: unknown): string[] | undefined {* secret (K8s Secret or `getDynamicClient`) per `secretSource`.*/export function resolveServerOAuthSubject(- server: McpServerOAuthSpecInput+ server: McpServerOAuthSpecInput,+ phase: RemoteOAuthCoherencePhase): ResolvedServerOAuthSubject | null {const oauth = server.spec?.oauthif (!oauth || typeof oauth.id !== 'string' || oauth.id.length === 0) return null@@ -449,7 +520,7 @@ export function resolveServerOAuthSubject(// ─── Remote lane (`source:'remote'`) ─────────────────────────────────────if (lane === 'remote') {- assertRemoteOAuthSpecCoherent(server)+ assertRemoteOAuthSpecCoherent(server, phase)const remote = extractRemoteRouting(oauth)if (!remote) return nullconst secretSource = resolveRemoteSecretSource(oauth, remote.clientMode)diff --git a/control-api/src/routes/admin/remoteMcp.ts b/control-api/src/routes/admin/remoteMcp.tsindex 06307fb27..92ad25acb 100644--- a/control-api/src/routes/admin/remoteMcp.ts+++ b/control-api/src/routes/admin/remoteMcp.ts@@ -10,15 +10,23 @@ 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, buildCimdDocument } from '../../oauth/cimd.js'+import { buildCimdDocument } from '../../oauth/cimd.js'+import { MAX_CLIENT_ID_LENGTH, isCimdClientId } from '../../oauth/cimdIdentity.js'import {type DcrDeps,type DcrMintHandle,buildDcrRequest,registerDynamicClient,+ verifyDcrRedirectUris,} from '../../oauth/dcr.js'import { bestEffortRfc7592Delete } from '../../oauth/dcrCleanup.js'-import { type DiscoveryResult, discoverRemoteOAuth } from '../../oauth/discovery.js'+import {+ type DiscoveryResult,+ advertisesIssBinding,+ discoverRemoteOAuth,+ registrationModeInputs,+ selectRegistrationMode,+} from '../../oauth/discovery.js'import { discoveryHttpStatus } from '../../oauth/discoveryHttpStatus.js'import {type DynamicClientKey,@@ -29,10 +37,18 @@ import {deleteDynamicClientOwnedByInstall,getDynamicClient,insertDynamicClientPending,+ isDynamicClientIdRegistered,reclaimOrphanDynamicClient,} from '../../oauth/dynamicClientStore.js'import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'import { probeMcpTransport } from '../../oauth/mcpTransportProbe.js'+import {+ InvalidRemoteRedirectUriInputError,+ type RemoteCallbackVariant,+ buildRemoteRedirectUri,+ isValidRemoteServerNameSegment,+ remoteCallbackVariant,+} from '../../oauth/remoteCallback.js'import { rootLogger } from '../../observability/logger.js'import { attachServerToContext } from '../../services/contextAllowlist.js'import { K8sNotFoundError } from '../../services/resourceService.js'@@ -73,6 +89,18 @@ const BASE = '/admin/mcp-servers/remote'const log = rootLogger.child({ module: 'admin-remote-mcp' })+/**+ * A minted DCR client is being abandoned without an RFC 7592 handle: it stays+ * registered at the AS. Logged the same way on every abandon path, so an abandoned+ * install is never mistaken for a cleaned-up one.+ */+function logDcrRevokeLocalOnly(serverName: string, hasRegistrationClientUri: boolean): void {+ log.info(+ { event: 'remote_oauth_dcr_revoke_local_only', serverName, hasRegistrationClientUri },+ 'dcr revoke skipped: no RFC 7592 management handle, the minted client remains at the AS'+ )+}+// `discoveryHttpStatus` moved to `oauth/discoveryHttpStatus.js` (H-5) so the remote// and generic discover endpoints share one mapping. Re-exported here so existing// importers (and the mapping's own test) keep resolving it from this module.@@ -89,17 +117,13 @@ const installBodySchema = z.object({contextRef: z.string().min(1),baseUrl: z.string().min(1),mode: z.enum(['cimd', 'pre-registered', 'dcr']),- clientId: z.string().min(1).optional(),+ clientId: z.string().min(1).max(MAX_CLIENT_ID_LENGTH).optional(),clientSecret: z.string().min(1).optional(),grantScope: z.enum(['user', 'context']).optional(),})type InstallBody = z.infer<typeof installBodySchema>-function isValidK8sName(name: string): boolean {- return RFC1123_RE.test(name) && name.length <= 253-}-/*** Fenced-delete preconditions from a just-created object, or undefined when the* apiserver response carried no complete identity. A rollback bound by@@ -248,6 +272,141 @@ function deriveDcrClientMode(result: DiscoveryResult): 'public' | 'confidential'return Array.isArray(methods) && methods.includes('none') ? 'public' : 'confidential'}+/**+ * The callback variant an install from this discovery result writes. Derived from the+ * `spec.oauth` block the install builds — not from the discovery fields directly — so+ * the install and the runtime (which reads the block back from the CR) share one+ * derivation. The builder options do not influence the variant.+ */+function callbackVariantOf(discovery: DiscoveryResult): RemoteCallbackVariant {+ return remoteCallbackVariant(+ buildRemoteOAuthSpec(discovery, { clientMode: 'public', grantScope: 'user' })+ )+}++/**+ * The AS offers CIMD to a public client and would resolve to it, but for the missing+ * RFC 9207 advertisement. Evaluated through the real mode selector so the answer can+ * never disagree with discovery.+ */+function cimdBlockedOnlyByMissingIssBinding(discovery: DiscoveryResult): boolean {+ if (advertisesIssBinding(discovery.as)) return false+ const withIssBinding = {+ ...registrationModeInputs(discovery.as, { hasPreRegisteredClient: false }),+ issBindingSupported: true,+ }+ return selectRegistrationMode(withIssBinding) === 'cimd'+}++// Stand-ins handed to the redirect-URI builder to render a template; they are replaced+// by placeholders, so the prefix the operator copies still comes from the one builder.+const TEMPLATE_SERVER_NAME = 'server-name'+const TEMPLATE_INSTALL_NONCE = '00000000-0000-0000-0000-000000000000'++export interface RemoteCallbackPreview {+ /**+ * Whether a public callback base URL is configured (for `per-server`, one that is a+ * bare origin). `false` blocks only a `per-server` install (503); a `shared` install+ * still proceeds, falling back to the request Host at consent, and simply has no URI+ * to show here.+ */+ configured: boolean+ variant: RemoteCallbackVariant+ /**+ * The redirect URI an install would register. Per-server URIs carry the literal+ * placeholders `{serverName}` and, for DCR, `{installId}` (minted at install time).+ */+ redirectUriTemplate?: string+}++/** The `/discover` view of the callback an install from this result would use. */+function previewRemoteCallback(discovery: DiscoveryResult): RemoteCallbackPreview {+ const variant = callbackVariantOf(discovery)+ const origin = normalizeConfiguredOrigin(config.oauthCallbackBaseUrl)+ if (origin === null) return { configured: false, variant }+ if (variant === 'shared') {+ return {+ configured: true,+ variant,+ redirectUriTemplate: buildRemoteRedirectUri({ origin, variant: 'shared' }),+ }+ }+ const dcr = discovery.registrationMode === 'dcr'+ const suffix = dcr+ ? `/${TEMPLATE_SERVER_NAME}/${TEMPLATE_INSTALL_NONCE}`+ : `/${TEMPLATE_SERVER_NAME}`+ let uri: string+ try {+ uri = dcr+ ? buildRemoteRedirectUri({+ origin,+ variant,+ mode: 'dcr',+ serverName: TEMPLATE_SERVER_NAME,+ installNonce: TEMPLATE_INSTALL_NONCE,+ })+ : buildRemoteRedirectUri({+ origin,+ variant,+ mode: 'pre-registered',+ serverName: TEMPLATE_SERVER_NAME,+ })+ } catch (err) {+ // A configured base URL that is not a bare origin cannot anchor a per-server URI.+ if (err instanceof InvalidRemoteRedirectUriInputError) return { configured: false, variant }+ throw err+ }+ return {+ configured: true,+ variant,+ redirectUriTemplate: `${uri.slice(0, -suffix.length)}${dcr ? '/{serverName}/{installId}' : '/{serverName}'}`,+ }+}++/** Hostnames of the AS endpoints an install would trust (shown before a per-server install). */+function asEndpointHostsOf(discovery: DiscoveryResult): {+ authorization: string+ token: string+ registration?: string+} {+ const { authorization, token, registration } = discovery.endpoints+ return {+ authorization: new URL(authorization).hostname,+ token: new URL(token).hostname,+ ...(registration ? { registration: new URL(registration).hostname } : {}),+ }+}++export type PreRegisteredClientIdConflict = 'cimd_client' | 'remote_server' | 'dynamic_client'++/**+ * Why a pre-registered client_id cannot back a per-server install, or null. A+ * per-server client must belong to exactly one server: its one registered redirect URI+ * is what binds its codes to that server, and a client shared with another server (or+ * one of our DCR clients, or the platform CIMD identity, which lists the shared+ * callback) would let the AS deliver a code for one server to another. Check-then-create+ * without a fence: an admin-only action on a confidential client, where a lost race+ * still leaves each server with its own redirect URI.+ */+async function preRegisteredClientIdConflict(+ gateway: K8sGateway,+ db: DbClient,+ namespace: string,+ clientId: string+): Promise<PreRegisteredClientIdConflict | null> {+ if (isCimdClientId(clientId)) return 'cimd_client'+ const servers = (await gateway.listResource('mcpservers', namespace)) as Array<{+ spec?: { oauth?: { source?: unknown; id?: unknown } }+ }>+ if (servers.some(s => s?.spec?.oauth?.source === 'remote' && s.spec.oauth.id === clientId)) {+ return 'remote_server'+ }+ if (await isDynamicClientIdRegistered(db, { serverNamespace: namespace, clientId })) {+ return 'dynamic_client'+ }+ return null+}+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@@ -372,8 +531,10 @@ export function createAdminRemoteMcpRouter()}+ const callback = previewRemoteCallback(r)res.status(200).json({transport,+ callback,detected: {registrationMode: r.registrationMode,// DCR is available in C2. Echo the resolved client mode (derived from the@@ -392,6 +553,10 @@ export function createAdminRemoteMcpRouter(resource: r.resource,issuer: r.issuer,...(r.issForCallback ? { issForCallback: r.issForCallback } : {}),+ // Without `iss` the same-site rule is all that ties these hosts to the+ // issuer, and it cannot tell two hosts of one registrable domain apart; the+ // operator sees them before trusting them.+ ...(callback.variant === 'per-server' ? { asEndpointHosts: asEndpointHostsOf(r) } : {}),scopes: derivedScopes(r),quirks: r.quirks,},@@ -412,13 +577,15 @@ export function createAdminRemoteMcpRouter(}const body: InstallBody = parsed.data- if (!isValidK8sName(body.serverName)) {+ // The server name becomes a segment of its per-server redirect URI, so it is held+ // to the same rule the callback route applies to that segment.+ if (!isValidRemoteServerNameSegment(body.serverName)) {res.status(400).json({- error: 'invalid serverName: must be a valid K8s name (RFC 1123 label, max 253 chars)',+ error: 'invalid serverName: must be a valid K8s name (RFC 1123 label, max 63 chars)',})return}- if (!isValidK8sName(body.contextRef)) {+ if (!RFC1123_RE.test(body.contextRef)) {res.status(400).json({ error: 'invalid contextRef' })return}@@ -497,6 +664,14 @@ export function createAdminRemoteMcpRouter(// (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 (cimdBlockedOnlyByMissingIssBinding(discovery)) {+ const fallbackMode = discovery.registrationMode === 'dcr' ? 'dcr' : 'pre-registered'+ res.status(400).json({+ error: 'mode_unsupported',+ message: `this authorization server supports CIMD but not RFC 9207; install with mode "${fallbackMode}"`,+ })+ return+ }if (discovery.registrationMode === 'dcr') {res.status(400).json({error: 'mode_unsupported',@@ -558,29 +733,94 @@ export function createAdminRemoteMcpRouter()}- // RFC 9207 issuer binding is MANDATORY on the remote lane. Every remote mode- // (dcr/cimd/pre-registered) lands on the SHARED remote callback- // (`/oauth-callback/remote`), whose mix-up defence fails closed when no issuer is- // pinned (`issuer_binding_required`, R3-H2). `discovery.issForCallback` is set iff- // the AS advertised `authorization_response_iss_parameter_supported`. Reject at- // install — BEFORE any AS registration (DCR saga step 0) or K8s/store write — so- // the operator learns now instead of the user hitting a 400 at consent against a- // server that can never complete OAuth (the regression this closes, R3F-H1).- // Ordered AFTER the bearerInBody/mode-match/transport admission checks so their- // more specific rejections keep precedence; still before any write.- if (!discovery.issForCallback) {+ // Callback variant, fixed before any AS registration or write: the shared callback+ // when the AS returns `iss` (RFC 9207), otherwise a redirect URI of this server's+ // own, which is then the only mix-up defence.+ const callbackVariant = callbackVariantOf(discovery)++ // Defensive: mode selection never resolves CIMD without RFC 9207, and the mode+ // check above rejects a CIMD request against such an AS. Kept so a regression+ // there can never install the platform CIMD identity — which lists only the+ // shared callback — onto a server with no issuer binding.+ if (body.mode === 'cimd' && callbackVariant !== 'shared') {log.warn({ event: 'remote_oauth_issuer_binding_unsupported', serverName: body.serverName },- 'remote install rejected: authorization server does not advertise RFC 9207 (authorization_response_iss_parameter_supported)'+ 'remote install rejected: cimd requires an authorization server that advertises RFC 9207')res.status(422).json({error: 'issuer_binding_required',message:- 'the authorization server does not advertise RFC 9207 (authorization_response_iss_parameter_supported); a remote OAuth install requires it',+ 'the authorization server does not advertise RFC 9207 (authorization_response_iss_parameter_supported); a CIMD install requires it',})return}+ // Minted before anything else that needs it: a DCR client registers a redirect+ // URI carrying this nonce, and every saga compensation deletes only the row that+ // carries it, so a concurrent install/reinstall of the same name that reclaimed+ // the row is never destroyed (R3-H1).+ const installId = randomUUID()++ // The effective redirect URI. Per-server fails closed without a configured public+ // origin: falling back to the request Host (as the shared callback still does)+ // would register a URI the AS compares byte-for-byte against whatever Host the+ // admin happened to use. Shared keeps its historical handling: DCR and CIMD+ // require the origin below, pre-registered resolves it at consent.+ const callbackOrigin = normalizeConfiguredOrigin(config.oauthCallbackBaseUrl)+ let redirectUri: string | undefined+ if (callbackVariant === 'per-server') {+ try {+ if (callbackOrigin === null) throw new InvalidRemoteRedirectUriInputError('no origin')+ redirectUri =+ body.mode === 'dcr'+ ? buildRemoteRedirectUri({+ origin: callbackOrigin,+ variant: 'per-server',+ mode: 'dcr',+ serverName: body.serverName,+ installNonce: installId,+ })+ : buildRemoteRedirectUri({+ origin: callbackOrigin,+ variant: 'per-server',+ mode: 'pre-registered',+ serverName: body.serverName,+ })+ } catch (err) {+ if (!(err instanceof InvalidRemoteRedirectUriInputError)) throw err+ log.error(+ { event: 'remote_oauth_per_server_callback_unconfigured', serverName: body.serverName },+ 'per-server remote install requires a configured public callback base URL (bare origin)'+ )+ res.status(503).json({ error: 'callback_base_url_unconfigured' })+ return+ }+ } else if (callbackOrigin !== null) {+ redirectUri = buildRemoteRedirectUri({ origin: callbackOrigin, variant: 'shared' })+ }++ if (body.mode === 'pre-registered' && callbackVariant === 'per-server') {+ const conflict = await preRegisteredClientIdConflict(+ gateway,+ db,+ config.mcpServersNamespace,+ body.clientId as string+ )+ if (conflict !== null) {+ log.warn(+ { event: 'remote_install_client_id_in_use', serverName: body.serverName, conflict },+ 'remote pre-registered install rejected: client_id already backs another client'+ )+ res.status(409).json({+ error: 'oauth_client_id_in_use',+ conflict,+ message:+ 'this client_id already backs another client; register a separate OAuth client for this server',+ })+ 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' =@@ -616,10 +856,6 @@ export function createAdminRemoteMcpRouter(serverNamespace: targetNs,serverName,}- // Install-ownership token minted at the start of DCR step 0. Every compensation- // deletes ONLY the row carrying this install_id, so a concurrent install/reinstall- // of the same name that reclaimed the row is never destroyed (R3-H1).- const installId = randomUUID()let dcrRegistered = falselet dcrClientId: string | undefinedlet dcrRegistrationClientUri: string | undefined@@ -639,10 +875,7 @@ export function createAdminRemoteMcpRouter()} 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'- )+ logDcrRevokeLocalOnly(serverName, Boolean(dcrRegistrationClientUri))}}@@ -670,10 +903,9 @@ export function createAdminRemoteMcpRouter(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) {+ // The client registers exactly the redirect URI built above; a DCR client also+ // needs it on the shared callback, so fail closed if no origin is configured.+ if (redirectUri === undefined) {log.error({ event: 'remote_oauth_dcr_callback_unconfigured', serverName },'dcr install requires a configured public callback base URL'@@ -684,7 +916,7 @@ export function createAdminRemoteMcpRouter(const dcrRequest = buildDcrRequest(discovery, {clientMode,- redirectUris: [`${origin}${REMOTE_CALLBACK_PATH}`],+ redirectUris: [redirectUri],scopes: derivedScopes(discovery),})const dcrOutcome = await registerDynamicClient(dcrDeps, registrationEndpoint, dcrRequest)@@ -696,14 +928,17 @@ export function createAdminRemoteMcpRouter(// these variants carry the handle; non-2xx errors mint nothing.if ((dcrError.kind === 'auth_method_unsupported' || dcrError.kind === 'invalid_response') &&- dcrError.registrationClientUri &&- dcrError.registrationAccessToken+ dcrError.minted) {- await bestEffortRfc7592Delete(- dcrDeps,- dcrError.registrationClientUri,- dcrError.registrationAccessToken- )+ if (dcrError.registrationClientUri && dcrError.registrationAccessToken) {+ await bestEffortRfc7592Delete(+ dcrDeps,+ dcrError.registrationClientUri,+ dcrError.registrationAccessToken+ )+ } else {+ logDcrRevokeLocalOnly(serverName, Boolean(dcrError.registrationClientUri))+ }}if (dcrError.kind === 'auth_method_unsupported') {log.warn(@@ -722,6 +957,7 @@ export function createAdminRemoteMcpRouter(const {registrationAccessToken: _t,registrationClientUri: _u,+ minted: _m,...safeDetail} = dcrError as typeof dcrError & Partial<DcrMintHandle>res.status(400).json({ error: 'dcr_registration_failed', detail: safeDetail })@@ -748,8 +984,40 @@ export function createAdminRemoteMcpRouter(mintedRegistrationClientUri,mintedRegistrationAccessToken)+ return}+ logDcrRevokeLocalOnly(serverName, Boolean(mintedRegistrationClientUri))}+ // Refuse a client we cannot trust to redirect only to this installation, before+ // anything is persisted. Per-server: the registered URI is the mix-up defence, so+ // the AS must report exactly the one we asked for. Any variant: a client_id equal+ // to the platform CIMD identity would be indistinguishable from that shared+ // client downstream.+ const redirectCheck = verifyDcrRedirectUris({+ variant: callbackVariant,+ requested: dcrRequest.redirect_uris,+ response: registration,+ })+ const rejection = !redirectCheck.ok+ ? redirectCheck.reason+ : isCimdClientId(registration.client_id)+ ? 'client_id_is_cimd_identity'+ : null+ if (rejection !== null) {+ await revokeMintedClient()+ log.warn(+ {+ event: 'remote_oauth_dcr_registration_rejected',+ serverName,+ variant: callbackVariant,+ reason: rejection,+ },+ 'dcr registration response rejected; revoked the minted client'+ )+ res.status(400).json({ error: 'dcr_registration_failed', detail: { kind: rejection } })+ return+ }+// A public client carries no secret; never persist one the AS may have echoed// alongside a `none` downgrade.const dcrCredentials: UpsertDynamicClientInput = {@@ -1179,6 +1447,11 @@ export function createAdminRemoteMcpRouter(contextUpdated: true,clientMode: effectiveClientMode,registrationMode: discovery.registrationMode,+ callbackVariant,+ // What the AS must hold for consent to work — the operator registers it for a+ // pre-registered client. Absent only for a shared pre-registered install with no+ // configured origin, whose URI is resolved from the request at consent.+ ...(redirectUri ? { redirectUri } : {}),...(clientSecretName ? { clientSecretName } : {}),})})diff --git a/control-api/src/routes/external/oauthCallback.ts b/control-api/src/routes/external/oauthCallback.tsindex 1872093d3..af0281fb7 100644--- a/control-api/src/routes/external/oauthCallback.ts+++ b/control-api/src/routes/external/oauthCallback.ts@@ -88,7 +88,7 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {if (err instanceof K8sNotFoundError) return nullthrow err}- const resolved = resolveServerOAuthSubject(server)+ const resolved = resolveServerOAuthSubject(server, 'consent')if (!resolved) return null// `resolved.crUid` seals grants written by this consent to the CR's identity:// the uid is the apiserver's, unique per object, so a same-name reinstall'sdiff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.tsindex 5ed8d33db..85beecb33 100644--- a/control-api/src/routes/internal/oauth.ts+++ b/control-api/src/routes/internal/oauth.ts@@ -134,7 +134,7 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {if (err instanceof K8sNotFoundError) return nullthrow err}- const resolved = resolveServerOAuthSubject(server)+ const resolved = resolveServerOAuthSubject(server, 'consent')if (!resolved) return nullreturn { namespace: config.mcpServersNamespace, ...resolved }},@@ -194,7 +194,7 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {let subject: ReturnType<typeof resolveServerOAuthSubject> = nulllet incoherent: RemoteOAuthSpecIncoherentError | undefinedtry {- subject = resolveServerOAuthSubject(server)+ subject = resolveServerOAuthSubject(server, 'consent')} catch (err) {if (!(err instanceof RemoteOAuthSpecIncoherentError)) throw errincoherent = errdiff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.tsindex 16115e619..744c742f8 100644--- a/control-api/src/routes/mcpOauth.ts+++ b/control-api/src/routes/mcpOauth.ts@@ -105,7 +105,7 @@ export function normalizeMcpServerOwnerDecl(// IDENTICALLY to the mint + callback (D4 — no drift). The remote decl carries the// pinned routing + secretSource that `getAccessToken` branches on.if (lane === 'remote') {- const resolved = resolveServerOAuthSubject(server)+ const resolved = resolveServerOAuthSubject(server, 'token')if (!resolved) return nullreturn { metadata: ownerMetadata(server), spec: { oauthClients: [resolved.decl] } }}@@ -114,7 +114,7 @@ export function normalizeMcpServerOwnerDecl(// gets the pinned `generic` routing + secretSource that `getAccessToken`// branches on.if (lane === 'generic') {- const resolved = resolveServerOAuthSubject(server)+ const resolved = resolveServerOAuthSubject(server, 'token')if (!resolved) return nullreturn { metadata: ownerMetadata(server), spec: { oauthClients: [resolved.decl] } }}@@ -475,7 +475,7 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {}// Checked up front, not only through the refresh reader: a still-fresh// access token is served without ever reading the owner declaration.- assertRemoteOAuthSpecCoherent(server)+ assertRemoteOAuthSpecCoherent(server, 'token')// Bifurcate by grantScope read from the server. The KEY comes from the// shared derivation (`buildMcpServerGrantKey`, D4) so the mint, thediff --git a/control-api/test/fixtures/legacyOAuthGrant.ts b/control-api/test/fixtures/legacyOAuthGrant.tsindex 738ab0eff..9416c2a70 100644--- a/control-api/test/fixtures/legacyOAuthGrant.ts+++ b/control-api/test/fixtures/legacyOAuthGrant.ts@@ -211,7 +211,7 @@ export async function legacyConsent(async read(serverName): Promise<McpServerOAuthSubject | null> {const cr = (await gateway.getResource('mcpservers', serverName, NS)) as ServerCRconst { uid: _preIdentityPodNeverReadIt, ...metadata } = cr.metadata- const resolved = resolveServerOAuthSubject({ ...cr, metadata })+ const resolved = resolveServerOAuthSubject({ ...cr, metadata }, 'consent')return resolved ? { namespace: NS, ...resolved } : null},},@@ -248,7 +248,7 @@ export async function currentConsent(mcpServerReader: {async read(serverName): Promise<McpServerOAuthSubject | null> {const cr = (await gateway.getResource('mcpservers', serverName, NS)) as ServerCR- const resolved = resolveServerOAuthSubject(cr)+ const resolved = resolveServerOAuthSubject(cr, 'consent')return resolved ? { namespace: NS, ...resolved } : null},},diff --git a/control-api/test/fixtures/remoteOAuthDiscovery.ts b/control-api/test/fixtures/remoteOAuthDiscovery.tsindex 05545fdc5..fd25aafc6 100644--- a/control-api/test/fixtures/remoteOAuthDiscovery.ts+++ b/control-api/test/fixtures/remoteOAuthDiscovery.ts@@ -417,6 +417,16 @@ export function makeDcrTransport(opts: {responseJson: stringstatus?: numbermanagementUri?: string+ /**+ * How the AS reports `redirect_uris` in the registration response:+ * - `'requested'`: echo the `redirect_uris` of the request actually POSTed, as an+ * RFC 7591 §3.2.1 AS does. Needed wherever the requested URI is only known at+ * install time (the per-server DCR URI carries a fresh install nonce).+ * - `'omit'`: drop the field.+ * - a string array: report these instead (an AS that registered something else).+ * Unset: `responseJson` verbatim.+ */+ redirectUris?: 'requested' | 'omit' | string[]}): { transport: PinnedTransport; calls: RecordedDcrCall[] } {const registrationEndpoint = opts.registrationEndpoint ?? DCR_REGISTRATION_ENDPOINTconst status = opts.status ?? 201@@ -424,10 +434,21 @@ export function makeDcrTransport(opts: {const transport: PinnedTransport = async ({ url, method, headers, body }) => {calls.push({ url, method, headers, body })if (url === registrationEndpoint && method === 'POST') {+ let bodyText = opts.responseJson+ if (opts.redirectUris !== undefined) {+ const response = JSON.parse(opts.responseJson) as Record<string, unknown>+ if (opts.redirectUris === 'omit') delete response.redirect_uris+ else if (opts.redirectUris === 'requested')+ response.redirect_uris = (+ JSON.parse(body ?? '{}') as { redirect_uris?: unknown }+ ).redirect_uris+ else response.redirect_uris = opts.redirectUris+ bodyText = JSON.stringify(response)+ }return {status,headers: { 'content-type': 'application/json' },- bodyText: opts.responseJson,+ bodyText,}}if (method === 'DELETE') {@@ -622,6 +643,17 @@ export function makeInMemoryDynamicClientsDb(): {}return { rows: [], rowCount: 0 }}+ if (text.includes('FROM dynamic_clients') && text.includes('client_id = $3')) {+ // Existence by client_id within a namespace (pre-registered uniqueness).+ const [owner_kind, server_namespace, client_id] = values+ const hit = [...rows.values()].some(+ row =>+ row.owner_kind === owner_kind &&+ row.server_namespace === server_namespace &&+ row.client_id === client_id+ )+ return hit ? { rows: [{ '?column?': 1 }], rowCount: 1 } : { rows: [], rowCount: 0 }+ }if (text.includes('FROM dynamic_clients')) {const [owner_kind, server_namespace, server_name] = valuesconst row = rows.get(keyOf(owner_kind, server_namespace, server_name))diff --git a/control-api/test/oauth.authorizeUrl.generic.test.ts b/control-api/test/oauth.authorizeUrl.generic.test.tsindex f57612dab..b141692a2 100644--- a/control-api/test/oauth.authorizeUrl.generic.test.ts+++ b/control-api/test/oauth.authorizeUrl.generic.test.ts@@ -17,29 +17,32 @@ const CLIENT_ID = 'my-generic-client'const REDIRECT_URI = 'https://control.example.com/api/v1/oauth-callback/my-generic-client'function genericSubject(overrides: Record<string, unknown> = {}): McpServerOAuthSubject {- const resolved = resolveServerOAuthSubject({- spec: {- contextRef: 'ctx-A',- oauth: {- source: 'generic',- id: CLIENT_ID,- authorizationEndpoint: 'https://idp.example.com/authorize',- tokenEndpoint: 'https://idp.example.com/token',- resource: 'https://api.example.com',- tokenRequestFormat: 'form',- tokenAuthMethod: 'body',- scopeSeparator: 'comma',- sendScope: true,- usePkce: true,- includeResponseType: true,- supportsRefresh: true,- grantScope: 'user',- scopes: ['read', 'write'],- extraAuthorizeParams: { audience: 'aud-1' },- ...overrides,+ const resolved = resolveServerOAuthSubject(+ {+ spec: {+ contextRef: 'ctx-A',+ oauth: {+ source: 'generic',+ id: CLIENT_ID,+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ resource: 'https://api.example.com',+ tokenRequestFormat: 'form',+ tokenAuthMethod: 'body',+ scopeSeparator: 'comma',+ sendScope: true,+ usePkce: true,+ includeResponseType: true,+ supportsRefresh: true,+ grantScope: 'user',+ scopes: ['read', 'write'],+ extraAuthorizeParams: { audience: 'aud-1' },+ ...overrides,+ },},},- })+ 'consent'+ )if (!resolved) throw new Error('fixture: generic resolve returned null')return { namespace: MCP_NS, ...resolved }}diff --git a/control-api/test/oauth.authorizeUrl.remote.test.ts b/control-api/test/oauth.authorizeUrl.remote.test.tsindex 8cd9cfa15..59f9e3e11 100644--- a/control-api/test/oauth.authorizeUrl.remote.test.ts+++ b/control-api/test/oauth.authorizeUrl.remote.test.ts@@ -1,13 +1,18 @@-import { describe, expect, it, vi } from 'vitest'+import { beforeAll, describe, expect, it, vi } from 'vitest'import { type BuildAuthorizeUrlDeps, buildAuthorizeUrl } from '../src/oauth/authorizeUrlHelper.js'import type { McpServerOAuthReader, McpServerOAuthSubject } from '../src/oauth/callback.js'+import { type DiscoveryResult, discoverRemoteOAuth } from '../src/oauth/discovery.js'import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'+import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'/*** C4/DEC-23 — the remote authorize-URL mint. The URL is built from the pinned* discovery-derived `authorizationEndpoint` with the PUBLIC client_id (`oauth.id`),* mandatory PKCE S256, and the RFC 8707 `resource`. No secret material rides the- * URL and no K8s Secret is read. Subject decl comes from the REAL resolver.+ * URL and no K8s Secret is read. The CR is the install's own output (T1): the real+ * discovery over the Linear probe (CIMD with RFC 9207) through `buildRemoteOAuthSpec`,+ * resolved by the REAL resolver.*/const STATE_SECRET = 'test-state-hmac-secret-32-bytes-padding'@@ -15,25 +20,27 @@ const MCP_NS = 'mcp-server'const CLIENT_ID = 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client'const REDIRECT_URI = 'https://control.example.com/api/v1/oauth-callback/remote'+let linear: DiscoveryResult++beforeAll(async () => {+ const outcome = await discoverRemoteOAuth(PILOTS.linear.mcpUrl, {+ transport: makeDiscoveryTransport(PILOTS.linear),+ resolveDns: async () => ['93.184.216.34'],+ })+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)+ linear = outcome.result+})+function remoteSubject(): McpServerOAuthSubject {- const resolved = resolveServerOAuthSubject({- spec: {- contextRef: 'ctx-A',- oauth: {- source: 'remote',- id: CLIENT_ID,- clientMode: 'public',- authorizationEndpoint: 'https://mcp.notion.com/authorize',- tokenEndpoint: 'https://mcp.notion.com/token',- issuer: 'https://mcp.notion.com',- resource: 'https://mcp.notion.com',- grantScope: 'user',- scopes: ['read', 'write'],- bearerInBody: false,- supportsRefresh: true,- },- },+ const oauth = buildRemoteOAuthSpec(linear, {+ clientMode: 'public',+ grantScope: 'user',+ cimdClientId: CLIENT_ID,})+ const resolved = resolveServerOAuthSubject(+ { spec: { contextRef: 'ctx-A', oauth: oauth as unknown as Record<string, unknown> } },+ 'consent'+ )if (!resolved) throw new Error('fixture: remote resolve returned null')return { namespace: MCP_NS, ...resolved }}@@ -52,7 +59,7 @@ describe('buildAuthorizeUrl — remote mcp subject (DEC-23)', () => {const result = await buildAuthorizeUrl({subjectKind: 'mcp',- mcpServerName: 'notion-remote',+ mcpServerName: 'linear-remote',oauthClientId: CLIENT_ID,userId: 'user-9',grantKind: 'user',@@ -65,13 +72,13 @@ describe('buildAuthorizeUrl — remote mcp subject (DEC-23)', () => {expect(result.kind).toBe('ok')if (result.kind !== 'ok') returnconst url = new URL(result.authorizeUrl)- expect(`${url.origin}${url.pathname}`).toBe('https://mcp.notion.com/authorize')+ expect(`${url.origin}${url.pathname}`).toBe('https://mcp.linear.app/authorize')expect(url.searchParams.get('response_type')).toBe('code')expect(url.searchParams.get('client_id')).toBe(CLIENT_ID)expect(url.searchParams.get('redirect_uri')).toBe(REDIRECT_URI)expect(url.searchParams.get('code_challenge_method')).toBe('S256')expect(url.searchParams.get('code_challenge')).toBeTruthy()- expect(url.searchParams.get('resource')).toBe('https://mcp.notion.com')+ expect(url.searchParams.get('resource')).toBe('https://mcp.linear.app/mcp')expect(url.searchParams.get('scope')).toBe('read write')expect(url.searchParams.get('state')).toBeTruthy()// No secret material, and the client-id Secret was never read (public client).diff --git a/control-api/test/oauth.callback.generic.test.ts b/control-api/test/oauth.callback.generic.test.tsindex 15cbbf2df..91ed78b07 100644--- a/control-api/test/oauth.callback.generic.test.ts+++ b/control-api/test/oauth.callback.generic.test.ts@@ -63,7 +63,7 @@ function genericCr(confidential: boolean) {function genericReader(confidential: boolean): McpServerOAuthReader {return {read: vi.fn(async () => {- const resolved = resolveServerOAuthSubject(genericCr(confidential))+ const resolved = resolveServerOAuthSubject(genericCr(confidential), 'consent')if (!resolved) return nullreturn { namespace: MCP_NS, ...resolved } as McpServerOAuthSubject}),diff --git a/control-api/test/oauth.callback.mcp.test.ts b/control-api/test/oauth.callback.mcp.test.tsindex 8834c8037..b42403db5 100644--- a/control-api/test/oauth.callback.mcp.test.ts+++ b/control-api/test/oauth.callback.mcp.test.ts@@ -70,7 +70,7 @@ function gdriveSubject(},},}- const resolved = resolveServerOAuthSubject(rawServer)+ const resolved = resolveServerOAuthSubject(rawServer, 'consent')if (!resolved) throw new Error('fixture: resolveServerOAuthSubject returned null')return { namespace: MCP_NS, ...resolved }}diff --git a/control-api/test/oauth.callback.remote.test.ts b/control-api/test/oauth.callback.remote.test.tsindex 85f21b36b..ed5f5b49c 100644--- a/control-api/test/oauth.callback.remote.test.ts+++ b/control-api/test/oauth.callback.remote.test.ts@@ -77,7 +77,7 @@ const REMOTE_CLIENT_ID = remoteServerCr().spec.oauth.idfunction remoteReader(): McpServerOAuthReader {return {read: vi.fn(async () => {- const resolved = resolveServerOAuthSubject(remoteServerCr())+ const resolved = resolveServerOAuthSubject(remoteServerCr(), 'consent')if (!resolved) return nullreturn { namespace: MCP_NS, ...resolved } as McpServerOAuthSubject}),@@ -196,7 +196,7 @@ describe('baked mcp exchange stays on fetchFn (byte-identical, T5c)', () => {},},}- const resolved = resolveServerOAuthSubject(bakedServer)+ const resolved = resolveServerOAuthSubject(bakedServer, 'consent')if (!resolved) throw new Error('fixture: baked resolve returned null')const subject = { namespace: MCP_NS, ...resolved } as McpServerOAuthSubjectdiff --git a/control-api/test/oauth.callback.reservedRemoteSegment.test.ts b/control-api/test/oauth.callback.reservedRemoteSegment.test.tsindex c4a80f76f..3d63f223b 100644--- a/control-api/test/oauth.callback.reservedRemoteSegment.test.ts+++ b/control-api/test/oauth.callback.reservedRemoteSegment.test.ts@@ -200,7 +200,7 @@ const TOKEN_RESPONSE = JSON.stringify({*/async function deliverState(lane: Lane, serverName: string, segment: string) {const { gw, cr } = await installServer(lane, serverName)- const resolved = resolveServerOAuthSubject(cr)+ const resolved = resolveServerOAuthSubject(cr, 'consent')if (!resolved) throw new Error('installed CR must resolve to an OAuth subject')const mcpServerReader: McpServerOAuthReader = {read: vi.fn(async () => ({ namespace: MCP_NS, ...resolved }) as McpServerOAuthSubject),diff --git a/control-api/test/oauth.cimdIdentity.test.ts b/control-api/test/oauth.cimdIdentity.test.tsnew file mode 100644index 000000000..02e08fec4--- /dev/null+++ b/control-api/test/oauth.cimdIdentity.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest'+import { buildCimdDocument } from '../src/oauth/cimd.js'+import { MAX_CLIENT_ID_LENGTH, isCimdClientId } from '../src/oauth/cimdIdentity.js'++describe('isCimdClientId', () => {+ it('matches the served CIMD client_id and its routed spellings, on any origin', () => {+ const served = buildCimdDocument('https://control.example.com').client_id+ expect(isCimdClientId(served)).toBe(true)+ expect(isCimdClientId(`${served}/`)).toBe(true)+ expect(isCimdClientId(served.toUpperCase())).toBe(true)+ expect(isCimdClientId(buildCimdDocument('https://old.example.org').client_id)).toBe(true)+ })++ it('rejects other ids, non-strings and non-URLs', () => {+ for (const value of [+ 'client-abc',+ '',+ undefined,+ 42,+ 'https://control.example.com/.well-known/evenfire-mcp-client',+ 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client/extra',+ ]) {+ expect(isCimdClientId(value)).toBe(false)+ }+ })++ it('the cap is the CRD maxLength of spec.oauth.id (512): at it still matches, above it never', () => {+ expect(MAX_CLIENT_ID_LENGTH).toBe(512)+ const served = buildCimdDocument('https://control.example.com').client_id+ const atCap = `${served}?${'x'.repeat(MAX_CLIENT_ID_LENGTH - served.length - 1)}`+ expect(atCap.length).toBe(MAX_CLIENT_ID_LENGTH)+ expect(isCimdClientId(atCap)).toBe(true)+ expect(isCimdClientId(`${atCap}x`)).toBe(false)+ })++ // A run of slashes before a non-slash made the trailing-slash pattern backtrack+ // quadratically on attacker-supplied ids (a DCR response or an operator client_id).+ it('answers a 200k-slash id quickly', () => {+ const hostile = `https://as.example.com/${'/'.repeat(200_000)}a`+ const started = performance.now()+ expect(isCimdClientId(hostile)).toBe(false)+ expect(performance.now() - started).toBeLessThan(200)+ })+})diff --git a/control-api/test/oauth.dcr.test.ts b/control-api/test/oauth.dcr.test.tsindex 45500170d..bf259be9a 100644--- a/control-api/test/oauth.dcr.test.ts+++ b/control-api/test/oauth.dcr.test.ts@@ -88,6 +88,52 @@ describe('registerDynamicClient (RFC 7591, effectful via injected pinned transporedirectUris: REDIRECT_URIS,})+ it('an oversized client_id → invalid_response carrying the RFC 7592 handle for cleanup', async () => {+ const { transport } = makeDcrTransport({+ responseJson: JSON.stringify({+ ...DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,+ client_id: `https://as.example.com/${'/'.repeat(200_000)}a`,+ }),+ })+ const started = performance.now()+ const outcome = await registerDynamicClient(+ { transport, resolveDns: PUBLIC_IP },+ DCR_REGISTRATION_ENDPOINT,+ confReq+ )+ expect(performance.now() - started).toBeLessThan(200)+ expect(outcome.ok).toBe(false)+ if (outcome.ok) return+ expect(outcome.error).toMatchObject({+ kind: 'invalid_response',+ minted: true,+ registrationClientUri: DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri,+ registrationAccessToken: DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_access_token,+ })+ })++ it('client_id length: 512 bytes accepted, 513 → invalid_response (the CRD caps spec.oauth.id at 512)', async () => {+ for (const [length, ok] of [+ [512, true],+ [513, false],+ ] as const) {+ const { transport } = makeDcrTransport({+ responseJson: JSON.stringify({+ ...DCR_PUBLIC_REGISTRATION_RESPONSE,+ client_id: 'c'.repeat(length),+ }),+ })+ const outcome = await registerDynamicClient(+ { transport, resolveDns: PUBLIC_IP },+ DCR_REGISTRATION_ENDPOINT,+ publicReq+ )+ expect(outcome.ok).toBe(ok)+ if (!outcome.ok)+ expect(outcome.error).toMatchObject({ kind: 'invalid_response', minted: true })+ }+ })+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),diff --git a/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts b/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.tsindex 7338b0709..53a0266b2 100644--- a/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts+++ b/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts@@ -196,7 +196,7 @@ describeRealPostgres(const cr = (await gateway.getResource('mcpservers', name, NS)) as Parameters<typeof resolveServerOAuthSubject>[0]- const resolved = resolveServerOAuthSubject(cr)+ const resolved = resolveServerOAuthSubject(cr, 'consent')return resolved ? { namespace: NS, ...resolved } : null},}diff --git a/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts b/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.tsindex 463e04f86..d84212db5 100644--- a/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts+++ b/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts@@ -13,6 +13,7 @@ import {deleteDynamicClientOwnedByInstall,getDynamicClient,insertDynamicClientPending,+ isDynamicClientIdRegistered,reclaimOrphanDynamicClient,upsertDynamicClient,} from '../src/oauth/dynamicClientStore.js'@@ -196,6 +197,42 @@ describeRealPostgres('dynamicClientStore install identity (real Postgres)', () =expect(after?.registrationClientUri).toBe(`https://as.example.com/reg/${name}`)})+ it('isDynamicClientIdRegistered finds a client_id in pending, bound and legacy rows of the namespace only', async () => {+ const tag = randomUUID().slice(0, 8)+ const pending = `srv-idp-${tag}`+ const bound = `srv-idb-${tag}`+ const legacy = `srv-idl-${tag}`+ await insertDynamicClientPending(db, KEY, {+ ...baseCreds(pending, { clientId: `cid-p-${tag}` }),+ installId: randomUUID(),+ })+ const boundInstall = randomUUID()+ await insertDynamicClientPending(db, KEY, {+ ...baseCreds(bound, { clientId: `cid-b-${tag}` }),+ installId: boundInstall,+ })+ await bindDynamicClientToResource(+ db,+ { serverNamespace: NS, serverName: bound },+ boundInstall,+ `uid-${tag}`+ )+ await upsertDynamicClient(db, KEY, baseCreds(legacy, { clientId: `cid-l-${tag}` }))++ for (const clientId of [`cid-p-${tag}`, `cid-b-${tag}`, `cid-l-${tag}`]) {+ expect(await isDynamicClientIdRegistered(db, { serverNamespace: NS, clientId })).toBe(true)+ }+ expect(+ await isDynamicClientIdRegistered(db, { serverNamespace: NS, clientId: `cid-none-${tag}` })+ ).toBe(false)+ expect(+ await isDynamicClientIdRegistered(db, {+ serverNamespace: `${NS}-other`,+ clientId: `cid-b-${tag}`,+ })+ ).toBe(false)+ })+const keyOf = (serverName: string) => ({ serverNamespace: NS, serverName })/**diff --git a/control-api/test/oauth.mcpServerOAuthSpec.generic.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.generic.test.tsindex d63c3ae2b..6cf28da99 100644--- a/control-api/test/oauth.mcpServerOAuthSpec.generic.test.ts+++ b/control-api/test/oauth.mcpServerOAuthSpec.generic.test.ts@@ -43,7 +43,7 @@ function serverFrom(oauth: Record<string, unknown>, contextRef = 'ctx-a'): McpSedescribe('resolveServerOAuthSubject — generic lane (DEC-28)', () => {it('public (neither ref) → secretSource:public, no refs, provider label generic', () => {- const r = resolveServerOAuthSubject(serverFrom({ ...KNOBS }))+ const r = resolveServerOAuthSubject(serverFrom({ ...KNOBS }), 'consent')expect(r).not.toBeNull()expect(r?.decl.id).toBe('my-generic-client')expect(r?.decl.provider).toBe('generic')@@ -70,7 +70,8 @@ describe('resolveServerOAuthSubject — generic lane (DEC-28)', () => {...KNOBS,clientIdRef: { name: 'gen-creds', key: 'client_id' },clientSecretRef: { name: 'gen-creds', key: 'client_secret' },- })+ }),+ 'consent')expect(r?.decl.clientIdRef).toEqual({ name: 'gen-creds', key: 'client_id' })expect(r?.decl.clientSecretRef).toEqual({ name: 'gen-creds', key: 'client_secret' })@@ -88,7 +89,8 @@ describe('resolveServerOAuthSubject — generic lane (DEC-28)', () => {refreshEndpoint: 'https://idp.example.com/refresh',resource: 'https://api.example.com',extraAuthorizeParams: { audience: 'aud-1', dropped: 42 },- })+ }),+ 'consent')expect(r?.decl.generic?.refreshEndpoint).toBe('https://idp.example.com/refresh')expect(r?.decl.generic?.resource).toBe('https://api.example.com')@@ -101,7 +103,10 @@ describe('resolveServerOAuthSubject — generic lane (DEC-28)', () => {// the runtime reader must apply the same key cap (genericKnobs: 16).const many: Record<string, string> = {}for (let i = 0; i < 20; i++) many[`k${String(i).padStart(2, '0')}`] = `v${i}`- const r = resolveServerOAuthSubject(serverFrom({ ...KNOBS, extraAuthorizeParams: many }))+ const r = resolveServerOAuthSubject(+ serverFrom({ ...KNOBS, extraAuthorizeParams: many }),+ 'consent'+ )expect(Object.keys(r?.decl.generic?.extraAuthorizeParams ?? {}).length).toBe(16)})@@ -110,7 +115,8 @@ describe('resolveServerOAuthSubject — generic lane (DEC-28)', () => {serverFrom({...KNOBS,extraAuthorizeParams: { ok: 'short', tooLong: 'x'.repeat(1025) },- })+ }),+ 'consent')const params = r?.decl.generic?.extraAuthorizeParams ?? {}// The over-long value is dropped, not truncated or forwarded.@@ -120,28 +126,34 @@ describe('resolveServerOAuthSubject — generic lane (DEC-28)', () => {it('half-declared refs (only one) fail closed to null', () => {expect(- resolveServerOAuthSubject(serverFrom({ ...KNOBS, clientIdRef: { name: 'x', key: 'y' } }))+ resolveServerOAuthSubject(+ serverFrom({ ...KNOBS, clientIdRef: { name: 'x', key: 'y' } }),+ 'consent'+ )).toBeNull()expect(- resolveServerOAuthSubject(serverFrom({ ...KNOBS, clientSecretRef: { name: 'x', key: 'y' } }))+ resolveServerOAuthSubject(+ serverFrom({ ...KNOBS, clientSecretRef: { name: 'x', key: 'y' } }),+ 'consent'+ )).toBeNull()})it('malformed wire enum fails closed to null', () => {expect(- resolveServerOAuthSubject(serverFrom({ ...KNOBS, tokenRequestFormat: 'xml' }))+ resolveServerOAuthSubject(serverFrom({ ...KNOBS, tokenRequestFormat: 'xml' }), 'consent')).toBeNull()expect(- resolveServerOAuthSubject(serverFrom({ ...KNOBS, tokenAuthMethod: 'header' }))+ resolveServerOAuthSubject(serverFrom({ ...KNOBS, tokenAuthMethod: 'header' }), 'consent')).toBeNull()expect(- resolveServerOAuthSubject(serverFrom({ ...KNOBS, scopeSeparator: 'semicolon' }))+ resolveServerOAuthSubject(serverFrom({ ...KNOBS, scopeSeparator: 'semicolon' }), 'consent')).toBeNull()})it('missing required endpoint fails closed to null', () => {const { tokenEndpoint: _drop, ...noToken } = KNOBS- expect(resolveServerOAuthSubject(serverFrom(noToken))).toBeNull()+ expect(resolveServerOAuthSubject(serverFrom(noToken), 'consent')).toBeNull()})it('resolveServerOAuth keys the grant coordinate by oauth.id (grantScope respected)', () => {@@ -166,7 +178,8 @@ describe('baked lane is unaffected by the generic branch', () => {clientSecretRef: { name: 'creds', key: 'client-secret' },scopes: ['a'],backgroundAccess: true,- })+ }),+ 'consent')expect(r?.decl.provider).toBe('google')expect('generic' in (r?.decl ?? {})).toBe(false)diff --git a/control-api/test/oauth.mcpServerOAuthSpec.lane.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.lane.test.tsindex 1f5616dcf..35dade64b 100644--- a/control-api/test/oauth.mcpServerOAuthSpec.lane.test.ts+++ b/control-api/test/oauth.mcpServerOAuthSpec.lane.test.ts@@ -55,8 +55,8 @@ describe('legacyProvider on the resolved coordinate', () => {source => {const oauth = { ...bakedOAuth('google', 'user'), source }const baked = bakedOAuth('google', 'user')- expect(resolveServerOAuthSubject(server(oauth))?.decl).toEqual(- resolveServerOAuthSubject(server(baked))?.decl+ expect(resolveServerOAuthSubject(server(oauth), 'consent')?.decl).toEqual(+ resolveServerOAuthSubject(server(baked), 'consent')?.decl)expect(normalizeMcpServerOwnerDecl(server(oauth))?.spec?.oauthClients).toEqual(normalizeMcpServerOwnerDecl(server(baked))?.spec?.oauthClientsdiff --git a/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.remote.test.tsindex 0cfe8873b..027fe7609 100644--- a/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts+++ b/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it } from 'vitest'-import type { DiscoveryResult } from '../src/oauth/discovery.js'+import { beforeAll, describe, expect, it } from 'vitest'+import { type DiscoveryResult, discoverRemoteOAuth } from '../src/oauth/discovery.js'import {type McpServerOAuthSpecInput,resolveServerOAuth,@@ -7,6 +7,7 @@ import {} from '../src/oauth/mcpServerOAuthSpec.js'import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'import { normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'+import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'/*** C4/DEC-23: `resolveServerOAuthSubject` gains the remote lane. T1 — every remote@@ -24,27 +25,23 @@ const CIMD_SELF = 'https://control.example.com/api/v1/.well-known/evenfire-mcp-c// `token: '…'` literal as a materialized credential; deriving the endpoint from// an interpolated origin keeps the value out of that shape (the guard exempts// interpolated values). Do not inline this back to a plain string literal.-const NOTION = 'https://mcp.notion.com'+const LINEAR = 'https://mcp.linear.app'++// The real discovery over the Linear probe: CIMD with RFC 9207, the only kind of AS a+// CIMD install targets, so every mode below is built from a producer-emittable result.+let linear: DiscoveryResult++beforeAll(async () => {+ const outcome = await discoverRemoteOAuth(PILOTS.linear.mcpUrl, {+ transport: makeDiscoveryTransport(PILOTS.linear),+ resolveDns: async () => ['93.184.216.34'],+ })+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)+ linear = outcome.result+})function discovery(): 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',- scopes_supported: ['read', 'write'],- },- resource: 'https://mcp.notion.com',- issuer: 'https://mcp.notion.com',- endpoints: {- authorization: `${NOTION}/authorize`,- token: `${NOTION}/token`,- registration: `${NOTION}/register`,- },- registrationMode: 'cimd',- quirks: { bearerInBody: false, supportsRefresh: true },- }+ return linear}/** Wrap a producer-emitted `spec.oauth` into a CR shape the resolver reads. */@@ -59,7 +56,10 @@ describe('resolveServerOAuthSubject — remote lane (real-producer fixtures, T1)grantScope: 'user',cimdClientId: CIMD_SELF,})- const r = resolveServerOAuthSubject(serverFrom(oauth as unknown as Record<string, unknown>))+ const r = resolveServerOAuthSubject(+ serverFrom(oauth as unknown as Record<string, unknown>),+ 'consent'+ )expect(r).not.toBeNull()expect(r?.decl.id).toBe(CIMD_SELF)expect(r?.decl.provider).toBe('remote')@@ -67,9 +67,9 @@ describe('resolveServerOAuthSubject — remote lane (real-producer fixtures, T1)expect(r?.decl.clientSecretRef).toBeUndefined()expect(r?.decl.secretSource).toEqual({ kind: 'public' })expect(r?.decl.remote).toMatchObject({- authorizationEndpoint: 'https://mcp.notion.com/authorize',- tokenEndpoint: 'https://mcp.notion.com/token',- resource: 'https://mcp.notion.com',+ authorizationEndpoint: `${LINEAR}/authorize`,+ tokenEndpoint: `${LINEAR}/token`,+ resource: `${LINEAR}/mcp`,clientMode: 'public',supportsRefresh: true,bearerInBody: false,@@ -82,7 +82,10 @@ describe('resolveServerOAuthSubject — remote lane (real-producer fixtures, T1)grantScope: 'user',dynamicClientId: 'dcr-pub-123',})- const r = resolveServerOAuthSubject(serverFrom(oauth as unknown as Record<string, unknown>))+ const r = resolveServerOAuthSubject(+ serverFrom(oauth as unknown as Record<string, unknown>),+ 'consent'+ )expect(r?.decl.id).toBe('dcr-pub-123')expect(r?.decl.secretSource).toEqual({ kind: 'public' })})@@ -93,7 +96,10 @@ describe('resolveServerOAuthSubject — remote lane (real-producer fixtures, T1)grantScope: 'user',dynamicClientId: 'dcr-conf-xyz',})- const r = resolveServerOAuthSubject(serverFrom(oauth as unknown as Record<string, unknown>))+ const r = resolveServerOAuthSubject(+ serverFrom(oauth as unknown as Record<string, unknown>),+ 'consent'+ )expect(r?.decl.id).toBe('dcr-conf-xyz')expect(r?.decl.clientIdRef).toBeUndefined()expect(r?.decl.secretSource).toEqual({ kind: 'dcr-store' })@@ -106,7 +112,10 @@ describe('resolveServerOAuthSubject — remote lane (real-producer fixtures, T1)clientSecretName: 'srv-oauth-client',preRegisteredClientId: 'client-abc',})- const r = resolveServerOAuthSubject(serverFrom(oauth as unknown as Record<string, unknown>))+ const r = resolveServerOAuthSubject(+ serverFrom(oauth as unknown as Record<string, unknown>),+ 'consent'+ )expect(r?.decl.id).toBe('client-abc')expect(r?.decl.clientIdRef).toEqual({ name: 'srv-oauth-client', key: 'client_id' })expect(r?.decl.clientSecretRef).toEqual({ name: 'srv-oauth-client', key: 'client_secret' })@@ -124,7 +133,7 @@ describe('resolveServerOAuthSubject — remote lane (real-producer fixtures, T1)cimdClientId: CIMD_SELF,}) as unknown as Record<string, unknown>delete oauth.tokenEndpoint- expect(resolveServerOAuthSubject(serverFrom(oauth))).toBeNull()+ expect(resolveServerOAuthSubject(serverFrom(oauth), 'consent')).toBeNull()})it('remote resolves the grant coordinate too (resolveServerOAuth keys by oauth.id)', () => {@@ -151,7 +160,7 @@ describe('baked lane stays byte-identical (no source)', () => {}it('returns exactly the confidential-K8s decl (no remote/secretSource keys)', () => {- const r = resolveServerOAuthSubject(serverFrom(BAKED))+ const r = resolveServerOAuthSubject(serverFrom(BAKED), 'consent')expect(r?.decl).toEqual({id: 'google-drive',provider: 'google',@@ -166,7 +175,7 @@ describe('baked lane stays byte-identical (no source)', () => {it('baked without clientSecretRef still fails closed (confidential-only)', () => {const { clientSecretRef: _drop, ...pub } = BAKED- expect(resolveServerOAuthSubject(serverFrom(pub))).toBeNull()+ expect(resolveServerOAuthSubject(serverFrom(pub), 'consent')).toBeNull()})})@@ -178,12 +187,12 @@ describe('normalizeMcpServerOwnerDecl (refresh reader) does not diverge from thecimdClientId: CIMD_SELF,})const normalized = normalizeMcpServerOwnerDecl({- metadata: { name: 'notion-remote', namespace: 'mcp-server' },+ metadata: { name: 'linear-remote', namespace: 'mcp-server' },spec: { oauth: oauth as never },})const decl = normalized?.spec?.oauthClients?.[0]expect(decl?.id).toBe(CIMD_SELF)- expect(decl?.remote?.tokenEndpoint).toBe('https://mcp.notion.com/token')+ expect(decl?.remote?.tokenEndpoint).toBe(`${LINEAR}/token`)expect(decl?.secretSource).toEqual({ kind: 'public' })})diff --git a/control-api/test/oauth.mcpServerOAuthSpec.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.test.tsindex b7a7e5ee4..8a14f7a6a 100644--- a/control-api/test/oauth.mcpServerOAuthSpec.test.ts+++ b/control-api/test/oauth.mcpServerOAuthSpec.test.ts@@ -33,7 +33,10 @@ const FULL_OAUTH = {describe('resolveServerOAuthSubject — fail-closed branches (U5)', () => {it('returns the full decl + routing for a well-formed context server', () => {- const r = resolveServerOAuthSubject(server({ ...FULL_OAUTH, grantScope: 'context' }, 'ctx-A'))+ const r = resolveServerOAuthSubject(+ server({ ...FULL_OAUTH, grantScope: 'context' }, 'ctx-A'),+ 'consent'+ )expect(r).not.toBeNull()expect(r?.decl).toEqual({id: 'google-drive',@@ -48,62 +51,83 @@ describe('resolveServerOAuthSubject — fail-closed branches (U5)', () => {})it('returns null when spec.oauth is absent', () => {- expect(resolveServerOAuthSubject(server(undefined))).toBeNull()+ expect(resolveServerOAuthSubject(server(undefined), 'consent')).toBeNull()})it('returns null when id is missing or empty', () => {- expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, id: undefined }))).toBeNull()- expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, id: '' }))).toBeNull()+ expect(+ resolveServerOAuthSubject(server({ ...FULL_OAUTH, id: undefined }), 'consent')+ ).toBeNull()+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, id: '' }), 'consent')).toBeNull()})it('returns null when provider is missing or empty', () => {- expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, provider: undefined }))).toBeNull()- expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, provider: '' }))).toBeNull()+ expect(+ resolveServerOAuthSubject(server({ ...FULL_OAUTH, provider: undefined }), 'consent')+ ).toBeNull()+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, provider: '' }), 'consent')).toBeNull()})it('returns null when clientIdRef (or its key) is missing', () => {- expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, clientIdRef: undefined }))).toBeNull()expect(- resolveServerOAuthSubject(server({ ...FULL_OAUTH, clientIdRef: { name: 'creds' } }))+ resolveServerOAuthSubject(server({ ...FULL_OAUTH, clientIdRef: undefined }), 'consent')+ ).toBeNull()+ expect(+ resolveServerOAuthSubject(+ server({ ...FULL_OAUTH, clientIdRef: { name: 'creds' } }),+ 'consent'+ )).toBeNull()})it('returns null when clientSecretRef (or its key) is missing', () => {expect(- resolveServerOAuthSubject(server({ ...FULL_OAUTH, clientSecretRef: undefined }))+ resolveServerOAuthSubject(server({ ...FULL_OAUTH, clientSecretRef: undefined }), 'consent')).toBeNull()expect(resolveServerOAuthSubject(- server({ ...FULL_OAUTH, clientSecretRef: { key: 'client-secret' } })+ server({ ...FULL_OAUTH, clientSecretRef: { key: 'client-secret' } }),+ 'consent')).toBeNull()})it('defaults grantScope to "user" for missing / non-"context" values', () => {- expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH }))?.grantScope).toBe('user')+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH }), 'consent')?.grantScope).toBe('user')expect(- resolveServerOAuthSubject(server({ ...FULL_OAUTH, grantScope: 'garbage' }))?.grantScope+ resolveServerOAuthSubject(server({ ...FULL_OAUTH, grantScope: 'garbage' }), 'consent')+ ?.grantScope).toBe('user')expect(- resolveServerOAuthSubject(server({ ...FULL_OAUTH, grantScope: 'context' }))?.grantScope+ resolveServerOAuthSubject(server({ ...FULL_OAUTH, grantScope: 'context' }), 'consent')+ ?.grantScope).toBe('context')})it('normalizes an empty / absent contextRef to undefined', () => {- expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH }, ''))?.contextRef).toBeUndefined()- expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH }))?.contextRef).toBeUndefined()- expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH }, 'ctx-Z'))?.contextRef).toBe('ctx-Z')+ expect(+ resolveServerOAuthSubject(server({ ...FULL_OAUTH }, ''), 'consent')?.contextRef+ ).toBeUndefined()+ expect(+ resolveServerOAuthSubject(server({ ...FULL_OAUTH }), 'consent')?.contextRef+ ).toBeUndefined()+ expect(+ resolveServerOAuthSubject(server({ ...FULL_OAUTH }, 'ctx-Z'), 'consent')?.contextRef+ ).toBe('ctx-Z')})it('drops non-string scope entries (never emits a non-string scope)', () => {- const r = resolveServerOAuthSubject(server({ ...FULL_OAUTH, scopes: ['ok', 5, null, 'yes'] }))+ const r = resolveServerOAuthSubject(+ server({ ...FULL_OAUTH, scopes: ['ok', 5, null, 'yes'] }),+ 'consent'+ )expect(r?.decl.scopes).toEqual(['ok', 'yes'])})// Cross-check the two producers agree on oauthClientId + grantScope + contextRef.it('agrees with resolveServerOAuth on id / grantScope / contextRef', () => {const input = server({ ...FULL_OAUTH, grantScope: 'context' }, 'ctx-A')- const subject = resolveServerOAuthSubject(input)+ const subject = resolveServerOAuthSubject(input, 'consent')const resolved = resolveServerOAuth(input)expect(subject?.decl.id).toBe(resolved?.oauthClientId)expect(subject?.grantScope).toBe(resolved?.grantScope)diff --git a/control-api/test/oauth.remoteSpecCoherence.test.ts b/control-api/test/oauth.remoteSpecCoherence.test.tsindex 4b3a25e71..b53baa246 100644--- a/control-api/test/oauth.remoteSpecCoherence.test.ts+++ b/control-api/test/oauth.remoteSpecCoherence.test.ts@@ -14,6 +14,8 @@ import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'import { normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'import { issueMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'import {+ ATLASSIAN_V2_PILOT,+ DROPBOX_PILOT,PILOTS,type PilotFixture,makeDiscoveryTransport,@@ -77,12 +79,26 @@ function bodyOnlyPilot(): PilotFixture {return { ...base, prm: { ...base.prm, json: JSON.stringify(prm) } }}+/** Dropbox as if it advertised RFC 9207: the only way discovery accepts its cross-site AS. */+function dropboxWithRfc9207(): PilotFixture {+ const as = {+ ...JSON.parse(DROPBOX_PILOT.as.json),+ authorization_response_iss_parameter_supported: true,+ }+ return { ...DROPBOX_PILOT, as: { ...DROPBOX_PILOT.as, json: JSON.stringify(as) } }+}+let headerDiscovery: DiscoveryResultlet bodyDiscovery: DiscoveryResult+// Real Atlassian v2: CIMD + DCR, no RFC 9207, every endpoint on atlassian.com.+let perServerDiscovery: DiscoveryResult+let crossSiteDiscovery: DiscoveryResultbeforeAll(async () => {headerDiscovery = await discover(PILOTS.sentry)bodyDiscovery = await discover(bodyOnlyPilot())+ perServerDiscovery = await discover(ATLASSIAN_V2_PILOT)+ crossSiteDiscovery = await discover(dropboxWithRfc9207())})function publicWithRefsOAuth(): Record<string, unknown> {@@ -103,13 +119,61 @@ function bearerInBodyOAuth(): Record<string, unknown> {}) as unknown as Record<string, unknown>}+/**+ * The CIMD identity on a server whose AS returns no `iss`. The builder emits it for any+ * discovery result; only the install refuses it, so it persists through a direct write.+ */+function cimdWithoutIssuerBindingOAuth(): Record<string, unknown> {+ return buildRemoteOAuthSpec(perServerDiscovery, {+ clientMode: 'public',+ grantScope: 'user',+ cimdClientId: CIMD_SELF,+ }) as unknown as Record<string, unknown>+}++/**+ * Dropbox's real endpoints (token on dropboxapi.com, issuer on dropbox.com) pinned on a+ * per-server CR. Discovery only accepts them with RFC 9207, so the per-server shape is+ * that output without `issForCallback` — the edit a direct write would make.+ */+function crossSitePerServerOAuth(): Record<string, unknown> {+ const oauth = buildRemoteOAuthSpec(crossSiteDiscovery, {+ clientMode: 'public',+ grantScope: 'user',+ dynamicClientId: 'dyn-dropbox-public',+ }) as unknown as Record<string, unknown>+ delete oauth.issForCallback+ return oauth+}+const INCOHERENT = [+ // CRD mirrors: refused in consent and token issuance alike.{label: 'public + secret refs',oauth: publicWithRefsOAuth,reason: 'public_client_with_secret_refs',+ consentOnly: false,+ },+ {+ label: 'bearerInBody: true',+ oauth: bearerInBodyOAuth,+ reason: 'bearer_in_body',+ consentOnly: false,+ },+ // Per-server callback rules: refused at consent only; a grant already obtained is+ // sealed to the CR's uid and refreshes against the token endpoint that issued it.+ {+ label: 'CIMD client without RFC 9207',+ oauth: cimdWithoutIssuerBindingOAuth,+ reason: 'cimd_without_issuer_binding',+ consentOnly: true,+ },+ {+ label: 'per-server AS endpoints off the issuer site',+ oauth: crossSitePerServerOAuth,+ reason: 'as_endpoints_cross_site',+ consentOnly: true,},- { label: 'bearerInBody: true', oauth: bearerInBodyOAuth, reason: 'bearer_in_body' },] as constfunction crFrom(@@ -136,17 +200,44 @@ describe('resolver mirror of the remote CRD coherence rules', () => {expect(bearerInBodyOAuth().bearerInBody).toBe(true)})+ it('the per-server fixtures really are per-server (no issForCallback) and cross-site', () => {+ expect(cimdWithoutIssuerBindingOAuth().issForCallback).toBeUndefined()+ const crossSite = crossSitePerServerOAuth()+ expect(crossSite.issForCallback).toBeUndefined()+ expect(new URL(crossSite.tokenEndpoint as string).hostname).toBe('api.dropboxapi.com')+ expect(new URL(crossSite.issuer as string).hostname).toMatch(/dropbox\.com$/)+ })+for (const c of INCOHERENT) {- it(`${c.label}: resolveServerOAuthSubject throws remote_oauth_spec_incoherent`, () => {- const err = thrownBy(() => resolveServerOAuthSubject(crFrom('srv', c.oauth())))+ it(`${c.label}: resolveServerOAuthSubject(consent) throws remote_oauth_spec_incoherent`, () => {+ const err = thrownBy(() => resolveServerOAuthSubject(crFrom('srv', c.oauth()), 'consent'))expect(err?.code).toBe('remote_oauth_spec_incoherent')expect(err?.reason).toBe(c.reason)})- it(`${c.label}: the refresh reader (normalizeMcpServerOwnerDecl) refuses it too`, () => {- const err = thrownBy(() => normalizeMcpServerOwnerDecl(crFrom('srv', c.oauth()) as never))- expect(err?.code).toBe('remote_oauth_spec_incoherent')- })+ if (c.consentOnly) {+ it(`${c.label}: resolveServerOAuthSubject(token) still resolves the subject`, () => {+ const r = resolveServerOAuthSubject(crFrom('srv', c.oauth()), 'token')+ expect(r?.decl.id).toBe(c.oauth().id)+ expect(r?.decl.remote?.tokenEndpoint).toBe(c.oauth().tokenEndpoint)+ })++ it(`${c.label}: the refresh reader (normalizeMcpServerOwnerDecl) keeps accepting it`, () => {+ const decl = normalizeMcpServerOwnerDecl(crFrom('srv', c.oauth()) as never)?.spec+ ?.oauthClients?.[0]+ expect(decl?.remote?.tokenEndpoint).toBe(c.oauth().tokenEndpoint)+ })+ } else {+ it(`${c.label}: resolveServerOAuthSubject(token) throws too`, () => {+ const err = thrownBy(() => resolveServerOAuthSubject(crFrom('srv', c.oauth()), 'token'))+ expect(err?.reason).toBe(c.reason)+ })++ it(`${c.label}: the refresh reader (normalizeMcpServerOwnerDecl) refuses it too`, () => {+ const err = thrownBy(() => normalizeMcpServerOwnerDecl(crFrom('srv', c.oauth()) as never))+ expect(err?.code).toBe('remote_oauth_spec_incoherent')+ })+ }it(`${c.label}: resolveServerOAuth still yields the grant coordinate (revoke, sweep)`, () => {const r = resolveServerOAuth(crFrom('srv', c.oauth()))@@ -163,15 +254,39 @@ describe('resolver mirror of the remote CRD coherence rules', () => {clientSecretName: 'srv-oauth-client',preRegisteredClientId: PRE_REGISTERED_CLIENT_ID,}) as unknown as Record<string, unknown>- expect(resolveServerOAuthSubject(crFrom('a', preRegistered))?.decl.secretSource?.kind).toBe(- 'k8s-secret'- )+ expect(+ resolveServerOAuthSubject(crFrom('a', preRegistered), 'consent')?.decl.secretSource?.kind+ ).toBe('k8s-secret')const cimd = buildRemoteOAuthSpec(headerDiscovery, {clientMode: 'public',grantScope: 'user',cimdClientId: CIMD_SELF,}) as unknown as Record<string, unknown>- expect(resolveServerOAuthSubject(crFrom('b', cimd))?.decl.secretSource?.kind).toBe('public')+ expect(resolveServerOAuthSubject(crFrom('b', cimd), 'consent')?.decl.secretSource?.kind).toBe(+ 'public'+ )+ // Per-server DCR on a same-site AS without RFC 9207 (what an Atlassian install writes).+ const perServerDcr = buildRemoteOAuthSpec(perServerDiscovery, {+ clientMode: 'public',+ grantScope: 'user',+ dynamicClientId: 'dyn-atlassian-public',+ }) as unknown as Record<string, unknown>+ expect(perServerDcr.issForCallback).toBeUndefined()+ const resolved = resolveServerOAuthSubject(crFrom('c', perServerDcr), 'consent')+ expect(resolved?.decl.secretSource?.kind).toBe('public')+ // The pinned issuer rides the routing: the per-server callback checks a present `iss`.+ expect(resolved?.decl.remote?.issuer).toBe(perServerDiscovery.issuer)+ // A per-server server whose client is pre-registered keeps resolving too.+ const perServerPreRegistered = buildRemoteOAuthSpec(perServerDiscovery, {+ clientMode: 'confidential',+ grantScope: 'user',+ clientSecretName: 'srv-oauth-client',+ preRegisteredClientId: PRE_REGISTERED_CLIENT_ID,+ }) as unknown as Record<string, unknown>+ expect(+ resolveServerOAuthSubject(crFrom('d', perServerPreRegistered), 'consent')?.decl.secretSource+ ?.kind+ ).toBe('k8s-secret')})})@@ -244,7 +359,7 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_iexpect(res.body).toEqual({ error: 'context_membership_denied' })})- it(`${c.label}: POST /mcp-oauth/user-token → 409 even with a fresh stored token`, async () => {+ it(`${c.label}: POST /mcp-oauth/user-token → ${c.consentOnly ? '200, the stored token is served' : '409 even with a fresh stored token'}`, async () => {const oauth = c.oauth()const uid = await seed('srv', oauth)mockPoolQuery.mockImplementation((sql: unknown) => {@@ -282,9 +397,14 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i.post('/api/v1/mcp-oauth/user-token').set('Authorization', `Bearer ${token}`).send({ mcpServerName: 'srv', userId: 'user-1' })- expect(res.status).toBe(409)- expect(res.body).toEqual({ error: 'remote_oauth_spec_incoherent', reason: c.reason })- expect(JSON.stringify(res.body)).not.toContain('LIVE-ACCESS')+ if (c.consentOnly) {+ expect(res.status).toBe(200)+ expect(JSON.stringify(res.body)).toContain('LIVE-ACCESS')+ } else {+ expect(res.status).toBe(409)+ expect(res.body).toEqual({ error: 'remote_oauth_spec_incoherent', reason: c.reason })+ expect(JSON.stringify(res.body)).not.toContain('LIVE-ACCESS')+ }})it(`${c.label}: GET /oauth-callback/remote → 409, nothing persisted`, async () => {diff --git a/control-api/test/oauth.tokenHelper.generic.test.ts b/control-api/test/oauth.tokenHelper.generic.test.tsindex 6090d8005..487b6d648 100644--- a/control-api/test/oauth.tokenHelper.generic.test.ts+++ b/control-api/test/oauth.tokenHelper.generic.test.ts@@ -19,28 +19,31 @@ const VALIDATED_IP = '93.184.216.34'const CLIENT_ID = 'my-generic-client'function genericOwnerDecl(supportsRefresh: boolean, refreshEndpoint?: string) {- const resolved = resolveServerOAuthSubject({- spec: {- contextRef: 'ctx-A',- oauth: {- source: 'generic',- id: CLIENT_ID,- authorizationEndpoint: 'https://idp.example.com/authorize',- tokenEndpoint: TOKEN_ENDPOINT,- refreshEndpoint,- resource: 'https://api.example.com',- tokenRequestFormat: 'form',- tokenAuthMethod: 'body',- scopeSeparator: 'space',- sendScope: true,- usePkce: true,- includeResponseType: true,- supportsRefresh,- grantScope: 'user',- scopes: ['read'],+ const resolved = resolveServerOAuthSubject(+ {+ spec: {+ contextRef: 'ctx-A',+ oauth: {+ source: 'generic',+ id: CLIENT_ID,+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: TOKEN_ENDPOINT,+ refreshEndpoint,+ resource: 'https://api.example.com',+ tokenRequestFormat: 'form',+ tokenAuthMethod: 'body',+ scopeSeparator: 'space',+ sendScope: true,+ usePkce: true,+ includeResponseType: true,+ supportsRefresh,+ grantScope: 'user',+ scopes: ['read'],+ },},},- })+ 'token'+ )if (!resolved) throw new Error('fixture: generic resolve returned null')return { spec: { oauthClients: [resolved.decl] } }}diff --git a/control-api/test/oauth.tokenHelper.remote.test.ts b/control-api/test/oauth.tokenHelper.remote.test.tsindex 9f83edc78..eafcb50d9 100644--- a/control-api/test/oauth.tokenHelper.remote.test.ts+++ b/control-api/test/oauth.tokenHelper.remote.test.ts@@ -1,8 +1,11 @@-import { describe, expect, it, vi } from 'vitest'+import { beforeAll, describe, expect, it, vi } from 'vitest'import type { PinnedRawResponse, PinnedTransportInput } from '../src/http/pinnedFetch.js'+import { type DiscoveryResult, discoverRemoteOAuth } from '../src/oauth/discovery.js'import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'import * as store from '../src/oauth/store.js'import { getAccessToken } from '../src/oauth/tokenHelper.js'+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'+import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'/*** C4/DEC-17 + D-8 — the REMOTE refresh goes through the IP-pinned transport (never@@ -16,25 +19,34 @@ const TOKEN_ENDPOINT = 'https://mcp.notion.com/token'const VALIDATED_IP = '93.184.216.34'const CLIENT_ID = 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client'+// Real Notion discovery: CIMD without RFC 9207. A CIMD client there (the shape a CR+// installed before the per-server callback carries) is refused at consent, but a grant it+// already holds keeps refreshing: the refresh reader resolves in the `token` phase.+let notion: DiscoveryResult++beforeAll(async () => {+ const outcome = await discoverRemoteOAuth(PILOTS.notion.mcpUrl, {+ transport: makeDiscoveryTransport(PILOTS.notion),+ resolveDns: async () => [VALIDATED_IP],+ })+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)+ notion = outcome.result+})+function remoteOwnerDecl(supportsRefresh: boolean) {- const resolved = resolveServerOAuthSubject({- spec: {- contextRef: 'ctx-A',- oauth: {- source: 'remote',- id: CLIENT_ID,- clientMode: 'public',- authorizationEndpoint: 'https://mcp.notion.com/authorize',- tokenEndpoint: TOKEN_ENDPOINT,- issuer: 'https://mcp.notion.com',- resource: 'https://mcp.notion.com',- grantScope: 'user',- scopes: ['read'],- bearerInBody: false,- supportsRefresh,- },- },+ const oauth = buildRemoteOAuthSpec(notion, {+ clientMode: 'public',+ grantScope: 'user',+ cimdClientId: CLIENT_ID,})+ expect(oauth.issForCallback).toBeUndefined()+ expect(oauth.tokenEndpoint).toBe(TOKEN_ENDPOINT)+ // `supportsRefresh` follows the AS metadata (true for Notion); the `false` case is the+ // same block with the flag flipped, as for an AS that advertises no refresh grant.+ const resolved = resolveServerOAuthSubject(+ { spec: { contextRef: 'ctx-A', oauth: { ...oauth, supportsRefresh } } },+ 'token'+ )if (!resolved) throw new Error('fixture: remote resolve returned null')return { spec: { oauthClients: [resolved.decl] } }}diff --git a/control-api/test/routes.adminRemoteMcp.test.ts b/control-api/test/routes.adminRemoteMcp.test.tsindex 452a9a540..03a8e51f4 100644--- a/control-api/test/routes.adminRemoteMcp.test.ts+++ b/control-api/test/routes.adminRemoteMcp.test.ts@@ -21,12 +21,14 @@ import {} from '../src/oauth/dynamicClientStore.js'import { decryptOAuthSecret, deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'import { probeMcpTransport } from '../src/oauth/mcpTransportProbe.js'+import { remoteCallbackVariant } from '../src/oauth/remoteCallback.js'import {type AdminRemoteMcpDeps,createAdminRemoteMcpRouter,} from '../src/routes/admin/remoteMcp.js'import { K8sNotFoundError } from '../src/services/resourceService.js'import {+ ATLASSIAN_V2_PILOT,DCR_BASIC_REGISTRATION_RESPONSE,DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,DCR_PUBLIC_REGISTRATION_RESPONSE,@@ -92,10 +94,14 @@ const inconclusiveProbe = boundProbe(async () => ({ status: 503, headers: {}, bo// discovery client run against the 2026-09-25 Vercel probe fixtures.let vercelResult: DiscoveryResult-function makeApp(gateway: MockGateway, probe: typeof probeMcpTransport = genericProbe) {+function makeApp(+ gateway: MockGateway,+ probe: typeof probeMcpTransport = genericProbe,+ deps: AdminRemoteMcpDeps = {}+) {const app = express()app.use(express.json())- app.use(createAdminRemoteMcpRouter(gateway as unknown as K8sGateway, { probe }))+ app.use(createAdminRemoteMcpRouter(gateway as unknown as K8sGateway, { probe, ...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' })@@ -396,39 +402,63 @@ describe('POST /admin/mcp-servers/remote (install saga)', () => {expect(ctx.spec.mcpServers).toContain('notion-remote')})- // R3F-H1 (regression of R3-H2): the shared remote callback fails closed without a- // pinned issuer, so an install against an AS that does NOT advertise RFC 9207 would- // create a server that can never complete OAuth (user hits 400 at consent). The- // install must reject up front. `notionResult` is the REAL Notion discovery (no- // `authorization_response_iss_parameter_supported`), derived from the real producer —- // NOT hand-authored. Fails at parent a835d7130 (install proceeds, 201 + CR).- it('rejects a remote install against an AS without RFC 9207 → 422, no CR, no Secret', async () => {- // Self-check the T1 fixture: real Notion genuinely lacks the issuer pin.+ // Before the per-server callback, an AS without RFC 9207 was refused outright (422+ // `issuer_binding_required`, R3F-H1): the shared callback has no mix-up defence without+ // `iss`. Now such an install proceeds on a redirect URI of the server's own. A+ // pre-registered client gets `/remote/<serverName>` (no nonce: the client is+ // confidential and its secret dies with the CR), returned so the operator can register+ // it. `notionResult` is the REAL Notion discovery (no RFC 9207).+ it('pre-registered against an AS without RFC 9207 → 201 on a per-server redirect URI', async () => {expect(notionResult.issForCallback).toBeUndefined()mockDiscovery(notionResult)const gw = gatewayWithContext('ctx-a')- const createResourceSpy = vi.spyOn(gw, 'createResource')- const createSecretSpy = vi.spyOn(gw, 'createSecret')+ const { db } = makeInMemoryDynamicClientsDb()+ const res = await request(makeApp(gw, genericProbe, { db }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'no-rfc9207-remote',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'pre-registered',+ clientId: 'client-abc',+ clientSecret: 'shhh-secret',+ })++ expect(res.status).toBe(201)+ expect(res.body.callbackVariant).toBe('per-server')+ expect(res.body.redirectUri).toBe(+ 'https://control.example.com/api/v1/oauth-callback/remote/no-rfc9207-remote'+ )+ const cr = (await gw.getResource('mcpservers', 'no-rfc9207-remote', NS)) as {+ spec: { oauth: Record<string, unknown> }+ }+ expect(cr.spec.oauth.issForCallback).toBeUndefined()+ expect(cr.spec.oauth.id).toBe('client-abc')+ const ctx = (await gw.getResource('contexts', 'ctx-a', NS)) as {+ spec: { mcpServers?: string[] }+ }+ expect(ctx.spec.mcpServers).toContain('no-rfc9207-remote')+ })++ // The CIMD identity lists only the shared callback, so a CIMD install on an AS without+ // RFC 9207 stays refused. Discovery never resolves `cimd` there; this mutant of its+ // real output (Notion, no RFC 9207, mode forced to `cimd`) stands for a regression in+ // mode selection, which the defensive gate must still stop before any write.+ it('CIMD against an AS without RFC 9207 (mode-selection regression) → 422, no CR', async () => {+ expect(notionResult.issForCallback).toBeUndefined()+ mockDiscovery({ ...notionResult, registrationMode: 'cimd' })+ const gw = gatewayWithContext('ctx-a')+ const createResourceSpy = vi.spyOn(gw, 'createResource')const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({- serverName: 'no-rfc9207-remote',+ serverName: 'cimd-no-iss',contextRef: 'ctx-a',baseUrl: 'https://mcp.notion.com/mcp',- mode: 'pre-registered',- clientId: 'client-abc',- clientSecret: 'shhh-secret',+ mode: 'cimd',})-- // Observable outcome (T4): rejected before any write.expect(res.status).toBe(422)expect(res.body.error).toBe('issuer_binding_required')expect(createResourceSpy).not.toHaveBeenCalled()- expect(createSecretSpy).not.toHaveBeenCalled()- await expect(gw.getResource('mcpservers', 'no-rfc9207-remote', NS)).rejects.toThrow()- const ctx = (await gw.getResource('contexts', 'ctx-a', NS)) as {- spec: { mcpServers?: string[] }- }- expect(ctx.spec.mcpServers ?? []).not.toContain('no-rfc9207-remote')})it('body-bearer resource: rejects at admission and creates no CR (the runtime cannot honor bearerInBody)', async () => {@@ -758,6 +788,8 @@ describe('POST /admin/mcp-servers/remote — DCR install saga (C2)', () => {const PUBLIC_IP = async () => ['93.184.216.34']// The DCR request needs a configured public callback origin for redirect_uris.let savedCallbackBaseUrl: string+ // Origin the live Vercel DCR captures were registered under (their echoed redirect_uris).+ const CAPTURED_DCR_ORIGIN = 'http://127.0.0.1:8090'// Real DCR DiscoveryResults, DERIVED FROM THE REAL PRODUCER by documented// subtraction (DEC-19): the actual discovery client is run against the Notion@@ -827,15 +859,16 @@ describe('POST /admin/mcp-servers/remote — DCR install saga (C2)', () => {return app}- // R3F-H1: a DCR AS without RFC 9207 must be rejected BEFORE the DCR registration- // POST (saga step 0), so no throwaway client is minted at the AS, no dynamic_clients- // row is written, and no CR is created. Fails at parent a835d7130 (install registers- // + persists + creates the CR). `dcrNoIssResult` is producer-derived (no iss), T1.- it('rejects a DCR install against an AS without RFC 9207 → 422, no DCR registration, no row, no CR', async () => {+ // Before the per-server callback, a DCR AS without RFC 9207 was refused before+ // registering (422, R3F-H1). Now the client registers a redirect URI of this+ // installation's own — `/remote/<serverName>/<installId>` — and the install succeeds.+ // `dcrNoIssResult` is producer-derived (no iss), T1; the AS echoes what we POSTed.+ it('DCR against an AS without RFC 9207 → 201, registers /remote/<name>/<installId>', async () => {vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrNoIssResult })const { db, rows } = makeInMemoryDynamicClientsDb()const { transport, calls } = makeDcrTransport({responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),+ redirectUris: 'requested',})const gw = gatewayWithContext('ctx-a')const res = await request(@@ -849,13 +882,17 @@ describe('POST /admin/mcp-servers/remote — DCR install saga (C2)', () => {mode: 'dcr',})- // Observable outcome (T4): rejected before any AS registration or write.- expect(res.status).toBe(422)- expect(res.body.error).toBe('issuer_binding_required')- // No DCR POST to the AS, no persisted dynamic_clients row, no CR.- expect(calls).toHaveLength(0)- expect(rows.size).toBe(0)- await expect(gw.getResource('mcpservers', 'no-rfc9207-dcr', NS)).rejects.toThrow()+ expect(res.status).toBe(201)+ expect(res.body.callbackVariant).toBe('per-server')+ const stored = [...rows.values()][0]+ expect(res.body.redirectUri).toBe(+ `https://control.example.com/api/v1/oauth-callback/remote/no-rfc9207-dcr/${stored.install_id}`+ )+ // The one DCR POST registered exactly the URI the install reports.+ const posts = calls.filter(c => c.method === 'POST')+ expect(posts).toHaveLength(1)+ expect(JSON.parse(posts[0].body ?? '{}').redirect_uris).toEqual([res.body.redirectUri])+ await expect(gw.getResource('mcpservers', 'no-rfc9207-dcr', NS)).resolves.toBeTruthy()})// T3(a) — fails at parent 9e4677652: DCR install returns 400 dcr_not_available there.@@ -957,6 +994,10 @@ describe('POST /admin/mcp-servers/remote — DCR install saga (C2)', () => {// triggered the Vercel downgrade in production.vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })const { db, rows } = makeInMemoryDynamicClientsDb()+ // The captured body echoes the redirect URI registered under the dev origin it was+ // captured with; the shared variant rejects an echo that differs from the request,+ // so the install runs under that same origin.+ config.oauthCallbackBaseUrl = CAPTURED_DCR_ORIGINconst { transport } = makeDcrTransport({responseJson: DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON,})@@ -1000,6 +1041,10 @@ describe('POST /admin/mcp-servers/remote — DCR install saga (C2)', () => {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()+ // The captured body echoes the redirect URI registered under the dev origin it was+ // captured with; the shared variant rejects an echo that differs from the request,+ // so the install runs under that same origin.+ config.oauthCallbackBaseUrl = CAPTURED_DCR_ORIGINconst { transport } = makeDcrTransport({responseJson: DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON,})@@ -1860,3 +1905,571 @@ describe('POST /admin/mcp-servers/remote — DCR install saga (C2)', () => {expect(deleteUrls).toEqual([MINTED_URI])})})++// ─── Per-server callback for an AS without RFC 9207 ─────────────────────────+describe('POST /admin/mcp-servers/remote — per-server callback (AS without RFC 9207)', () => {+ const PUBLIC_IP = async () => ['93.184.216.34']+ const ORIGIN = 'https://control.example.com'+ const CIMD_SELF_CLIENT_ID = `${ORIGIN}/api/v1/.well-known/evenfire-mcp-client`+ const ATLASSIAN_REGISTRATION =+ 'https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3/dcr/register'+ const NONCE_RE = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'+ let savedCallbackBaseUrl: string++ // All producer-derived (T1): the real discovery client over real probe fixtures, with+ // documented substitutions only where named.+ let atlassianResult: DiscoveryResult+ // Notion minus CIMD, confidential, no RFC 9207 → per-server DCR-confidential. Its+ // registration responses carry an RFC 7592 handle, so the cleanup DELETE is observable.+ let dcrConfNoIssResult: DiscoveryResult+ // Same AS with RFC 9207 → shared DCR-confidential.+ let dcrConfSharedResult: DiscoveryResult+ // Linear minus its registration endpoint and minus RFC 9207: CIMD-only without `iss` →+ // `manual`, i.e. the operator must pre-register.+ let cimdOnlyNoIssResult: DiscoveryResult++ function withoutRfc9207<T extends { as: { json: string } }>(pilot: T): T {+ const as = JSON.parse(pilot.as.json)+ delete as.authorization_response_iss_parameter_supported+ return { ...pilot, as: { ...pilot.as, json: JSON.stringify(as) } }+ }++ async function discoverPilot(pilot: Parameters<typeof makeDiscoveryTransport>[0]) {+ const actual = await vi.importActual<typeof import('../src/oauth/discovery.js')>(+ '../src/oauth/discovery.js'+ )+ const outcome = await actual.discoverRemoteOAuth(pilot.mcpUrl, {+ transport: makeDiscoveryTransport(pilot),+ resolveDns: PUBLIC_IP,+ })+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)+ return outcome.result+ }++ beforeAll(async () => {+ atlassianResult = await discoverPilot(ATLASSIAN_V2_PILOT)+ dcrConfNoIssResult = await discoverPilot(dcrPilot('confidential'))+ dcrConfSharedResult = await discoverPilot(withRfc9207(dcrPilot('confidential')))+ cimdOnlyNoIssResult = await discoverPilot(+ withoutRfc9207(withoutRegistrationEndpoint(PILOTS.linear))+ )+ })++ beforeEach(() => {+ vi.mocked(discoverRemoteOAuth).mockReset()+ savedCallbackBaseUrl = config.oauthCallbackBaseUrl+ config.oauthCallbackBaseUrl = ORIGIN+ })+ afterEach(() => {+ config.oauthCallbackBaseUrl = savedCallbackBaseUrl+ })++ function app(gw: MockGateway, deps: AdminRemoteMcpDeps) {+ return makeApp(gw, genericProbe, deps)+ }++ it('fixtures: Atlassian is CIMD+DCR without RFC 9207 on one site → dcr; the others as named', () => {+ expect(atlassianResult.issForCallback).toBeUndefined()+ expect(atlassianResult.as.client_id_metadata_document_supported).toBe(true)+ expect(atlassianResult.registrationMode).toBe('dcr')+ expect(dcrConfNoIssResult.issForCallback).toBeUndefined()+ expect(dcrConfSharedResult.issForCallback).toBeTruthy()+ expect(cimdOnlyNoIssResult.registrationMode).toBe('manual')+ })++ // I7 — the e2e origin of this change: Atlassian v2 returned 422 issuer_binding_required.+ it('Atlassian (CIMD+DCR, no RFC 9207, same site) → 201 by DCR on /remote/<name>/<installId>', async () => {+ mockDiscovery(atlassianResult)+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const { transport, calls } = makeDcrTransport({+ registrationEndpoint: ATLASSIAN_REGISTRATION,+ responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),+ redirectUris: 'requested',+ })+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'atlassian',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.atlassian.com/v2/mcp',+ mode: 'dcr',+ })++ expect(res.status).toBe(201)+ expect(res.body).toMatchObject({+ registrationMode: 'dcr',+ clientMode: 'public',+ callbackVariant: 'per-server',+ })+ expect(res.body.redirectUri).toMatch(+ new RegExp(`^${ORIGIN}/api/v1/oauth-callback/remote/atlassian/${NONCE_RE}$`)+ )+ // The nonce is this installation's install_id (what the callback will check).+ const stored = [...rows.values()][0]+ expect(res.body.redirectUri.endsWith(`/${stored.install_id}`)).toBe(true)+ // I4 (partial): the DCR POST registered exactly the URI the 201 reports.+ const post = calls.find(c => c.method === 'POST')+ expect(JSON.parse(post?.body ?? '{}').redirect_uris).toEqual([res.body.redirectUri])++ const cr = (await gw.getResource('mcpservers', 'atlassian', NS)) as {+ spec: { oauth: Record<string, unknown> }+ }+ expect(cr.spec.oauth.issForCallback).toBeUndefined()+ expect(cr.spec.oauth.id).toBe(DCR_PUBLIC_REGISTRATION_RESPONSE.client_id)+ })++ // I15 — one derivation: the variant the install decided before registering equals the+ // variant the runtime will derive from the CR the saga actually wrote.+ const I15_CASES = [+ { label: 'shared CIMD (Linear)', mode: 'cimd', result: () => linearResult },+ { label: 'shared DCR', mode: 'dcr', result: () => dcrConfSharedResult },+ { label: 'per-server DCR', mode: 'dcr', result: () => dcrConfNoIssResult },+ { label: 'shared pre-registered', mode: 'pre-registered', result: () => rfc9207Result },+ { label: 'per-server pre-registered', mode: 'pre-registered', result: () => notionResult },+ ] as const+ for (const c of I15_CASES) {+ it(`I15 ${c.label}: variant(install block) === variant(written CR)`, async () => {+ mockDiscovery(c.result())+ const { db } = makeInMemoryDynamicClientsDb()+ const { transport } = makeDcrTransport({+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),+ redirectUris: 'requested',+ })+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'i15-server',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: c.mode,+ ...(c.mode === 'pre-registered' ? { clientId: 'cid-i15', clientSecret: 's' } : {}),+ })+ expect(res.status).toBe(201)+ const cr = (await gw.getResource('mcpservers', 'i15-server', NS)) as {+ spec: { oauth: Record<string, unknown> }+ }+ const expected = c.result().issForCallback ? 'shared' : 'per-server'+ expect(res.body.callbackVariant).toBe(expected)+ expect(remoteCallbackVariant(cr.spec.oauth)).toBe(res.body.callbackVariant)+ })+ }++ // I12 — the registration response must report the per-server URI we asked for.+ const PER_SERVER_REJECTIONS = [+ {+ label: 'a different redirect URI (the shared one)',+ redirectUris: [`${ORIGIN}/api/v1/oauth-callback/remote`] as string[],+ kind: 'redirect_uris_mismatch',+ },+ { label: 'no redirect_uris', redirectUris: 'omit' as const, kind: 'redirect_uris_missing' },+ ]+ for (const c of PER_SERVER_REJECTIONS) {+ it(`I12 per-server DCR response with ${c.label} → 400, no CR, no row, RFC 7592 DELETE sent`, async () => {+ mockDiscovery(dcrConfNoIssResult)+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const { transport, calls } = makeDcrTransport({+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),+ redirectUris: c.redirectUris,+ })+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'i12-server',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'dcr',+ })+ expect(res.status).toBe(400)+ expect(res.body).toEqual({ error: 'dcr_registration_failed', detail: { kind: c.kind } })+ expect(rows.size).toBe(0)+ await expect(gw.getResource('mcpservers', 'i12-server', NS)).rejects.toThrow()+ const deletes = calls.filter(call => call.method === 'DELETE')+ expect(deletes.map(d => d.url)).toEqual([+ DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri,+ ])+ // The management bearer never reaches the response.+ expect(JSON.stringify(res.body)).not.toContain(+ DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_access_token+ )+ })+ }++ it('I12 shared DCR response reporting a different redirect URI → 400, no CR, no row, DELETE sent', async () => {+ mockDiscovery(dcrConfSharedResult)+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const { transport, calls } = makeDcrTransport({+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),+ redirectUris: ['https://elsewhere.example.com/api/v1/oauth-callback/remote'],+ })+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'i12-shared',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'dcr',+ })+ expect(res.status).toBe(400)+ expect(res.body.detail).toEqual({ kind: 'redirect_uris_mismatch' })+ expect(rows.size).toBe(0)+ await expect(gw.getResource('mcpservers', 'i12-shared', NS)).rejects.toThrow()+ expect(calls.filter(call => call.method === 'DELETE')).toHaveLength(1)+ })++ it('I12 shared DCR response without redirect_uris is tolerated → 201', async () => {+ mockDiscovery(dcrConfSharedResult)+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const { transport } = makeDcrTransport({+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),+ redirectUris: 'omit',+ })+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'i12-omit',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'dcr',+ })+ expect(res.status).toBe(201)+ expect(res.body.redirectUri).toBe(`${ORIGIN}/api/v1/oauth-callback/remote`)+ expect(rows.size).toBe(1)+ })++ for (const c of [+ { label: 'per-server', result: () => dcrConfNoIssResult },+ { label: 'shared', result: () => dcrConfSharedResult },+ ]) {+ it(`I12 ${c.label} DCR assigning the platform CIMD client_id → 400, no CR, no row, DELETE sent`, async () => {+ mockDiscovery(c.result())+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const { transport, calls } = makeDcrTransport({+ responseJson: JSON.stringify({+ ...DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,+ client_id: CIMD_SELF_CLIENT_ID,+ }),+ redirectUris: 'requested',+ })+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'i12-cimd',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'dcr',+ })+ expect(res.status).toBe(400)+ expect(res.body.detail).toEqual({ kind: 'client_id_is_cimd_identity' })+ expect(rows.size).toBe(0)+ await expect(gw.getResource('mcpservers', 'i12-cimd', NS)).rejects.toThrow()+ expect(calls.filter(call => call.method === 'DELETE')).toHaveLength(1)+ })+ }++ it('DCR response with an oversized client_id → 400, no CR, no row, RFC 7592 DELETE sent', async () => {+ mockDiscovery(dcrConfNoIssResult)+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const { transport, calls } = makeDcrTransport({+ responseJson: JSON.stringify({+ ...DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,+ client_id: `https://as.example.com/${'/'.repeat(200_000)}a`,+ }),+ redirectUris: 'requested',+ })+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'huge-client-id',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'dcr',+ })+ expect(res.status).toBe(400)+ expect(res.body.error).toBe('dcr_registration_failed')+ expect(res.body.detail.kind).toBe('invalid_response')+ expect(rows.size).toBe(0)+ await expect(gw.getResource('mcpservers', 'huge-client-id', NS)).rejects.toThrow()+ expect(calls.filter(call => call.method === 'DELETE')).toHaveLength(1)+ })++ it('DCR oversized client_id without an RFC 7592 handle → 400, no DELETE, internal flag not echoed', async () => {+ mockDiscovery(dcrConfNoIssResult)+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const {+ registration_client_uri: _u,+ registration_access_token: _t,+ ...noHandle+ } = DCR_CONFIDENTIAL_REGISTRATION_RESPONSE+ const { transport, calls } = makeDcrTransport({+ responseJson: JSON.stringify({ ...noHandle, client_id: 'c'.repeat(513) }),+ redirectUris: 'requested',+ })+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'huge-no-handle',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'dcr',+ })+ expect(res.status).toBe(400)+ expect(res.body.detail.kind).toBe('invalid_response')+ expect(res.body.detail.minted).toBeUndefined()+ expect(calls.filter(call => call.method === 'DELETE')).toHaveLength(0)+ expect(rows.size).toBe(0)+ })++ it('pre-registered clientId longer than the CRD cap (512) → 400 before discovery', async () => {+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, {}))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'long-cid',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'pre-registered',+ clientId: 'c'.repeat(513),+ clientSecret: 's',+ })+ expect(res.status).toBe(400)+ expect(res.body.error).toBe('invalid_request')+ expect(discoverRemoteOAuth).not.toHaveBeenCalled()+ })++ // I17 — a per-server pre-registered client belongs to exactly one server.+ async function installPreRegistered(+ gw: MockGateway,+ deps: AdminRemoteMcpDeps,+ serverName: string,+ clientId: string,+ result: DiscoveryResult = notionResult+ ) {+ mockDiscovery(result)+ return request(app(gw, deps)).post('/admin/mcp-servers/remote').send({+ serverName,+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'pre-registered',+ clientId,+ clientSecret: 'pre-reg-secret',+ })+ }++ it('I17 client_id already used by another remote server → 409, no Secret, no CR', async () => {+ const gw = gatewayWithContext('ctx-a')+ const { db } = makeInMemoryDynamicClientsDb()+ // The first server is written by the real saga (T1), not seeded by hand.+ expect((await installPreRegistered(gw, { db }, 'first-server', 'shared-cid')).status).toBe(201)+ const res = await installPreRegistered(gw, { db }, 'second-server', 'shared-cid')+ expect(res.status).toBe(409)+ expect(res.body).toMatchObject({ error: 'oauth_client_id_in_use', conflict: 'remote_server' })+ expect(res.body.message).toMatch(/separate OAuth client/)+ await expect(gw.getResource('mcpservers', 'second-server', NS)).rejects.toThrow()+ await expect(gw.getSecret('second-server-oauth-client', NS)).rejects.toThrow()+ })++ it('I17 client_id of a live DCR client → 409 (dynamic_client), no Secret, no CR', async () => {+ const gw = gatewayWithContext('ctx-a')+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const { transport } = makeDcrTransport({+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),+ redirectUris: 'requested',+ })+ // A real DCR install leaves the live dynamic_clients row (T1).+ mockDiscovery(dcrConfNoIssResult)+ const dcr = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'dcr-server',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'dcr',+ })+ expect(dcr.status).toBe(201)+ const dcrClientId = [...rows.values()][0].client_id as string+ expect(dcrClientId).toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.client_id)+ // With the CR still present the CR check answers first; remove it the way a+ // `kubectl delete` does (the row, and the client at the AS, stay behind).+ await gw.deleteResource('mcpservers', 'dcr-server', NS)+ expect(rows.size).toBe(1)++ const res = await installPreRegistered(gw, { db }, 'pre-server', dcrClientId)+ expect(res.status).toBe(409)+ expect(res.body).toMatchObject({ error: 'oauth_client_id_in_use', conflict: 'dynamic_client' })+ expect(res.body.message).toMatch(/separate OAuth client/)+ await expect(gw.getResource('mcpservers', 'pre-server', NS)).rejects.toThrow()+ await expect(gw.getSecret('pre-server-oauth-client', NS)).rejects.toThrow()+ })++ it('I17 client_id equal to the platform CIMD identity (any origin) → 409 (cimd_client)', async () => {+ const gw = gatewayWithContext('ctx-a')+ const { db } = makeInMemoryDynamicClientsDb()+ for (const clientId of [+ CIMD_SELF_CLIENT_ID,+ 'https://old-origin.example.org/api/v1/.well-known/evenfire-mcp-client',+ ]) {+ const res = await installPreRegistered(gw, { db }, 'cimd-pre', clientId)+ expect(res.status).toBe(409)+ expect(res.body).toMatchObject({ error: 'oauth_client_id_in_use', conflict: 'cimd_client' })+ expect(res.body.message).toMatch(/separate OAuth client/)+ }+ await expect(gw.getResource('mcpservers', 'cimd-pre', NS)).rejects.toThrow()+ })++ it('I17 does not constrain a shared (RFC 9207) pre-registered install → 201', async () => {+ const gw = gatewayWithContext('ctx-a')+ const { db } = makeInMemoryDynamicClientsDb()+ expect(+ (await installPreRegistered(gw, { db }, 'a-shared', 'cid-x', rfc9207Result)).status+ ).toBe(201)+ expect(+ (await installPreRegistered(gw, { db }, 'b-shared', 'cid-x', rfc9207Result)).status+ ).toBe(201)+ })++ // Per-server origin fails closed; shared keeps its historical behaviour.+ for (const baseUrl of ['', 'https://control.example.com/some/prefix']) {+ it(`per-server install with callback base URL ${JSON.stringify(baseUrl)} → 503, nothing written or minted`, async () => {+ config.oauthCallbackBaseUrl = baseUrl+ const gw = gatewayWithContext('ctx-a')+ const { db, rows } = makeInMemoryDynamicClientsDb()+ const { transport, calls } = makeDcrTransport({+ responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),+ redirectUris: 'requested',+ })+ mockDiscovery(dcrConfNoIssResult)+ const dcr = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))+ .post('/admin/mcp-servers/remote')+ .send({+ serverName: 'no-origin-dcr',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'dcr',+ })+ expect(dcr.status).toBe(503)+ expect(dcr.body).toEqual({ error: 'callback_base_url_unconfigured' })+ expect(calls).toHaveLength(0)+ expect(rows.size).toBe(0)++ const pre = await installPreRegistered(gw, { db }, 'no-origin-pre', 'cid-no-origin')+ expect(pre.status).toBe(503)+ expect(pre.body).toEqual({ error: 'callback_base_url_unconfigured' })+ await expect(gw.getSecret('no-origin-pre-oauth-client', NS)).rejects.toThrow()+ await expect(gw.getResource('mcpservers', 'no-origin-pre', NS)).rejects.toThrow()+ })+ }++ it('shared pre-registered install without a callback base URL still succeeds (no redirectUri reported)', async () => {+ config.oauthCallbackBaseUrl = ''+ const gw = gatewayWithContext('ctx-a')+ const res = await installPreRegistered(gw, {}, 'shared-no-origin', 'cid-y', rfc9207Result)+ expect(res.status).toBe(201)+ expect(res.body.callbackVariant).toBe('shared')+ expect(res.body.redirectUri).toBeUndefined()+ })++ // mode_unsupported names the missing RFC 9207 and the mode that does work.+ for (const c of [+ { label: 'DCR available (Notion)', result: () => notionResult, next: 'dcr' },+ {+ label: 'no DCR (Linear minus registration)',+ result: () => cimdOnlyNoIssResult,+ next: 'pre-registered',+ },+ ]) {+ it(`CIMD requested on a CIMD AS without RFC 9207, ${c.label} → 400 naming "${c.next}"`, async () => {+ mockDiscovery(c.result())+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, {})).post('/admin/mcp-servers/remote').send({+ serverName: 'cimd-req',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'cimd',+ })+ expect(res.status).toBe(400)+ expect(res.body).toEqual({+ error: 'mode_unsupported',+ message: `this authorization server supports CIMD but not RFC 9207; install with mode "${c.next}"`,+ })+ })+ }++ it('CIMD requested on a DCR-only AS keeps the generic message', async () => {+ mockDiscovery(dcrConfNoIssResult)+ const gw = gatewayWithContext('ctx-a')+ const res = await request(app(gw, {})).post('/admin/mcp-servers/remote').send({+ serverName: 'cimd-req2',+ contextRef: 'ctx-a',+ baseUrl: 'https://mcp.notion.com/mcp',+ mode: 'cimd',+ })+ expect(res.status).toBe(400)+ expect(res.body.message).toBe(+ 'this authorization server requires dynamic client registration; install with mode "dcr"'+ )+ })++ describe('/discover callback preview', () => {+ async function discoverWith(result: DiscoveryResult) {+ mockDiscovery(result)+ return request(makeApp(gatewayWithContext()))+ .post('/admin/mcp-servers/remote/discover')+ .send({ baseUrl: 'https://mcp.example.com/mcp' })+ }++ it('per-server DCR (Atlassian): template with {serverName}/{installId} + AS endpoint hosts', async () => {+ const res = await discoverWith(atlassianResult)+ expect(res.status).toBe(200)+ expect(res.body.callback).toEqual({+ configured: true,+ variant: 'per-server',+ redirectUriTemplate: `${ORIGIN}/api/v1/oauth-callback/remote/{serverName}/{installId}`,+ })+ expect(res.body.detected.asEndpointHosts).toEqual({+ authorization: 'auth.atlassian.com',+ token: 'auth.atlassian.com',+ registration: 'auth.atlassian.com',+ })+ })++ it('per-server pre-registered (CIMD-only AS without RFC 9207): template /remote/{serverName}', async () => {+ const res = await discoverWith(cimdOnlyNoIssResult)+ expect(res.body.callback).toEqual({+ configured: true,+ variant: 'per-server',+ redirectUriTemplate: `${ORIGIN}/api/v1/oauth-callback/remote/{serverName}`,+ })+ expect(res.body.detected.asEndpointHosts).toEqual({+ authorization: 'mcp.linear.app',+ token: 'mcp.linear.app',+ })+ })++ it('shared (Linear, RFC 9207): the real shared URI, no endpoint hosts', async () => {+ const res = await discoverWith(linearResult)+ expect(res.body.callback).toEqual({+ configured: true,+ variant: 'shared',+ redirectUriTemplate: `${ORIGIN}/api/v1/oauth-callback/remote`,+ })+ expect(res.body.detected.asEndpointHosts).toBeUndefined()+ })++ for (const baseUrl of ['', 'https://control.example.com/some/prefix']) {+ it(`per-server with callback base URL ${JSON.stringify(baseUrl)} → configured:false, no template`, async () => {+ config.oauthCallbackBaseUrl = baseUrl+ const res = await discoverWith(atlassianResult)+ expect(res.status).toBe(200)+ expect(res.body.callback).toEqual({ configured: false, variant: 'per-server' })+ })+ }+ })+})diff --git a/control-api/test/routes.registryInstall.oauth.test.ts b/control-api/test/routes.registryInstall.oauth.test.tsindex 9e6e1d191..ff9330de6 100644--- a/control-api/test/routes.registryInstall.oauth.test.ts+++ b/control-api/test/routes.registryInstall.oauth.test.ts@@ -722,7 +722,7 @@ describe('generic carril install (S3-B4)', () => {await expect(gw.getSecret('my-idp-oauth-client', 'mcp-server')).rejects.toThrow()// inv.3: the resolver (real producer→consumer) reads the CR back as public generic.- const subject = resolveServerOAuthSubject({ spec: server.spec })+ const subject = resolveServerOAuthSubject({ spec: server.spec }, 'consent')expect(subject?.decl.provider).toBe('generic')expect(subject?.decl.secretSource).toEqual({ kind: 'public' })})@@ -761,7 +761,7 @@ describe('generic carril install (S3-B4)', () => {}expect(Object.keys(secret.data ?? {}).sort()).toEqual(['client_id', 'client_secret'])- const subject = resolveServerOAuthSubject({ spec: server.spec })+ const subject = resolveServerOAuthSubject({ spec: server.spec }, 'consent')expect(subject?.decl.secretSource).toEqual({kind: 'k8s-secret',clientIdRef: { name: 'my-idp-oauth-client', key: 'client_id' },diff --git a/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts b/control-api/test/routes.registryUninstall.realPostgres.integration.test.tsindex 03718ee53..3ba4e8b21 100644--- a/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts+++ b/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts@@ -227,7 +227,8 @@ describeRealPostgres('registry uninstall tears OAuth grants down (real Postgres)const resolved = resolveServerOAuthSubject((await gw.getResource('mcpservers', name, NS)) as Parameters<typeof resolveServerOAuthSubject- >[0]+ >[0],+ 'consent')return resolved ? { namespace: NS, ...resolved } : null},diff --git a/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts b/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.tsindex 7fd0c2705..61db85ba0 100644--- a/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts+++ b/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts@@ -28,10 +28,12 @@ import type { K8sGateway } from '../src/k8s.js'import { buildCimdDocument } from '../src/oauth/cimd.js'import { type DiscoveryResult, discoverRemoteOAuth } from '../src/oauth/discovery.js'import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'import { bootstrapSharedOAuthGrant, getOAuthGrant } from '../src/oauth/store.js'import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'import { runProactiveRefreshSweep } from '../src/services/oauthProactiveRefreshCron.js'import {+ DROPBOX_PILOT,PILOTS,type PilotFixture,makeDiscoveryTransport,@@ -266,6 +268,98 @@ describeRealPostgres('proactive refresh sweep — installation identity (real Poexpect(rows).toEqual([{ has_rt: true, cr_uid: null }])})+ // A per-server CR (no RFC 9207) holding the platform CIMD client, or with AS endpoints+ // off the issuer's site, is refused at consent. A grant it already holds is sealed to+ // its uid and its endpoints are immutable, so the refresh returns to the token+ // endpoint that issued it: the sweep keeps refreshing it instead of stranding it.+ it('keeps refreshing grants of per-server CRs that consent refuses (CIMD without iss, cross-site)', async () => {+ await dbPool.query('DELETE FROM oauth_grants')+ const gateway = new MockGateway(NS)++ // Notion (real): CIMD without RFC 9207 — `discovery` of this suite.+ expect(discovery.issForCallback).toBeUndefined()+ const cimdNoIss = buildRemoteOAuthSpec(discovery, {+ clientMode: 'public',+ grantScope: 'context',+ cimdClientId: oauthId(),+ })+ // Dropbox (real): discovery accepts its cross-site AS only with RFC 9207, so the+ // per-server shape is that output without `issForCallback` (a direct write).+ const dropbox9207: PilotFixture = {+ ...DROPBOX_PILOT,+ as: {+ ...DROPBOX_PILOT.as,+ json: JSON.stringify({+ ...JSON.parse(DROPBOX_PILOT.as.json),+ authorization_response_iss_parameter_supported: true,+ }),+ },+ }+ const dropboxOutcome = await discoverRemoteOAuth(dropbox9207.mcpUrl, {+ transport: makeDiscoveryTransport(dropbox9207),+ resolveDns: async () => [VALIDATED_IP],+ })+ if (!dropboxOutcome.ok)+ throw new Error(`fixture discovery failed: ${dropboxOutcome.error.kind}`)+ const crossSite = buildRemoteOAuthSpec(dropboxOutcome.result, {+ clientMode: 'public',+ grantScope: 'context',+ dynamicClientId: 'dyn-dropbox-public',+ })+ delete crossSite.issForCallback++ const cases = [+ { name: 'cron-cimd-noiss', oauth: cimdNoIss, reason: 'cimd_without_issuer_binding' },+ { name: 'cron-cross-site', oauth: crossSite, reason: 'as_endpoints_cross_site' },+ ]+ for (const c of cases) {+ await gateway.createResource(+ 'mcpservers',+ {+ metadata: { name: c.name },+ spec: { contextRef: CONTEXT, auth: { type: 'oauth' }, oauth: c.oauth },+ },+ NS+ )+ const cr = (await gateway.getResource('mcpservers', c.name, NS)) as {+ metadata: { uid: string }+ spec: Record<string, unknown>+ }+ // Consent refuses it (the other half of the invariant).+ let consentError: { reason?: unknown } | undefined+ try {+ resolveServerOAuthSubject(cr, 'consent')+ } catch (err) {+ consentError = err as { reason?: unknown }+ }+ expect(consentError?.reason).toBe(c.reason)+ const { inserted } = await bootstrapSharedOAuthGrant(db, KEY, {+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: c.name,+ contextId: CONTEXT,+ oauthClientId: c.oauth.id as string,+ bootstrappedByUserId: 'user-1',+ provider: 'remote',+ accessToken: `AT-${c.name}`,+ refreshToken: `RT-${c.name}`,+ accessTokenExpiresInSec: IN_WINDOW_SEC,+ crUid: cr.metadata.uid,+ })+ expect(inserted).toBe(true)+ }++ tokenEndpoint.posts.length = 0+ const summary = await sweep(gateway)++ expect(summary.candidates).toBe(2)+ expect(summary.outcomes.ok).toBe(2)+ expect(summary.outcomes.error).toBe(0)+ expect(tokenEndpoint.posts.map(p => p.url).sort()).toEqual(+ [cimdNoIss.tokenEndpoint, crossSite.tokenEndpoint].sort()+ )+ })+// Invariant 8: a remote CR the CRD now rejects (public + secret refs, or// bearerInBody: true) may still exist from a write that bypassed the install// route. The sweep must not spend its refresh token; the row counts as `error`.