Skip to content

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

TypeScript

feat(control-api): per-server remote OAuth callback and authorize redirect

Diego Zacarias79ada4757e26
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index f5f8c5188..58bf51631 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.683",
+ "version": "0.1.684",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.683",
+ "version": "0.1.684",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index 63e3b2241..445613332 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.683",
+ "version": "0.1.684",
"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/__tests__/callbackMcpMembership.test.ts b/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
index acf802ebe..c4c1e14e4 100644
--- a/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
+++ b/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
@@ -56,10 +56,13 @@ function signedMcpState(): string {
function input(): CallbackInput {
return {
- oauthClientId: OAUTH_CLIENT_ID,
+ target: {
+ kind: 'client',
+ id: OAUTH_CLIENT_ID,
+ redirectUri: 'https://example.test/oauth/callback',
+ },
code: 'auth-code-single-use',
state: signedMcpState(),
- redirectUri: 'https://example.test/oauth/callback',
}
}
diff --git a/control-api/src/oauth/__tests__/callbackRemoteIss.test.ts b/control-api/src/oauth/__tests__/callbackRemoteIss.test.ts
index 6231c9ab1..adc46424f 100644
--- a/control-api/src/oauth/__tests__/callbackRemoteIss.test.ts
+++ b/control-api/src/oauth/__tests__/callbackRemoteIss.test.ts
@@ -5,7 +5,6 @@ import {
type CallbackDeps,
type CallbackInput,
type McpServerOAuthSubject,
- REMOTE_CALLBACK_CLIENT_SEGMENT,
handleOAuthCallback,
} from '../callback.js'
// State is derived from the REAL producer (T1): never hand-write the signed
@@ -77,12 +76,11 @@ function signedMcpState(): string {
function input(overrides: Partial<CallbackInput> = {}): CallbackInput {
return {
- // Stable remote callback: the URL segment is the reserved constant, the real
- // client id rides the signed state.
- oauthClientId: REMOTE_CALLBACK_CLIENT_SEGMENT,
+ // Shared remote callback: the URL carries no client id, the real one rides the
+ // signed state.
+ target: { kind: 'remote-shared', origin: 'https://callback.example.test' },
code: 'auth-code-single-use',
state: signedMcpState(),
- redirectUri: 'https://callback.example.test/api/v1/oauth-callback/remote',
...overrides,
}
}
diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.ts
index c6c590ca9..d30921940 100644
--- a/control-api/src/oauth/callback.ts
+++ b/control-api/src/oauth/callback.ts
@@ -2,11 +2,13 @@ import type { DbClient } from '../db.js'
import type { PinnedTransport } from '../http/pinnedFetch.js'
import { pinnedFetch } from '../http/pinnedFetch.js'
import type { DnsResolver } from '../http/validateMcpServerSpec.js'
+import { rootLogger } from '../observability/logger.js'
import { getDynamicClient } from './dynamicClientStore.js'
import {
type RemoteOAuthSpecIncoherence,
RemoteOAuthSpecIncoherentError,
} from './mcpServerOAuthSpec.js'
+import { buildPerServerRedirectUri, resolvePerServerRegistration } from './perServerRegistration.js'
import { deriveCodeVerifier } from './pkce.js'
import {
type GenericAdapterConfig,
@@ -18,7 +20,12 @@ import {
isKnownOAuthProvider,
parseRemoteTokenResponse,
} from './providers.js'
-import { REMOTE_CALLBACK_CLIENT_SEGMENT } from './remoteCallback.js'
+import {
+ InvalidRemoteRedirectUriInputError,
+ REMOTE_CALLBACK_CLIENT_SEGMENT,
+ buildRemoteRedirectUri,
+ remoteCallbackVariant,
+} from './remoteCallback.js'
import type { OAuthMcpStateClaims } from './state.js'
import { signOAuthState, verifyOAuthStateSignature } from './state.js'
import { bootstrapSharedOAuthGrant, setUserGrantBackground, upsertOAuthGrant } from './store.js'
@@ -28,6 +35,8 @@ import { bootstrapSharedOAuthGrant, setUserGrantBackground, upsertOAuthGrant } f
// importers of this module.
export { REMOTE_CALLBACK_CLIENT_SEGMENT }
+const log = rootLogger.child({ module: 'oauth-callback' })
+
/**
* Discriminator for WHERE an mcp-server's OAuth client credentials live
* (DEC-18). Present only on a `source:'remote'` subject; baked/recipe decls read
@@ -211,26 +220,55 @@ export interface McpServerOAuthReader {
export class SecretNotFoundError extends Error {}
export class RecipeNotFoundError extends Error {}
+/**
+ * Which callback URL the provider redirected to. Decided by the route from the path
+ * shape alone; the handler then checks it against the signed state and the CR.
+ *
+ * - `client` — `/oauth-callback/<oauthClientId>` (recipe, baked, generic).
+ * - `remote-shared` — `/oauth-callback/remote`: every remote server whose AS
+ * returns RFC 9207 `iss`, which is what binds the code there.
+ * - `remote-per-server` — `/oauth-callback/remote/<serverName>[/<installNonce>]`: a
+ * remote server whose AS does not return `iss`, where the URI
+ * itself is the binding. Both segments are already validated.
+ *
+ * The remote kinds carry an origin, not a URI: the redirect URI replayed on the token
+ * exchange is rebuilt from the signed state and the CR once they have been checked,
+ * never from the request path.
+ */
+export type CallbackTarget =
+ | {
+ kind: 'client'
+ id: string
+ /** Public URL registered for this client; replayed on the token POST. */
+ redirectUri: string
+ }
+ | {
+ kind: 'remote-shared'
+ /** Origin of the shared callback (the configured base URL, else the request Host). */
+ origin: string
+ }
+ | {
+ kind: 'remote-per-server'
+ serverName: string
+ installNonce?: string
+ /** The configured public origin; null when none is configured (fails closed). */
+ origin: string | null
+ }
+
export interface CallbackInput {
- /**
- * oauthClientId from the callback URL path. The (recipeNamespace, recipeName)
- * are no longer carried in the URL — they are recovered from the signed state
- * — but this id rides the stable path and is cross-checked against the claims
- * for defence in depth.
- */
- oauthClientId: string
+ target: CallbackTarget
/** OAuth `code` query parameter from the provider redirect. */
code: string
/** Signed state value (we re-verify before doing anything). */
state: string
- /** Public URL we registered with the provider; included in the token POST. */
- redirectUri: string
/**
- * RFC 9207 `iss` from the authorization-response redirect (`req.query.iss`);
- * validated on the remote lane against the pinned `issForCallback`. Absent on
- * the baked lane (baked ASes do not advertise `iss`), where it is ignored.
+ * RFC 9207 `iss` exactly as parsed from the query (`req.query.iss`): a string, an
+ * array when repeated, an object for bracket syntax, or undefined. Kept raw because
+ * the two remote variants read it differently: the shared callback treats anything
+ * but a string as absent, while the per-server callback rejects a malformed value
+ * instead of letting it pass as "no iss". Ignored on the `client` target.
*/
- iss?: string
+ iss?: unknown
}
export interface CallbackDeps {
@@ -328,6 +366,11 @@ export type CallbackResult =
* closed BEFORE the single-use code is exchanged. No value fields.
*/
| { kind: 'issuer_binding_required' }
+ /**
+ * A per-server remote callback with no usable configured public origin: its redirect
+ * URI cannot be rebuilt byte-for-byte, so the code is not exchanged.
+ */
+ | { kind: 'callback_base_url_unconfigured' }
| { kind: 'unknown_oauth_client' }
| { kind: 'recipe_not_found' }
/** mcp subject: the McpServer named in the signed state does not exist / is not OAuth. */
@@ -355,6 +398,8 @@ export type CallbackResult =
| { kind: 'provider_token_exchange_failed'; status: number; body: string }
| { kind: 'provider_response_invalid'; detail: string }
+const BINDING_MISMATCH = { kind: 'invalid_state', reason: 'binding_mismatch' } as const
+
/**
* Run the full callback flow. Pure relative to its `CallbackDeps` so tests
* inject stub readers / fetch / db.
@@ -365,33 +410,44 @@ export async function handleOAuthCallback(
): Promise<CallbackResult> {
// ─── 1. Verify state signature, recover binding from the claims ───────
// The callback URL no longer carries the subject coordinates — they are
- // recovered from the signed, unforgeable state. The oauthClientId still rides
- // the stable URL path, so cross-check it against the claims for defence in
- // depth. The subject identity itself needs no such check: the HMAC guarantees
- // it, and every authorize-url minter only signs its own namespace's states.
+ // recovered from the signed, unforgeable state. Whatever the URL does carry is
+ // cross-checked against the claims: the subject identity itself needs no such
+ // check (the HMAC guarantees it), but the URL is where the AS delivered the code,
+ // and on the per-server remote callback that location IS the mix-up defence.
const verified = verifyOAuthStateSignature(deps.stateSecret, input.state)
if (verified.kind !== 'ok') {
return { kind: 'invalid_state', reason: verified.kind }
}
const claims = verified.claims
- // Defence-in-depth: the URL segment must equal the signed client id — EXCEPT on
- // the stable remote callback (`/oauth-callback/remote`), where CIMD/DCR register
- // one fixed redirect_uri and the segment is the reserved constant, not the
- // client id. There the binding rides the HMAC state (`subjectKind:'mcp'` +
- // `mcpServerName`) and is re-checked below against the freshly-resolved subject
- // (`subject.decl.id === claims.oauthClientId`). Recipe subjects always enforce
- // the segment==id check (the reserved segment is mcp-only).
- const isRemoteStableSegment =
- claims.subjectKind === 'mcp' && input.oauthClientId === REMOTE_CALLBACK_CLIENT_SEGMENT
- if (!isRemoteStableSegment && claims.oauthClientId !== input.oauthClientId) {
- return { kind: 'invalid_state', reason: 'binding_mismatch' }
- }
+ const target = input.target
- // Dispatch by the signed subject. mcp subjects go to their own handler; the
- // recipe path below is unchanged (byte-identical grant persistence).
if (claims.subjectKind === 'mcp') {
- return handleMcpOAuthCallback(claims, input, deps, isRemoteStableSegment)
+ // `/oauth-callback/<id>`: the segment must be the signed client id.
+ if (target.kind === 'client' && claims.oauthClientId !== target.id) return BINDING_MISMATCH
+ // `/remote/<serverName>/…`: a code delivered to one server's URI must never be
+ // attributed to another, and this is decided before the CR the state names is even
+ // read — an AS that redirects to `a` with `b`'s state learns nothing about `b`.
+ if (target.kind === 'remote-per-server' && claims.mcpServerName !== target.serverName) {
+ return BINDING_MISMATCH
+ }
+ return handleMcpOAuthCallback(claims, input, deps)
+ }
+
+ // Recipe subject. The per-server URI only exists for remote mcp servers. A recipe
+ // client may legitimately be named `remote` (operator-authored id), so the shared
+ // path keeps the segment==id rule for it, over the same bytes it always used.
+ let recipeRedirectUri: string
+ let segmentId: string
+ if (target.kind === 'client') {
+ segmentId = target.id
+ recipeRedirectUri = target.redirectUri
+ } else if (target.kind === 'remote-shared') {
+ segmentId = REMOTE_CALLBACK_CLIENT_SEGMENT
+ recipeRedirectUri = buildRemoteRedirectUri({ origin: target.origin, variant: 'shared' })
+ } else {
+ return BINDING_MISMATCH
}
+ if (claims.oauthClientId !== segmentId) return BINDING_MISMATCH
const recipeNamespace = claims.recipeNamespace
const recipeName = claims.recipeName
@@ -416,7 +472,13 @@ export async function handleOAuthCallback(
if (!clientDecl) return { kind: 'unknown_oauth_client' }
// ─── 3-4. Read secrets + exchange code ────────────────────────────────
- const exchanged = await exchangeAuthCode(clientDecl, recipeNamespace, undefined, input, deps)
+ const exchanged = await exchangeAuthCode(
+ clientDecl,
+ recipeNamespace,
+ undefined,
+ { code: input.code, state: input.state, redirectUri: recipeRedirectUri },
+ deps
+ )
if (exchanged.kind !== 'ok') return exchanged
const { provider, parsed } = exchanged
@@ -492,8 +554,7 @@ export async function handleOAuthCallback(
async function handleMcpOAuthCallback(
claims: OAuthMcpStateClaims,
input: CallbackInput,
- deps: CallbackDeps,
- isRemoteStableSegment: boolean
+ deps: CallbackDeps
): Promise<CallbackResult> {
// Fail closed: an mcp state cannot be processed without an mcp reader wired.
if (!deps.mcpServerReader) return { kind: 'server_not_found' }
@@ -511,54 +572,39 @@ async function handleMcpOAuthCallback(
if (!subject) return { kind: 'server_not_found' }
// Defence in depth: the resolved server's declared oauthClient must match the
- // client id bound in the signed state. Check against `claims.oauthClientId`
- // (NOT `input.oauthClientId`): on the stable remote callback the URL segment is
- // the reserved `remote` constant, not the client id — the state carries the real
- // one. For the baked mcp lane `claims.oauthClientId === input.oauthClientId`
- // (enforced above), so this stays equivalent.
- if (subject.decl.id !== claims.oauthClientId) {
- return { kind: 'invalid_state', reason: 'binding_mismatch' }
- }
- // The segment==id waiver above is only sound for remote subjects, whose issuer
- // check below replaces it. A baked/generic state delivered here would bypass
- // both, leaving the AS's own redirect_uri comparison as the only binding — and
- // the generic lane exists precisely for ASes that may not enforce it. A
- // non-remote server that nonetheless owns the reserved id (e.g. written straight
- // to the apiserver) fails closed here instead of completing consent.
- if (isRemoteStableSegment && !subject.decl.remote) {
- return { kind: 'invalid_state', reason: 'binding_mismatch' }
- }
+ // client id bound in the signed state. Checked against `claims.oauthClientId`
+ // because on the remote callbacks the URL carries no client id at all.
+ if (subject.decl.id !== claims.oauthClientId) return BINDING_MISMATCH
- // ─── RFC 9207 issuer check (remote lane only) ─────────────────────────────
- // Authorization-server mix-up defence: an attacker who controls one AS in a
- // multi-AS deployment can trick a client into sending a code minted by the
- // honest AS to the attacker's token endpoint (or vice versa). RFC 9207 binds
- // the authorization response to its issuer via the `iss` query param; we pin
- // the honest issuer at discovery (`issForCallback`) and require the callback's
- // `iss` to match it here — BEFORE the single-use code is ever exchanged.
- //
- // FAIL CLOSED for every remote subject. The stable remote callback
- // (`/oauth-callback/remote`) is SHARED across all remote subjects (CIMD/DCR/
- // pre-registered register ONE fixed redirect_uri), so whether the check runs
- // must NOT be governed by the resolved AS's own advertised metadata: a
- // malicious installed AS whose discovery omitted `iss` (⇒ `issForCallback`
- // absent) could relay the user to an honest AS sharing this redirect/state/PKCE
- // and have the honest code attributed to itself. So a remote subject with no
- // pinned issuer can never satisfy the defence — reject rather than bind a code
- // we cannot attribute. The baked/generic lanes have no `decl.remote`; they are
- // unaffected (this is a remote-lane defence only).
- if (subject.decl.remote) {
- const expectedIss = subject.decl.remote.issForCallback
- if (typeof expectedIss !== 'string' || expectedIss.length === 0) {
- // No issuer pinned at install → the mix-up defence is unsatisfiable for this
- // server. (An install-time guard would surface this to the operator earlier
- // instead of the user at consent — tracked as a follow-up.)
- return { kind: 'issuer_binding_required' }
- }
- // Fail closed on any deviation, INCLUDING an absent/empty callback `iss`.
- if (input.iss !== expectedIss) {
- return { kind: 'issuer_mismatch' }
- }
+ // The callback URL must be the one this server's lane registers, in both
+ // directions: remote servers only ever register a remote URI, and the remote
+ // URIs waive the segment==id rule on the strength of checks (issuer, per-server
+ // binding) that only exist for remote servers. A baked/generic server that owns
+ // the reserved id, or a remote server reached through `/oauth-callback/<id>`,
+ // fails closed instead of leaving the AS's own redirect_uri comparison — which
+ // the generic lane cannot rely on — as the only binding.
+ const target = input.target
+ const remote = subject.decl.remote
+ const reachedOnRemoteUri = target.kind !== 'client'
+ if (reachedOnRemoteUri !== Boolean(remote)) return BINDING_MISMATCH
+
+ let redirectUri: string
+ if (target.kind === 'client') {
+ redirectUri = target.redirectUri
+ } else if (target.kind === 'remote-shared') {
+ const rejected = checkSharedCallbackIssuer(remote as RemoteClientRouting, input.iss)
+ if (rejected) return rejected
+ redirectUri = buildRemoteRedirectUri({ origin: target.origin, variant: 'shared' })
+ } else {
+ const perServer = await checkPerServerCallback(
+ subject,
+ claims.mcpServerName,
+ target,
+ input.iss,
+ deps.db
+ )
+ if (perServer.kind !== 'ok') return perServer
+ redirectUri = perServer.redirectUri
}
// ─── Membership guards run BEFORE the token exchange (R3-L1) ──────────────
@@ -596,7 +642,7 @@ async function handleMcpOAuthCallback(
subject.decl,
subject.namespace,
{ name: claims.mcpServerName, crUid: subject.crUid },
- input,
+ { code: input.code, state: input.state, redirectUri },
deps
)
if (exchanged.kind !== 'ok') return exchanged
@@ -609,10 +655,10 @@ async function handleMcpOAuthCallback(
recipeNamespace: subject.namespace,
recipeName: claims.mcpServerName,
contextId: contextRef,
- // Grant coordinate = the resolved client id (`oauth.id`), NEVER the URL
- // segment: on the stable remote callback `input.oauthClientId` is the literal
- // `remote`. `subject.decl.id === claims.oauthClientId` (checked above), and it
- // matches what the token broker keys by (`resolveServerOAuth`, D4).
+ // Grant coordinate = the resolved client id (`oauth.id`), NEVER the URL: the
+ // remote callbacks carry no client id in it. `subject.decl.id ===
+ // claims.oauthClientId` (checked above), and it matches what the token broker
+ // keys by (`resolveServerOAuth`, D4).
oauthClientId: subject.decl.id,
// Bootstrapper = the signed initiator. Audit-only, first-wins on conflict.
bootstrappedByUserId: claims.userId,
@@ -657,6 +703,111 @@ async function handleMcpOAuthCallback(
}
}
+/**
+ * RFC 9207 check of the shared remote callback. The shared URI carries no per-server
+ * binding, so `iss` is the only thing that attributes a code to the AS that minted it:
+ * pinned at discovery (`issForCallback`) and required to match exactly, before the
+ * single-use code is exchanged.
+ *
+ * Fails closed when the server pinned no issuer. The shared callback serves every
+ * remote server, so whether the check runs must not depend on the resolved AS's own
+ * metadata: a malicious installed AS that omitted `iss` could otherwise relay the user
+ * to an honest AS sharing this redirect/state/PKCE and have the honest code attributed
+ * to itself. Such a server belongs on its per-server URI instead.
+ */
+function checkSharedCallbackIssuer(
+ remote: RemoteClientRouting,
+ rawIss: unknown
+): { kind: 'issuer_binding_required' } | { kind: 'issuer_mismatch' } | null {
+ const expectedIss = remote.issForCallback
+ if (typeof expectedIss !== 'string' || expectedIss.length === 0) {
+ return { kind: 'issuer_binding_required' }
+ }
+ // Anything but a string (repeated or bracketed parameter) reads as absent, and
+ // absent never matches a pinned issuer.
+ const iss = typeof rawIss === 'string' ? rawIss : undefined
+ return iss === expectedIss ? null : { kind: 'issuer_mismatch' }
+}
+
+type PerServerCheckResult =
+ | { kind: 'ok'; redirectUri: string }
+ | { kind: 'invalid_state'; reason: 'binding_mismatch' }
+ | { kind: 'issuer_mismatch' }
+ | { kind: 'callback_base_url_unconfigured' }
+
+/**
+ * Checks of the per-server remote callback (`/remote/<serverName>[/<installNonce>]`),
+ * for an AS that does not return RFC 9207 `iss`. The server name was already matched
+ * to the signed state before the CR was read; here:
+ *
+ * 1. the CR must use the per-server variant — a server whose AS returns `iss` is
+ * bound by it on the shared callback and must never be reachable here;
+ * 2. the URI must be the one this installation registered: for DCR, the nonce of the
+ * row bound to this CR; for pre-registered, no nonce (the mode comes from the CR);
+ * 3. an `iss` the AS sends anyway must be the pinned issuer — but it cannot be
+ * required, which is why this variant exists;
+ * 4. the redirect URI for the exchange is rebuilt from the signed server name and the
+ * stored registration, not from the request path.
+ */
+async function checkPerServerCallback(
+ subject: McpServerOAuthSubject,
+ serverName: string,
+ target: Extract<CallbackTarget, { kind: 'remote-per-server' }>,
+ rawIss: unknown,
+ db: DbClient
+): Promise<PerServerCheckResult> {
+ const remote = subject.decl.remote as RemoteClientRouting
+ if (remoteCallbackVariant(remote) !== 'per-server') return BINDING_MISMATCH
+
+ const registration = await resolvePerServerRegistration(db, subject, serverName)
+ if (!registration) return BINDING_MISMATCH
+ const expectedNonce = registration.mode === 'dcr' ? registration.installNonce : undefined
+ if (target.installNonce !== expectedNonce) return BINDING_MISMATCH
+
+ const issRejection = perServerIssRejection(rawIss, remote.issuer)
+ if (issRejection) {
+ // Only the server and the reason: the query also carries `code` and `state`,
+ // which the log redaction does not cover.
+ log.warn({ serverName, reason: issRejection }, 'per-server oauth callback iss rejected')
+ return { kind: 'issuer_mismatch' }
+ }
+
+ if (target.origin === null) return { kind: 'callback_base_url_unconfigured' }
+ try {
+ return {
+ kind: 'ok',
+ redirectUri: buildPerServerRedirectUri(target.origin, serverName, registration),
+ }
+ } catch (err) {
+ if (err instanceof InvalidRemoteRedirectUriInputError) {
+ return { kind: 'callback_base_url_unconfigured' }
+ }
+ throw err
+ }
+}
+
+/**
+ * Validate an `iss` the AS sent on a per-server callback. Absent is fine; a present
+ * value must be a single non-empty string equal to the pinned issuer. A repeated,
+ * bracketed or empty parameter is rejected rather than read as absent, so an attacker
+ * who can append to the query cannot turn a wrong issuer into "no issuer".
+ */
+function perServerIssRejection(
+ rawIss: unknown,
+ pinnedIssuer: string | undefined
+): 'iss_malformed' | 'iss_mismatch' | null {
+ if (rawIss === undefined) return null
+ if (typeof rawIss !== 'string' || rawIss.length === 0) return 'iss_malformed'
+ return rawIss === pinnedIssuer ? null : 'iss_mismatch'
+}
+
+/** The authorization-code grant a callback redeems, with the redirect URI to replay. */
+interface AuthCodeGrant {
+ code: string
+ state: string
+ redirectUri: string
+}
+
type ExchangeAuthCodeResult =
| { kind: 'ok'; provider: GrantProviderLabel; parsed: ParsedTokenResponse }
| { kind: 'unknown_oauth_client' }
@@ -676,21 +827,21 @@ async function exchangeAuthCode(
secretNamespace: string,
/** mcp-server owner (dynamic-client coordinate + installation); undefined for the recipe lane. */
owner: RemoteCredentialOwner | undefined,
- input: CallbackInput,
+ grant: AuthCodeGrant,
deps: CallbackDeps
): Promise<ExchangeAuthCodeResult> {
// Remote lane (`source:'remote'`): discovery-derived endpoint ⇒ IP-pinned POST
// (DEC-17), public token client, credentials per `secretSource`. Byte-identical
// baked path is below (unchanged).
if (decl.remote) {
- return exchangeRemoteAuthCode(decl, secretNamespace, owner, input, deps)
+ return exchangeRemoteAuthCode(decl, secretNamespace, owner, grant, deps)
}
// Generic self-hosted lane (`source:'generic'`): knob-configured request over
// the same IP-pinned POST (DEC-17). Credentials per `secretSource` (public or
// k8s-secret). Baked path is below (unchanged).
if (decl.generic) {
- return exchangeGenericAuthCode(decl, secretNamespace, owner, input, deps)
+ return exchangeGenericAuthCode(decl, secretNamespace, owner, grant, deps)
}
// Baked/recipe lane. clientIdRef is always present here (remote is the only
@@ -744,7 +895,7 @@ async function exchangeAuthCode(
// PKCE (DEC-1): re-derive the verifier from the EXACT round-tripped state
// string — the same signed value the authorize URL derived its challenge from.
const codeVerifier = adapter.usesPkce
- ? deriveCodeVerifier(deps.stateSecret, input.state)
+ ? deriveCodeVerifier(deps.stateSecret, grant.state)
: undefined
try {
@@ -754,10 +905,10 @@ async function exchangeAuthCode(
// closed, no token) instead of an opaque 500 — symmetric with tokenHelper's
// wrapped `buildRefreshRequest`.
const tokenRequest = adapter.buildTokenRequest({
- code: input.code,
+ code: grant.code,
clientId,
clientSecret,
- redirectUri: input.redirectUri,
+ redirectUri: grant.redirectUri,
codeVerifier,
})
const response = await deps.fetchFn(tokenRequest.url, {
@@ -786,7 +937,7 @@ async function exchangeRemoteAuthCode(
decl: OAuthClientDecl,
secretNamespace: string,
owner: RemoteCredentialOwner | undefined,
- input: CallbackInput,
+ grant: AuthCodeGrant,
deps: CallbackDeps
): Promise<ExchangeAuthCodeResult> {
// `decl.remote` presence is the branch guard in the caller.
@@ -796,14 +947,14 @@ async function exchangeRemoteAuthCode(
// PKCE (DEC-1 / §6 #3): the remote lane is ALWAYS S256 — re-derive the verifier
// from the exact round-tripped state, same as the baked PKCE adapters.
- const codeVerifier = deriveCodeVerifier(deps.stateSecret, input.state)
+ const codeVerifier = deriveCodeVerifier(deps.stateSecret, grant.state)
const tokenRequest = buildRemoteTokenRequest(
remote.tokenEndpoint,
{
- code: input.code,
+ code: grant.code,
clientId: credResult.cred.clientId,
clientSecret: credResult.cred.clientSecret,
- redirectUri: input.redirectUri,
+ redirectUri: grant.redirectUri,
codeVerifier,
},
remote.resource
@@ -846,7 +997,7 @@ async function exchangeGenericAuthCode(
decl: OAuthClientDecl,
secretNamespace: string,
owner: RemoteCredentialOwner | undefined,
- input: CallbackInput,
+ grant: AuthCodeGrant,
deps: CallbackDeps
): Promise<ExchangeAuthCodeResult> {
// `decl.generic` presence is the branch guard in the caller.
@@ -858,7 +1009,7 @@ async function exchangeGenericAuthCode(
// PKCE gated on the knob: re-derive the verifier from the exact round-tripped
// state (the authorize URL derived its challenge from the same value).
const codeVerifier = generic.usePkce
- ? deriveCodeVerifier(deps.stateSecret, input.state)
+ ? deriveCodeVerifier(deps.stateSecret, grant.state)
: undefined
let tokenRequest: ReturnType<typeof adapter.buildTokenRequest>
@@ -866,10 +1017,10 @@ async function exchangeGenericAuthCode(
// The build can throw (e.g. tokenAuthMethod=basic on a secret-less client) —
// turn that into a typed fail-closed result, never an opaque 500.
tokenRequest = adapter.buildTokenRequest({
- code: input.code,
+ code: grant.code,
clientId: credResult.cred.clientId,
clientSecret: credResult.cred.clientSecret,
- redirectUri: input.redirectUri,
+ redirectUri: grant.redirectUri,
codeVerifier,
})
} catch (err) {
diff --git a/control-api/src/oauth/discovery.ts b/control-api/src/oauth/discovery.ts
index 761be26c2..31e7c1ba4 100644
--- a/control-api/src/oauth/discovery.ts
+++ b/control-api/src/oauth/discovery.ts
@@ -634,10 +634,10 @@ async function resolvePrm(
* `hasPreRegisteredClient` reflects operator config (a pre-registered Secret),
* defaulting to false.
*
- * Mirror: control-ui hand-copies this projection (the `detected` shape the remoteMcp
- * route builds from this result) in test/fixtures/__tests__/remoteMcpDiscovery.contract.test.ts
- * (projectDetected), because control-api is not importable there. A shape change here
- * must be reflected in that copy or its fixtures certify a stale shape.
+ * Contract with control-ui: the `/discover` and install responses built from this
+ * result are pinned as wire goldens by test/routes.adminRemoteMcp.wireGoldens.test.ts,
+ * which control-ui's fixtures consume (control-api is not importable there). A shape
+ * change here must regenerate those goldens or control-ui certifies a stale shape.
*/
export async function discoverRemoteOAuth(
mcpUrl: string,
diff --git a/control-api/src/oauth/dynamicClientStore.ts b/control-api/src/oauth/dynamicClientStore.ts
index ee272edc7..cae4f6b9f 100644
--- a/control-api/src/oauth/dynamicClientStore.ts
+++ b/control-api/src/oauth/dynamicClientStore.ts
@@ -265,6 +265,39 @@ export async function isDynamicClientIdRegistered(
return result.rows.length > 0
}
+/** The installation identity of a dynamic client, without any credential material. */
+export interface DynamicClientBinding {
+ clientId: string
+ /** Install nonce the client's redirect URI was registered with; undefined = legacy row. */
+ installId?: string
+ /** metadata.uid of the McpServer the row is bound to; undefined = pending or legacy. */
+ crUid?: string
+}
+
+/**
+ * Read which installation a server's dynamic client belongs to. Reads no encrypted
+ * column, so the consent paths can check the binding without decrypting a secret they
+ * may never use.
+ */
+export async function getDynamicClientBinding(
+ db: DbClient,
+ key: DynamicClientKey
+): Promise<DynamicClientBinding | null> {
+ const result = await db.query(
+ `SELECT client_id, install_id, cr_uid
+ FROM dynamic_clients
+ WHERE owner_kind = $1 AND server_namespace = $2 AND server_name = $3`,
+ [resolveOwnerKind(key), key.serverNamespace, key.serverName]
+ )
+ if (result.rows.length === 0) return null
+ const row = result.rows[0] as Pick<DynamicClientDbRow, 'client_id' | 'install_id' | 'cr_uid'>
+ return {
+ clientId: row.client_id,
+ installId: row.install_id ?? undefined,
+ crUid: row.cr_uid ?? undefined,
+ }
+}
+
/**
* Metadata-only view of a `dynamic_clients` row whose confidential secret is at
* or near expiry — enough for the DCR lifecycle decision (§5) without touching
diff --git a/control-api/src/oauth/perServerRegistration.ts b/control-api/src/oauth/perServerRegistration.ts
new file mode 100644
index 000000000..027ee0553
--- /dev/null
+++ b/control-api/src/oauth/perServerRegistration.ts
@@ -0,0 +1,62 @@
+import type { DbClient } from '../db.js'
+import type { McpServerOAuthSubject } from './callback.js'
+import { getDynamicClientBinding } from './dynamicClientStore.js'
+import { buildRemoteRedirectUri, isValidInstallNonce } from './remoteCallback.js'
+
+/**
+ * How a per-server remote client is registered at its AS, which decides the shape of
+ * its redirect URI: a DCR client registered `/remote/<serverName>/<installNonce>`, a
+ * pre-registered one `/remote/<serverName>`.
+ */
+export type PerServerRegistration =
+ | { mode: 'pre-registered' }
+ | { mode: 'dcr'; installNonce: string }
+
+/**
+ * Resolve the registration of a per-server remote server, shared by the authorize-URL
+ * mint and the callback so the URI sent to the AS and the one accepted back cannot
+ * disagree.
+ *
+ * The mode comes from the CR, never from whether a `dynamic_clients` row exists: a CR
+ * with both secret refs is pre-registered; anything else is DCR and must have a row.
+ * Deriving it from the row would let a public CR without refs (written by GitOps, or
+ * whose row was deleted) be treated as pre-registered and accept a nonce-less URI —
+ * a public pre-registered client, which the per-server variant cannot protect because
+ * its codes stay redeemable after a same-name reinstall.
+ *
+ * A DCR registration is only returned for a row bound to this very CR (`cr_uid`), with
+ * a valid nonce and the CR's client id. A pending row, a legacy row without a nonce, or
+ * a row of a previous installation of the same name yields null: consent fails closed.
+ */
+export async function resolvePerServerRegistration(
+ db: DbClient,
+ subject: Pick<McpServerOAuthSubject, 'namespace' | 'decl' | 'crUid'>,
+ serverName: string
+): Promise<PerServerRegistration | null> {
+ if (subject.decl.secretSource?.kind === 'k8s-secret') return { mode: 'pre-registered' }
+ if (subject.crUid === undefined) return null
+ const row = await getDynamicClientBinding(db, {
+ serverNamespace: subject.namespace,
+ serverName,
+ })
+ if (!row || row.crUid !== subject.crUid || row.clientId !== subject.decl.id) return null
+ if (!isValidInstallNonce(row.installId)) return null
+ return { mode: 'dcr', installNonce: row.installId }
+}
+
+/** The per-server redirect URI of a resolved registration. Throws like its builder. */
+export function buildPerServerRedirectUri(
+ origin: string,
+ serverName: string,
+ registration: PerServerRegistration
+): string {
+ return registration.mode === 'dcr'
+ ? buildRemoteRedirectUri({
+ origin,
+ variant: 'per-server',
+ mode: 'dcr',
+ serverName,
+ installNonce: registration.installNonce,
+ })
+ : buildRemoteRedirectUri({ origin, variant: 'per-server', mode: 'pre-registered', serverName })
+}
diff --git a/control-api/src/oauth/remoteCallback.ts b/control-api/src/oauth/remoteCallback.ts
index 696ea3803..ce7eb3f40 100644
--- a/control-api/src/oauth/remoteCallback.ts
+++ b/control-api/src/oauth/remoteCallback.ts
@@ -61,7 +61,7 @@ export function isValidInstallNonce(value: unknown): value is string {
// A per-server URI is compared byte-for-byte by the AS and replayed on the token
// exchange, so its origin must already be in canonical form: no path, trailing slash,
// query, fragment or userinfo, and no spelling `new URL` would normalize differently.
-function isBareOrigin(origin: unknown): origin is string {
+export function isBareOrigin(origin: unknown): origin is string {
if (typeof origin !== 'string' || origin.length === 0) return false
try {
return new URL(origin).origin === origin
diff --git a/control-api/src/routes/admin/remoteMcp.ts b/control-api/src/routes/admin/remoteMcp.ts
index 92ad25acb..eaef8d8d8 100644
--- a/control-api/src/routes/admin/remoteMcp.ts
+++ b/control-api/src/routes/admin/remoteMcp.ts
@@ -363,7 +363,10 @@ function previewRemoteCallback(discovery: DiscoveryResult): RemoteCallbackPrevie
}
}
-/** Hostnames of the AS endpoints an install would trust (shown before a per-server install). */
+/**
+ * Hosts (with any non-default port) of the AS endpoints an install would trust, shown
+ * before a per-server install so a different port is not hidden from the operator.
+ */
function asEndpointHostsOf(discovery: DiscoveryResult): {
authorization: string
token: string
@@ -371,9 +374,9 @@ function asEndpointHostsOf(discovery: DiscoveryResult): {
} {
const { authorization, token, registration } = discovery.endpoints
return {
- authorization: new URL(authorization).hostname,
- token: new URL(token).hostname,
- ...(registration ? { registration: new URL(registration).hostname } : {}),
+ authorization: new URL(authorization).host,
+ token: new URL(token).host,
+ ...(registration ? { registration: new URL(registration).host } : {}),
}
}
diff --git a/control-api/src/routes/external/oauthCallback.ts b/control-api/src/routes/external/oauthCallback.ts
index af0281fb7..5b33957a3 100644
--- a/control-api/src/routes/external/oauthCallback.ts
+++ b/control-api/src/routes/external/oauthCallback.ts
@@ -1,10 +1,12 @@
-import { Router } from 'express'
+import { type NextFunction, type Request, type Response, Router } from 'express'
import { config } from '../../config.js'
import { pool } from '../../db.js'
import { K8sGateway } from '../../k8s.js'
import {
+ type CallbackTarget,
type McpServerOAuthReader,
type McpServerOAuthSubject,
+ REMOTE_CALLBACK_CLIENT_SEGMENT,
RecipeNotFoundError,
type RecipeReader,
type RecipeWithOAuthClients,
@@ -18,6 +20,7 @@ import {
type McpServerOAuthSpecInput,
resolveServerOAuthSubject,
} from '../../oauth/mcpServerOAuthSpec.js'
+import { isValidInstallNonce, isValidRemoteServerNameSegment } from '../../oauth/remoteCallback.js'
import { getUserContexts } from '../../services/directory/index.js'
import { K8sNotFoundError } from '../../services/resourceService.js'
@@ -97,29 +100,26 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {
},
}
- // Stable callback path: only the oauthClientId rides the URL (one registered
- // redirect URI per provider client). The recipe (namespace, name) is recovered
- // from the signed state inside handleOAuthCallback, so the URI no longer churns
- // per recipe instance / catalog version. No namespace check is needed here: the
- // recipe namespace comes from the unforgeable state, and both authorize-url
- // minters only sign sandbox-namespace states.
- router.get('/oauth-callback/:oauthClientId', async (req, res, next) => {
+ async function completeCallback(
+ req: Request,
+ res: Response,
+ next: NextFunction,
+ target: CallbackTarget
+ ): Promise<unknown> {
try {
- const { oauthClientId } = req.params
const code = typeof req.query.code === 'string' ? req.query.code : ''
const state = typeof req.query.state === 'string' ? req.query.state : ''
- // RFC 9207 issuer — validated on the remote lane against the pinned
- // `issForCallback` inside handleOAuthCallback (AS mix-up defence).
- const iss = typeof req.query.iss === 'string' ? req.query.iss : undefined
-
if (!code || !state) {
return res.status(400).json({ error: 'missing_code_or_state' })
}
-
- const redirectUri = buildPublicCallbackUrl(req, oauthClientId, config.oauthCallbackBaseUrl)
+ // The desktop deep link and the not-configured body name the integration by the
+ // URL's client id; the remote callbacks have none, so both variants report the
+ // reserved `remote` (the desktop routes remote consents by `mcpServerName`).
+ const integrationId = target.kind === 'client' ? target.id : REMOTE_CALLBACK_CLIENT_SEGMENT
const result = await handleOAuthCallback(
- { oauthClientId, code, state, redirectUri, iss },
+ // `iss` goes through raw: each remote variant decides how a malformed value reads.
+ { target, code, state, iss: req.query.iss },
{
db: { query: (text, values) => pool.query(text, values) },
recipeReader,
@@ -140,10 +140,11 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {
.status(200)
.type('html')
.send(
- renderSuccessHtml(result.provider, oauthClientId, {
+ renderSuccessHtml(result.provider, integrationId, {
backgroundRequested: result.backgroundRequested,
backgroundEnabled: result.backgroundEnabled,
source: result.source,
+ // From the signed state, never from the URL segment.
mcpServerName: result.mcpServerName,
})
)
@@ -158,6 +159,8 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {
// issuer at install, so the shared remote callback cannot attribute the
// code. Fail closed — same 400 class, distinct error for operator triage.
return res.status(400).json({ error: 'issuer_binding_required' })
+ case 'callback_base_url_unconfigured':
+ return res.status(503).json({ error: 'callback_base_url_unconfigured' })
case 'unknown_oauth_client':
return res.status(400).json({ error: 'unknown_oauth_client' })
case 'recipe_not_found':
@@ -173,7 +176,7 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {
.status(409)
.json({ error: 'remote_oauth_spec_incoherent', reason: result.reason })
case 'secret_missing':
- return res.status(503).json(integrationNotConfigured(oauthClientId, result.secret))
+ return res.status(503).json(integrationNotConfigured(integrationId, result.secret))
case 'unsupported_provider':
return res.status(500).json({ error: 'unsupported_provider', provider: result.provider })
case 'provider_token_exchange_failed':
@@ -186,6 +189,55 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {
} catch (err) {
next(err)
}
+ }
+
+ // Per-server remote callback, for an AS that does not return RFC 9207 `iss`: the URI
+ // itself binds the code to one server (and, for DCR, one installation). Public like
+ // its sibling — authentication is the signed state plus that binding. The segments
+ // are re-validated here with the same rules the public gateway applies: this route is
+ // also reachable without the gateway, and an unvalidated segment must never reach
+ // the handler.
+ router.get('/oauth-callback/remote/:serverName/:installNonce?', (req, res, next) => {
+ const { serverName, installNonce } = req.params as {
+ serverName: string
+ installNonce?: string
+ }
+ if (
+ !isValidRemoteServerNameSegment(serverName) ||
+ (installNonce !== undefined && !isValidInstallNonce(installNonce))
+ ) {
+ res.status(404).json({ error: 'Not Found' })
+ return
+ }
+ void completeCallback(req, res, next, {
+ kind: 'remote-per-server',
+ serverName,
+ installNonce,
+ // Configured origin only: a per-server URI anchored on the request Host would
+ // differ from the one registered at the AS whenever the Host differs.
+ origin: normalizeConfiguredOrigin(config.oauthCallbackBaseUrl),
+ })
+ })
+
+ // `/oauth-callback/<oauthClientId>`: one registered redirect URI per provider client,
+ // stable across recipe versions — the recipe (namespace, name) is recovered from the
+ // signed state, and both authorize-url minters only sign sandbox-namespace states.
+ // The reserved `remote` segment is the shared callback of every remote server whose
+ // AS returns RFC 9207 `iss`.
+ router.get('/oauth-callback/:oauthClientId', (req, res, next) => {
+ const { oauthClientId } = req.params
+ const target: CallbackTarget =
+ oauthClientId === REMOTE_CALLBACK_CLIENT_SEGMENT
+ ? {
+ kind: 'remote-shared',
+ origin: resolveCallbackOrigin(req, config.oauthCallbackBaseUrl),
+ }
+ : {
+ kind: 'client',
+ id: oauthClientId,
+ redirectUri: buildPublicCallbackUrl(req, oauthClientId, config.oauthCallbackBaseUrl),
+ }
+ void completeCallback(req, res, next, target)
})
return router
@@ -205,6 +257,20 @@ export function normalizeConfiguredOrigin(configuredBaseUrl?: string): string |
return configuredBaseUrl.replace(/\/+$/, '')
}
+/**
+ * Origin of the callback URLs that tolerate an unconfigured base URL (the per-client
+ * and shared remote callbacks): the configured public base URL, else the request Host.
+ */
+export function resolveCallbackOrigin(
+ req: { protocol: string; get: (h: string) => string | undefined },
+ configuredBaseUrl?: string
+): string {
+ return (
+ normalizeConfiguredOrigin(configuredBaseUrl) ??
+ `${req.protocol}://${req.get('host') ?? 'localhost'}`
+ )
+}
+
export function buildPublicCallbackUrl(
req: { protocol: string; get: (h: string) => string | undefined },
oauthClientId: string,
@@ -220,9 +286,7 @@ export function buildPublicCallbackUrl(
// request Host is an internal hostname, so prefer an explicitly configured
// public base URL (CONTROL_API_OAUTH_CALLBACK_BASE_URL). Fall back to the
// request Host for local/dev where none is set.
- const origin =
- normalizeConfiguredOrigin(configuredBaseUrl) ??
- `${req.protocol}://${req.get('host') ?? 'localhost'}`
+ const origin = resolveCallbackOrigin(req, configuredBaseUrl)
return `${origin}/api/v1/oauth-callback/${encodeURIComponent(oauthClientId)}`
}
diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.ts
index 85beecb33..f6a91c959 100644
--- a/control-api/src/routes/internal/oauth.ts
+++ b/control-api/src/routes/internal/oauth.ts
@@ -1,4 +1,4 @@
-import { Router } from 'express'
+import { type Request, Router } from 'express'
import { config } from '../../config.js'
import { pool } from '../../db.js'
import { K8sGateway } from '../../k8s.js'
@@ -8,7 +8,6 @@ import { buildAuthorizeUrl } from '../../oauth/authorizeUrlHelper.js'
import {
type McpServerOAuthReader,
type McpServerOAuthSubject,
- REMOTE_CALLBACK_CLIENT_SEGMENT,
RecipeNotFoundError,
type RecipeReader,
type RecipeWithOAuthClients,
@@ -16,23 +15,45 @@ import {
type SecretReader,
} from '../../oauth/callback.js'
import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'
-import { integrationNotConfigured, isSecretNotFound } from '../../oauth/integrationNotConfigured.js'
+import {
+ type IntegrationNotConfiguredBody,
+ integrationNotConfigured,
+ isSecretNotFound,
+} from '../../oauth/integrationNotConfigured.js'
import {
type McpServerOAuthSpecInput,
RemoteOAuthSpecIncoherentError,
+ type ResolvedServerOAuthSubject,
buildMcpServerGrantKey,
resolveServerOAuth,
resolveServerOAuthSubject,
} from '../../oauth/mcpServerOAuthSpec.js'
+import {
+ buildPerServerRedirectUri,
+ resolvePerServerRegistration,
+} from '../../oauth/perServerRegistration.js'
import { getAccessTokenReactive } from '../../oauth/reactiveTokenHelper.js'
+import {
+ buildRemoteRedirectUri,
+ isBareOrigin,
+ isValidRemoteServerNameSegment,
+ remoteCallbackVariant,
+} from '../../oauth/remoteCallback.js'
import { deleteOAuthGrant } from '../../oauth/store.js'
import { getUserContexts } from '../../services/directory/index.js'
import { K8sNotFoundError } from '../../services/resourceService.js'
-import { buildPublicCallbackUrl } from '../external/oauthCallback.js'
+import {
+ buildPublicCallbackUrl,
+ normalizeConfiguredOrigin,
+ resolveCallbackOrigin,
+} from '../external/oauthCallback.js'
// DNS-1123 subdomain — the shape a k8s resource name takes. Reject anything else
// up front so a malformed `mcpServerName` becomes a 400 rather than surfacing a
-// non-404 apiserver error as a 500. (Mirrors routes/mcpOauth.ts.)
+// non-404 apiserver error as a 500. (Mirrors routes/mcpOauth.ts.) Deliberately wider
+// than the per-server callback segment (an RFC 1123 label): these routes serve every
+// OAuth lane, and only a per-server remote server needs its name to fit in a URL
+// segment — that narrower rule is applied where its redirect URI is built.
const K8S_NAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/
function isValidK8sName(name: string): boolean {
return name.length > 0 && name.length <= 253 && K8S_NAME_RE.test(name)
@@ -140,6 +161,76 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
},
}
+ /**
+ * The redirect URI an mcp-server's authorize URL carries — the one its client
+ * registered at the AS, which the callback replays on the token exchange:
+ * - baked/generic: `/oauth-callback/<oauthClientId>`;
+ * - remote, shared (AS returns RFC 9207 `iss`): `/oauth-callback/remote`;
+ * - remote, per-server: `/oauth-callback/remote/<name>[/<installNonce>]`, the nonce
+ * read from the `dynamic_clients` row bound to this CR.
+ * Per-server fails closed without a configured bare origin: the AS compares the URI
+ * byte-for-byte, and a request-Host fallback would depend on how the caller reached
+ * us. Minting for a server whose callback would reject the code is refused here
+ * rather than after the user has consented.
+ */
+ async function mintRedirectUri(
+ req: Request,
+ subject: ResolvedServerOAuthSubject,
+ mcpServerName: string
+ ): Promise<{ ok: true; redirectUri: string } | { ok: false; status: number; body: object }> {
+ const remote = subject.decl.remote
+ if (!remote) {
+ return {
+ ok: true,
+ redirectUri: buildPublicCallbackUrl(req, subject.decl.id, config.oauthCallbackBaseUrl),
+ }
+ }
+ if (remoteCallbackVariant(remote) === 'shared') {
+ return {
+ ok: true,
+ redirectUri: buildRemoteRedirectUri({
+ origin: resolveCallbackOrigin(req, config.oauthCallbackBaseUrl),
+ variant: 'shared',
+ }),
+ }
+ }
+ // Only a CR written outside the install can carry a name that is not a label; its
+ // callback route would never match, so there is no URI to mint.
+ if (!isValidRemoteServerNameSegment(mcpServerName)) {
+ return { ok: false, status: 400, body: { error: 'invalid_request' } }
+ }
+ const origin = normalizeConfiguredOrigin(config.oauthCallbackBaseUrl)
+ if (origin === null || !isBareOrigin(origin)) {
+ req.log?.error(
+ { event: 'remote_oauth_per_server_callback_unconfigured', mcpServerName },
+ 'per-server remote consent requires a configured public callback base URL (bare origin)'
+ )
+ return { ok: false, status: 503, body: { error: 'callback_base_url_unconfigured' } }
+ }
+ const registration = await resolvePerServerRegistration(
+ { query: (text, values) => pool.query(text, values) },
+ { namespace: config.mcpServersNamespace, decl: subject.decl, crUid: subject.crUid },
+ mcpServerName
+ )
+ if (!registration) {
+ // Same contract as any other missing client credential, but there is no Secret to
+ // create: the DCR client is only (re)registered by installing the server again.
+ return {
+ ok: false,
+ status: 503,
+ body: {
+ error: 'integration_not_configured',
+ integration: subject.decl.id,
+ hint: `reinstall the remote MCP server ${mcpServerName} to register its OAuth client again`,
+ } satisfies IntegrationNotConfiguredBody,
+ }
+ }
+ return {
+ ok: true,
+ redirectUri: buildPerServerRedirectUri(origin, mcpServerName, registration),
+ }
+ }
+
// ── U5: mint a fresh authorize-URL for an OAuth mcp-server, on click ──────
//
// rpc-proxy fronts this from the desktop "Connect <server>" surface. The
@@ -246,18 +337,9 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
if (!resolved) return res.status(400).json({ error: 'not_oauth_server' })
const oauthClientId = resolved.decl.id
- // Remote lane registers ONE stable redirect_uri (`/oauth-callback/remote`),
- // so the callback URL segment is the reserved constant, NOT the client id —
- // the real binding rides the signed state. Baked keeps the per-client
- // segment. The exchange re-derives the same redirect_uri from this segment.
- const callbackSegment = resolved.decl.remote
- ? REMOTE_CALLBACK_CLIENT_SEGMENT
- : oauthClientId
- const redirectUri = buildPublicCallbackUrl(
- req,
- callbackSegment,
- config.oauthCallbackBaseUrl
- )
+ const redirect = await mintRedirectUri(req, resolved, mcpServerName)
+ if (!redirect.ok) return res.status(redirect.status).json(redirect.body)
+ const redirectUri = redirect.redirectUri
const result = await buildAuthorizeUrl(
{
diff --git a/control-api/test/fixtures/legacyOAuthGrant.ts b/control-api/test/fixtures/legacyOAuthGrant.ts
index 9416c2a70..4ed516d5d 100644
--- a/control-api/test/fixtures/legacyOAuthGrant.ts
+++ b/control-api/test/fixtures/legacyOAuthGrant.ts
@@ -19,7 +19,11 @@ import { vi } from 'vitest'
import { config } from '../../src/config.js'
import type { DbClient } from '../../src/db.js'
import type { PinnedTransport } from '../../src/http/pinnedFetch.js'
-import { type McpServerOAuthSubject, handleOAuthCallback } from '../../src/oauth/callback.js'
+import {
+ type CallbackTarget,
+ type McpServerOAuthSubject,
+ handleOAuthCallback,
+} from '../../src/oauth/callback.js'
import { type DiscoveryResult, discoverRemoteOAuth } from '../../src/oauth/discovery.js'
import {
type McpServerOAuthSpecInput,
@@ -164,9 +168,13 @@ function tokenResponse(tokens: ConsentTokens) {
}
}
-function consentInput(name: string, userId: string) {
+function consentInput(name: string, userId: string, target?: CallbackTarget) {
return {
- oauthClientId: OAUTH_ID,
+ target: target ?? {
+ kind: 'client' as const,
+ id: OAUTH_ID,
+ redirectUri: `https://control.example.com/api/v1/oauth-callback/${OAUTH_ID}`,
+ },
code: `code-${name}-${userId}`,
state: signOAuthState(STATE_SECRET, {
subjectKind: 'mcp',
@@ -176,7 +184,6 @@ function consentInput(name: string, userId: string) {
grantKind: 'user',
background: false,
}),
- redirectUri: `https://control.example.com/api/v1/oauth-callback/${OAUTH_ID}`,
}
}
@@ -239,8 +246,15 @@ export async function currentConsent(
/** RFC 9207 `iss` of the authorization response; the remote lane requires it. */
iss?: string
): Promise<void> {
+ // Each lane's own callback URL, as its authorize URL registers it: a remote server
+ // always consents on a remote URI (the shared one here, as `iss` is supplied).
+ const cr = (await gateway.getResource('mcpservers', name, NS)) as ServerCR
+ const target: CallbackTarget | undefined =
+ (cr.spec as { oauth?: { source?: unknown } }).oauth?.source === 'remote'
+ ? { kind: 'remote-shared', origin: 'https://control.example.com' }
+ : undefined
const result = await handleOAuthCallback(
- { ...consentInput(name, userId), iss },
+ { ...consentInput(name, userId, target), iss },
{
db,
recipeReader: { read: async () => null },
diff --git a/control-api/test/fixtures/perServerInstall.ts b/control-api/test/fixtures/perServerInstall.ts
new file mode 100644
index 000000000..abb76cc48
--- /dev/null
+++ b/control-api/test/fixtures/perServerInstall.ts
@@ -0,0 +1,108 @@
+/**
+ * Remote MCP servers installed through the REAL admin install route, for the consent
+ * (authorize-url + callback) suites of the per-server callback variant.
+ *
+ * Everything the consent path reads is produced by its real producer (T1): discovery
+ * by `discoverRemoteOAuth` over the probe fixtures, the CR and its `metadata.uid` by
+ * the install saga on a `MockGateway`, the `dynamic_clients` row — install nonce and
+ * `cr_uid` binding included — by the saga's own store calls on whatever `DbClient` the
+ * suite passes (the in-memory harness or a real Postgres). The RFC 7591 registration
+ * response is the only external fixture (a live DCR POST would create a client at a
+ * third party); the AS echoes the `redirect_uris` actually POSTed.
+ */
+import express from 'express'
+import request from 'supertest'
+import type { DbClient } from '../../src/db.js'
+import type { PinnedTransport } from '../../src/http/pinnedFetch.js'
+import type { K8sGateway } from '../../src/k8s.js'
+import { type DiscoveryResult, discoverRemoteOAuth } from '../../src/oauth/discovery.js'
+import { probeMcpTransport } from '../../src/oauth/mcpTransportProbe.js'
+import { createAdminRemoteMcpRouter } from '../../src/routes/admin/remoteMcp.js'
+import type { MockGateway } from '../mockGateway.js'
+import {
+ DCR_PUBLIC_REGISTRATION_RESPONSE,
+ type RecordedDcrCall,
+ makeDcrTransport,
+ makeDiscoveryTransport,
+} from './remoteOAuthDiscovery.js'
+
+export const PUBLIC_IP = '93.184.216.34'
+const resolvePublic = async () => [PUBLIC_IP]
+
+/** Run the real discovery client over a probe fixture. */
+export async function discoverPilot(
+ pilot: Parameters<typeof makeDiscoveryTransport>[0]
+): Promise<DiscoveryResult> {
+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, {
+ transport: makeDiscoveryTransport(pilot),
+ resolveDns: resolvePublic,
+ })
+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)
+ return outcome.result
+}
+
+/** Documented T1 substitution: add RFC 9207 to a pilot's AS metadata. */
+export function withRfc9207<T extends { as: { json: string } }>(pilot: T): T {
+ const as = JSON.parse(pilot.as.json)
+ as.authorization_response_iss_parameter_supported = true
+ return { ...pilot, as: { ...pilot.as, json: JSON.stringify(as) } }
+}
+
+// A tokenless POST `initialize` answered with a Bearer challenge: transport alive.
+const ALIVE_TRANSPORT: PinnedTransport = async ({ method }) =>
+ method === 'POST'
+ ? { status: 401, headers: { 'www-authenticate': 'Bearer realm="OAuth"' }, bodyText: '' }
+ : { status: 404, headers: {}, bodyText: '' }
+
+const aliveProbe: typeof probeMcpTransport = (baseUrl, deps, opts) =>
+ probeMcpTransport(
+ baseUrl,
+ { ...deps, transport: ALIVE_TRANSPORT, resolveDns: resolvePublic },
+ opts
+ )
+
+export interface InstallOutcome {
+ status: number
+ body: Record<string, unknown>
+ /** Every call the DCR transport received (empty for a pre-registered install). */
+ dcrCalls: RecordedDcrCall[]
+}
+
+/** Seed the Context the install attaches the server to. */
+export async function seedContext(gateway: MockGateway, namespace: string, name: string) {
+ await gateway.createResource(
+ 'contexts',
+ { metadata: { name }, spec: { contextId: name } },
+ namespace
+ )
+}
+
+/**
+ * POST /admin/mcp-servers/remote through the real router. `discovery` is what the
+ * install's server-side discovery resolves; for DCR the AS assigns `registration`.
+ */
+export async function installRemoteServer(opts: {
+ gateway: MockGateway
+ db: DbClient
+ discovery: DiscoveryResult
+ body: Record<string, unknown>
+ registration?: Record<string, unknown>
+}): Promise<InstallOutcome> {
+ const { transport, calls } = makeDcrTransport({
+ registrationEndpoint: opts.discovery.endpoints.registration,
+ responseJson: JSON.stringify(opts.registration ?? DCR_PUBLIC_REGISTRATION_RESPONSE),
+ redirectUris: 'requested',
+ })
+ const app = express()
+ app.use(express.json())
+ app.use(
+ createAdminRemoteMcpRouter(opts.gateway as unknown as K8sGateway, {
+ db: opts.db,
+ discover: async () => ({ ok: true, result: opts.discovery }),
+ probe: aliveProbe,
+ dcr: { transport, resolveDns: resolvePublic },
+ })
+ )
+ const res = await request(app).post('/admin/mcp-servers/remote').send(opts.body)
+ return { status: res.status, body: res.body as Record<string, unknown>, dcrCalls: calls }
+}
diff --git a/control-api/test/oauth.callback.background.test.ts b/control-api/test/oauth.callback.background.test.ts
index 57232299b..e4b3e8687 100644
--- a/control-api/test/oauth.callback.background.test.ts
+++ b/control-api/test/oauth.callback.background.test.ts
@@ -1,16 +1,21 @@
-import { describe, it, expect, vi } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import { handleOAuthCallback } from '../src/oauth/callback.js'
-import { renderSuccessHtml } from '../src/routes/external/oauthCallback.js'
import { signOAuthState } from '../src/oauth/state.js'
import * as store from '../src/oauth/store.js'
+import { renderSuccessHtml } from '../src/routes/external/oauthCallback.js'
const SECRET = 'x'.repeat(40)
const recipe = {
- spec: { oauthClients: [
- { id: 'google-gmail', provider: 'google',
- clientIdRef: { name: 's', key: 'client-id' },
- clientSecretRef: { name: 's', key: 'client-secret' } },
- ] },
+ spec: {
+ oauthClients: [
+ {
+ id: 'google-gmail',
+ provider: 'google',
+ clientIdRef: { name: 's', key: 'client-id' },
+ clientSecretRef: { name: 's', key: 'client-secret' },
+ },
+ ],
+ },
}
function deps(tokenJson: object) {
return {
@@ -23,11 +28,15 @@ function deps(tokenJson: object) {
}
}
const input = (background: boolean) => ({
- oauthClientId: 'google-gmail',
- code: 'code', redirectUri: 'https://api/cb',
+ target: { kind: 'client' as const, id: 'google-gmail', redirectUri: 'https://api/cb' },
+ code: 'code',
state: signOAuthState(SECRET, {
- recipeNamespace: 'sandbox-recipes', recipeName: 'leadforge', userId: 'user-1',
- oauthClientId: 'google-gmail', grantKind: 'user', background,
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'leadforge',
+ userId: 'user-1',
+ oauthClientId: 'google-gmail',
+ grantKind: 'user',
+ background,
}),
})
@@ -35,14 +44,20 @@ describe('handleOAuthCallback background', () => {
it('sets background=true when consented AND a refresh token is returned', async () => {
const spy = vi.spyOn(store, 'setUserGrantBackground').mockResolvedValue()
vi.spyOn(store, 'upsertOAuthGrant').mockResolvedValue()
- const res = await handleOAuthCallback(input(true), deps({ access_token: 'a', refresh_token: 'r', expires_in: 3600 }))
+ const res = await handleOAuthCallback(
+ input(true),
+ deps({ access_token: 'a', refresh_token: 'r', expires_in: 3600 })
+ )
expect(res.kind).toBe('ok')
if (res.kind === 'ok') {
expect(res.backgroundRequested).toBe(true)
expect(res.backgroundEnabled).toBe(true)
}
- expect(spy).toHaveBeenCalledWith(expect.anything(),
- expect.objectContaining({ userId: 'user-1', oauthClientId: 'google-gmail' }), true)
+ expect(spy).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ userId: 'user-1', oauthClientId: 'google-gmail' }),
+ true
+ )
spy.mockRestore()
})
@@ -62,7 +77,10 @@ describe('handleOAuthCallback background', () => {
it('never sets background for a non-background (plain) connect', async () => {
const spy = vi.spyOn(store, 'setUserGrantBackground').mockResolvedValue()
vi.spyOn(store, 'upsertOAuthGrant').mockResolvedValue()
- const res = await handleOAuthCallback(input(false), deps({ access_token: 'a', refresh_token: 'r' }))
+ const res = await handleOAuthCallback(
+ input(false),
+ deps({ access_token: 'a', refresh_token: 'r' })
+ )
expect(res.kind).toBe('ok')
if (res.kind === 'ok') {
expect(res.backgroundRequested).toBe(false)
diff --git a/control-api/test/oauth.callback.generic.test.ts b/control-api/test/oauth.callback.generic.test.ts
index 91ed78b07..e36f438d2 100644
--- a/control-api/test/oauth.callback.generic.test.ts
+++ b/control-api/test/oauth.callback.generic.test.ts
@@ -94,7 +94,11 @@ function recordingTransport(responseJson: string, status = 200) {
function genericInput(): CallbackInput {
return {
- oauthClientId: CLIENT_ID,
+ target: {
+ kind: 'client',
+ id: CLIENT_ID,
+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/my-generic-client',
+ },
code: 'AUTH_CODE',
state: signOAuthState(STATE_SECRET, {
subjectKind: 'mcp',
@@ -104,7 +108,6 @@ function genericInput(): CallbackInput {
grantKind: 'user',
background: false,
} as Parameters<typeof signOAuthState>[1]),
- redirectUri: 'https://control.example.com/api/v1/oauth-callback/my-generic-client',
}
}
diff --git a/control-api/test/oauth.callback.mcp.test.ts b/control-api/test/oauth.callback.mcp.test.ts
index b42403db5..59121351b 100644
--- a/control-api/test/oauth.callback.mcp.test.ts
+++ b/control-api/test/oauth.callback.mcp.test.ts
@@ -40,10 +40,9 @@ function mcpState(overrides: Partial<Parameters<typeof signOAuthState>[1]> = {})
function buildInput(overrides: Partial<CallbackInput> = {}): CallbackInput {
return {
- oauthClientId: 'google-drive',
+ target: { kind: 'client', id: 'google-drive', redirectUri: REDIRECT_URI },
code: 'AUTH_CODE',
state: mcpState(),
- redirectUri: REDIRECT_URI,
...overrides,
}
}
@@ -241,7 +240,10 @@ describe('handleOAuthCallback — mcp subject (U5)', () => {
it('rejects when the callback-path oauthClientId disagrees with the signed state', async () => {
const { deps } = buildDeps({ subject: gdriveSubject() })
- const result = await handleOAuthCallback(buildInput({ oauthClientId: 'other' }), deps)
+ const result = await handleOAuthCallback(
+ buildInput({ target: { kind: 'client', id: 'other', redirectUri: REDIRECT_URI } }),
+ deps
+ )
expect(result.kind).toBe('invalid_state')
})
diff --git a/control-api/test/oauth.callback.publicClient.test.ts b/control-api/test/oauth.callback.publicClient.test.ts
index 9f4262e03..94b2da42e 100644
--- a/control-api/test/oauth.callback.publicClient.test.ts
+++ b/control-api/test/oauth.callback.publicClient.test.ts
@@ -87,7 +87,11 @@ it('public client: exchanges without reading or sending a client_secret', async
})
const result = await handleOAuthCallback(
- { oauthClientId: 'salesforce', code: 'AUTH_CODE', state, redirectUri: REDIRECT_URI },
+ {
+ target: { kind: 'client', id: 'salesforce', redirectUri: REDIRECT_URI },
+ code: 'AUTH_CODE',
+ state,
+ },
deps
)
@@ -152,7 +156,11 @@ describe('confidential client (control) still reads + sends client_secret', () =
background: false,
})
const result = await handleOAuthCallback(
- { oauthClientId: 'salesforce', code: 'AUTH_CODE', state, redirectUri: REDIRECT_URI },
+ {
+ target: { kind: 'client', id: 'salesforce', redirectUri: REDIRECT_URI },
+ code: 'AUTH_CODE',
+ state,
+ },
deps
)
expect(result.kind).toBe('ok')
diff --git a/control-api/test/oauth.callback.remote.test.ts b/control-api/test/oauth.callback.remote.test.ts
index ed5f5b49c..56e5d3d4f 100644
--- a/control-api/test/oauth.callback.remote.test.ts
+++ b/control-api/test/oauth.callback.remote.test.ts
@@ -122,10 +122,9 @@ function remoteState() {
function remoteInput(): CallbackInput {
return {
- oauthClientId: 'remote', // stable segment, not the client id
+ target: { kind: 'remote-shared', origin: 'https://control.example.com' },
code: 'AUTH_CODE',
state: remoteState(),
- redirectUri: 'https://control.example.com/api/v1/oauth-callback/remote',
// RFC 9207 issuer echoed by the authorization response; matches the pinned
// `issForCallback` so the mix-up defence passes and the exchange proceeds.
iss: 'https://mcp.sentry.dev',
@@ -226,7 +225,11 @@ describe('baked mcp exchange stays on fetchFn (byte-identical, T5c)', () => {
}
const input: CallbackInput = {
- oauthClientId: 'google-drive',
+ target: {
+ kind: 'client',
+ id: 'google-drive',
+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/google-drive',
+ },
code: 'AUTH_CODE',
state: signOAuthState(STATE_SECRET, {
subjectKind: 'mcp',
@@ -236,7 +239,6 @@ describe('baked mcp exchange stays on fetchFn (byte-identical, T5c)', () => {
grantKind: 'user',
background: false,
} as Parameters<typeof signOAuthState>[1]),
- redirectUri: 'https://control.example.com/api/v1/oauth-callback/google-drive',
}
const result = await handleOAuthCallback(input, deps)
diff --git a/control-api/test/oauth.callback.reservedRemoteSegment.test.ts b/control-api/test/oauth.callback.reservedRemoteSegment.test.ts
index 3d63f223b..fcc132554 100644
--- a/control-api/test/oauth.callback.reservedRemoteSegment.test.ts
+++ b/control-api/test/oauth.callback.reservedRemoteSegment.test.ts
@@ -258,10 +258,17 @@ async function deliverState(lane: Lane, serverName: string, segment: string) {
const result = await handleOAuthCallback(
{
- oauthClientId: segment,
+ // The route maps the reserved segment to the shared remote callback.
+ target:
+ segment === REMOTE_CALLBACK_CLIENT_SEGMENT
+ ? { kind: 'remote-shared', origin: 'https://control.example.com' }
+ : {
+ kind: 'client',
+ id: segment,
+ redirectUri: `https://control.example.com/api/v1/oauth-callback/${segment}`,
+ },
code: 'AUTH_CODE',
state,
- redirectUri: `https://control.example.com/api/v1/oauth-callback/${segment}`,
},
deps
)
@@ -385,7 +392,11 @@ describe('handleOAuthCallback — recipe clients are outside the reservation (RP
)
const db = { query: vi.fn().mockResolvedValue({ rows: [], rowCount: 1 }) }
const result = await handleOAuthCallback(
- { oauthClientId: REMOTE_CALLBACK_CLIENT_SEGMENT, code: 'AUTH_CODE', state, redirectUri },
+ {
+ target: { kind: 'remote-shared', origin: 'https://control.example.com' },
+ code: 'AUTH_CODE',
+ state,
+ },
{
db: db as unknown as CallbackDeps['db'],
recipeReader,
@@ -398,6 +409,9 @@ describe('handleOAuthCallback — recipe clients are outside the reservation (RP
expect(result.kind).toBe('ok')
expect(fetchFn).toHaveBeenCalledTimes(1)
+ // The recipe exchange replays the exact URI its authorize URL carried.
+ const tokenInit = (fetchFn.mock.calls[0] as unknown as [string, RequestInit])[1]
+ expect(new URLSearchParams(String(tokenInit.body)).get('redirect_uri')).toBe(redirectUri)
expect(String(db.query.mock.calls[0]?.[0])).toContain('INSERT INTO oauth_grants')
})
})
diff --git a/control-api/test/oauth.callback.test.ts b/control-api/test/oauth.callback.test.ts
index ab96fe424..2e3679ab0 100644
--- a/control-api/test/oauth.callback.test.ts
+++ b/control-api/test/oauth.callback.test.ts
@@ -24,7 +24,7 @@ function buildInput(
grantKind: 'user' | 'service' = 'user'
): CallbackInput {
return {
- oauthClientId: 'salesforce',
+ target: { kind: 'client', id: 'salesforce', redirectUri: REDIRECT_URI },
code: 'AUTH_CODE_FROM_PROVIDER',
state: signOAuthState(STATE_SECRET, {
recipeNamespace: 'sandbox-recipes',
@@ -34,7 +34,6 @@ function buildInput(
grantKind,
background: false,
}),
- redirectUri: REDIRECT_URI,
...overrides,
}
}
@@ -206,7 +205,12 @@ describe('handleOAuthCallback (O4.1)', () => {
it('rejects when the path oauthClientId does not match the signed state', async () => {
const { deps } = buildDeps({ recipe: recipeWithSalesforce() })
// State signed for salesforce; the callback path claims a different client.
- const result = await handleOAuthCallback(buildInput({ oauthClientId: 'attacker-client' }), deps)
+ const result = await handleOAuthCallback(
+ buildInput({
+ target: { kind: 'client', id: 'attacker-client', redirectUri: REDIRECT_URI },
+ }),
+ deps
+ )
expect(result.kind).toBe('invalid_state')
})
diff --git a/control-api/test/oauth.callbackRemotePerServer.test.ts b/control-api/test/oauth.callbackRemotePerServer.test.ts
new file mode 100644
index 000000000..0561c36c7
--- /dev/null
+++ b/control-api/test/oauth.callbackRemotePerServer.test.ts
@@ -0,0 +1,450 @@
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { randomUUID } from 'node:crypto'
+import { config } from '../src/config.js'
+import type { PinnedRawResponse, PinnedTransportInput } from '../src/http/pinnedFetch.js'
+import {
+ type CallbackDeps,
+ type CallbackTarget,
+ type McpServerOAuthSubject,
+ handleOAuthCallback,
+} from '../src/oauth/callback.js'
+import type { DiscoveryResult } from '../src/oauth/discovery.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import {
+ type McpServerOAuthSpecInput,
+ resolveServerOAuthSubject,
+} from '../src/oauth/mcpServerOAuthSpec.js'
+import { signOAuthState } from '../src/oauth/state.js'
+import {
+ discoverPilot,
+ installRemoteServer,
+ seedContext,
+ withRfc9207,
+} from './fixtures/perServerInstall.js'
+import {
+ ATLASSIAN_V2_PILOT,
+ PILOTS,
+ dcrPilot,
+ makeInMemoryDynamicClientsDb,
+} from './fixtures/remoteOAuthDiscovery.js'
+import { MockGateway } from './mockGateway.js'
+
+/**
+ * Callback of the per-server remote variant (`/oauth-callback/remote/<serverName>
+ * [/<installNonce>]`), used when the AS does not return RFC 9207 `iss`. There the
+ * redirect URI is the mix-up defence, so the handler must:
+ * - refuse a code delivered to one server's URI with another server's state BEFORE
+ * reading any CR or exchanging the code;
+ * - accept only the URI this installation registered (DCR: the nonce of the row bound
+ * to this CR; pre-registered: no nonce), and only for a per-server CR;
+ * - validate an `iss` the AS sends anyway, rejecting a malformed one;
+ * - replay on the token exchange the URI rebuilt from the signed state and the CR.
+ *
+ * T1: servers are installed through the real admin install route (CR, uid, row and
+ * nonce from the saga); discovery by the real client over probe fixtures; the state by
+ * the real signer. The AS token endpoint is the only network edge, recorded here.
+ */
+
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn(async () => [{ address: '93.184.216.34', family: 4 }]),
+}))
+
+// Capture what the callback logs when it rejects an `iss`, to pin that no request data
+// (code, state, the query) reaches the log.
+const logged = vi.hoisted(() => ({ warns: [] as unknown[][] }))
+vi.mock('../src/observability/logger.js', async importActual => {
+ const actual = await importActual<typeof import('../src/observability/logger.js')>()
+ const root = actual.rootLogger
+ const wrapped = Object.create(root) as typeof root
+ wrapped.child = ((bindings: Record<string, unknown>, options?: unknown) => {
+ const child = root.child(bindings, options as never)
+ if (bindings?.module === 'oauth-callback') {
+ const warn = child.warn.bind(child)
+ child.warn = ((...args: unknown[]) => {
+ logged.warns.push(args)
+ return (warn as (...a: unknown[]) => void)(...args)
+ }) as typeof child.warn
+ }
+ return child
+ }) as unknown as typeof root.child
+ return { ...actual, rootLogger: wrapped }
+})
+
+const NS = config.mcpServersNamespace
+const ORIGIN = 'https://control.example.com'
+const CONTEXT = 'ctx-a'
+const STATE_SECRET = 'test-state-hmac-secret-32-bytes-padding'
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+
+// Atlassian v2: CIMD + DCR, no RFC 9207, one site → per-server DCR (public).
+let atlassian: DiscoveryResult
+// Notion: no RFC 9207 → per-server when pre-registered.
+let notion: DiscoveryResult
+// A DCR AS that returns RFC 9207 → shared.
+let sharedDcr: DiscoveryResult
+
+beforeAll(async () => {
+ atlassian = await discoverPilot(ATLASSIAN_V2_PILOT)
+ notion = await discoverPilot(PILOTS.notion)
+ sharedDcr = await discoverPilot(withRfc9207(dcrPilot('public')))
+})
+
+let gateway: MockGateway
+let db: ReturnType<typeof makeInMemoryDynamicClientsDb>['db']
+let savedBaseUrl: string
+
+beforeEach(async () => {
+ savedBaseUrl = config.oauthCallbackBaseUrl
+ config.oauthCallbackBaseUrl = ORIGIN
+ gateway = new MockGateway(NS)
+ await seedContext(gateway, NS, CONTEXT)
+ db = makeInMemoryDynamicClientsDb().db
+ logged.warns.length = 0
+})
+
+afterEach(() => {
+ config.oauthCallbackBaseUrl = savedBaseUrl
+})
+
+interface Installed {
+ name: string
+ redirectUri: string
+ /** Last path segment of a DCR redirect URI; undefined for pre-registered. */
+ nonce?: string
+}
+
+async function installDcr(
+ name: string,
+ discovery = atlassian,
+ baseUrl = ATLASSIAN_V2_PILOT.mcpUrl
+): Promise<Installed> {
+ const res = await installRemoteServer({
+ gateway,
+ db,
+ discovery,
+ body: { serverName: name, contextRef: CONTEXT, baseUrl, mode: 'dcr' },
+ })
+ if (res.status !== 201) throw new Error(`install failed: ${JSON.stringify(res.body)}`)
+ const redirectUri = String(res.body.redirectUri)
+ return { name, redirectUri, nonce: redirectUri.split('/').pop() }
+}
+
+async function installPreRegistered(name: string): Promise<Installed> {
+ const res = await installRemoteServer({
+ gateway,
+ db,
+ discovery: notion,
+ body: {
+ serverName: name,
+ contextRef: CONTEXT,
+ baseUrl: PILOTS.notion.mcpUrl,
+ mode: 'pre-registered',
+ clientId: `client-${name}`,
+ clientSecret: `secret-${name}`,
+ },
+ })
+ if (res.status !== 201) throw new Error(`install failed: ${JSON.stringify(res.body)}`)
+ return { name, redirectUri: String(res.body.redirectUri) }
+}
+
+async function oauthOf(name: string): Promise<Record<string, unknown>> {
+ const cr = (await gateway.getResource('mcpservers', name, NS)) as {
+ spec: { oauth: Record<string, unknown> }
+ }
+ return cr.spec.oauth
+}
+
+/** The state the authorize-url mint signs for this server: its CR's client id. */
+async function stateFor(name: string): Promise<string> {
+ return signOAuthState(STATE_SECRET, {
+ subjectKind: 'mcp',
+ mcpServerName: name,
+ userId: 'user-9',
+ oauthClientId: String((await oauthOf(name)).id),
+ grantKind: 'user',
+ background: false,
+ } as Parameters<typeof signOAuthState>[1])
+}
+
+function perServer(
+ serverName: string,
+ installNonce?: string,
+ origin: string | null = ORIGIN
+): CallbackTarget {
+ return { kind: 'remote-per-server', serverName, installNonce, origin }
+}
+
+function harness() {
+ const tokenPosts: { url: string; body: string }[] = []
+ const pinnedTransport = vi.fn(async (input: PinnedTransportInput): Promise<PinnedRawResponse> => {
+ tokenPosts.push({ url: input.url, body: input.body ?? '' })
+ return {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ bodyText: JSON.stringify({ access_token: 'AT', refresh_token: 'RT', expires_in: 3600 }),
+ }
+ })
+ // The production subject reader (routes/external/oauthCallback.ts) over the gateway.
+ const read = vi.fn(async (name: string): Promise<McpServerOAuthSubject | null> => {
+ const cr = (await gateway.getResource('mcpservers', name, NS)) as McpServerOAuthSpecInput
+ const resolved = resolveServerOAuthSubject(cr, 'consent')
+ return resolved ? { namespace: NS, ...resolved } : null
+ })
+ const recipeRead = vi.fn(async () => null)
+ const deps: CallbackDeps = {
+ db,
+ recipeReader: { read: recipeRead },
+ secretReader: {
+ async read(name, namespace) {
+ const raw = (await gateway.getSecret(name, namespace)) as { data?: Record<string, string> }
+ return Object.fromEntries(
+ Object.entries(raw.data ?? {}).map(([k, v]) => [k, Buffer.from(v, 'base64').toString()])
+ )
+ },
+ },
+ mcpServerReader: { read },
+ userContextsReader: async () => ({ contextIds: [CONTEXT] }),
+ fetchFn: (async () => {
+ throw new Error('the remote lane must not use fetchFn')
+ }) as unknown as typeof fetch,
+ stateSecret: STATE_SECRET,
+ encryptionKey: KEY,
+ resolveDns: async () => ['93.184.216.34'],
+ pinnedTransport,
+ }
+ return { deps, read, recipeRead, tokenPosts }
+}
+
+function redirectUriOf(post: { body: string }): string | null {
+ return new URLSearchParams(post.body).get('redirect_uri')
+}
+
+describe('per-server callback — success', () => {
+ it('DCR: the registered /remote/<name>/<nonce> exchanges, replaying that exact URI', async () => {
+ const srv = await installDcr('atlassian')
+ const h = harness()
+
+ const result = await handleOAuthCallback(
+ { target: perServer(srv.name, srv.nonce), code: 'CODE', state: await stateFor(srv.name) },
+ h.deps
+ )
+
+ expect(result).toMatchObject({ kind: 'ok', source: 'mcp', mcpServerName: 'atlassian' })
+ expect(h.tokenPosts).toHaveLength(1)
+ expect(redirectUriOf(h.tokenPosts[0])).toBe(srv.redirectUri)
+ })
+
+ it('pre-registered: /remote/<name> exchanges with the confidential secret', async () => {
+ const srv = await installPreRegistered('hubspot')
+ const h = harness()
+
+ const result = await handleOAuthCallback(
+ { target: perServer(srv.name), code: 'CODE', state: await stateFor(srv.name) },
+ h.deps
+ )
+
+ expect(result.kind).toBe('ok')
+ expect(h.tokenPosts).toHaveLength(1)
+ expect(redirectUriOf(h.tokenPosts[0])).toBe(`${ORIGIN}/api/v1/oauth-callback/remote/hubspot`)
+ expect(redirectUriOf(h.tokenPosts[0])).toBe(srv.redirectUri)
+ expect(new URLSearchParams(h.tokenPosts[0].body).get('client_secret')).toBe('secret-hubspot')
+ })
+})
+
+describe('per-server callback — a code for one server never binds to another (I2)', () => {
+ it('DCR: /remote/a/<nonceA> with the state of b → binding_mismatch, b never read, no exchange', async () => {
+ const a = await installDcr('server-a')
+ await installDcr('server-b')
+ const h = harness()
+
+ const result = await handleOAuthCallback(
+ { target: perServer(a.name, a.nonce), code: 'CODE', state: await stateFor('server-b') },
+ h.deps
+ )
+
+ expect(result).toEqual({ kind: 'invalid_state', reason: 'binding_mismatch' })
+ expect(h.read).not.toHaveBeenCalled()
+ expect(h.tokenPosts).toHaveLength(0)
+ })
+
+ it('pre-registered: /remote/a with the state of b → binding_mismatch, b never read, no exchange', async () => {
+ const a = await installPreRegistered('server-a')
+ await installPreRegistered('server-b')
+ const h = harness()
+
+ const result = await handleOAuthCallback(
+ { target: perServer(a.name), code: 'CODE', state: await stateFor('server-b') },
+ h.deps
+ )
+
+ expect(result).toEqual({ kind: 'invalid_state', reason: 'binding_mismatch' })
+ expect(h.read).not.toHaveBeenCalled()
+ expect(h.tokenPosts).toHaveLength(0)
+ })
+
+ it('a recipe state on a per-server URI → binding_mismatch, no recipe read', async () => {
+ const a = await installPreRegistered('server-a')
+ const h = harness()
+ const state = signOAuthState(STATE_SECRET, {
+ recipeNamespace: config.sandboxNamespace,
+ recipeName: 'server-a',
+ userId: 'user-9',
+ oauthClientId: 'client-server-a',
+ grantKind: 'user',
+ background: false,
+ })
+
+ const result = await handleOAuthCallback(
+ { target: perServer(a.name), code: 'CODE', state },
+ h.deps
+ )
+
+ expect(result).toEqual({ kind: 'invalid_state', reason: 'binding_mismatch' })
+ expect(h.recipeRead).not.toHaveBeenCalled()
+ expect(h.tokenPosts).toHaveLength(0)
+ })
+})
+
+describe('per-server callback — only the URI this installation registered', () => {
+ it('DCR with a nonce that is not the bound row’s → binding_mismatch, no exchange', async () => {
+ const srv = await installDcr('atlassian')
+ const h = harness()
+
+ const result = await handleOAuthCallback(
+ { target: perServer(srv.name, randomUUID()), code: 'CODE', state: await stateFor(srv.name) },
+ h.deps
+ )
+
+ expect(result).toEqual({ kind: 'invalid_state', reason: 'binding_mismatch' })
+ expect(h.tokenPosts).toHaveLength(0)
+ })
+
+ it('DCR on the nonce-less URI → binding_mismatch (a DCR client never registered it)', async () => {
+ const srv = await installDcr('atlassian')
+ const h = harness()
+
+ const result = await handleOAuthCallback(
+ { target: perServer(srv.name), code: 'CODE', state: await stateFor(srv.name) },
+ h.deps
+ )
+
+ expect(result).toEqual({ kind: 'invalid_state', reason: 'binding_mismatch' })
+ expect(h.tokenPosts).toHaveLength(0)
+ })
+
+ it('pre-registered with a nonce → binding_mismatch (the operator registered /remote/<name>)', async () => {
+ const srv = await installPreRegistered('hubspot')
+ const h = harness()
+
+ const result = await handleOAuthCallback(
+ { target: perServer(srv.name, randomUUID()), code: 'CODE', state: await stateFor(srv.name) },
+ h.deps
+ )
+
+ expect(result).toEqual({ kind: 'invalid_state', reason: 'binding_mismatch' })
+ expect(h.tokenPosts).toHaveLength(0)
+ })
+
+ // I6: an AS that returns `iss` is bound on the shared callback; reaching it through a
+ // per-server URI would skip the issuer check.
+ it('a shared (RFC 9207) server on a per-server URI → binding_mismatch, even with the right iss', async () => {
+ const srv = await installDcr('shared-dcr', sharedDcr, dcrPilot('public').mcpUrl)
+ expect(srv.redirectUri).toBe(`${ORIGIN}/api/v1/oauth-callback/remote`)
+ const h = harness()
+ const iss = String((await oauthOf(srv.name)).issForCallback)
+
+ for (const target of [perServer(srv.name), perServer(srv.name, randomUUID())]) {
+ const result = await handleOAuthCallback(
+ { target, code: 'CODE', state: await stateFor(srv.name), iss },
+ h.deps
+ )
+ expect(result).toEqual({ kind: 'invalid_state', reason: 'binding_mismatch' })
+ }
+ expect(h.tokenPosts).toHaveLength(0)
+ })
+
+ it('a remote server on /oauth-callback/<oauthClientId> → binding_mismatch, no exchange', async () => {
+ const srv = await installDcr('atlassian')
+ const h = harness()
+ const id = String((await oauthOf(srv.name)).id)
+
+ const result = await handleOAuthCallback(
+ {
+ target: { kind: 'client', id, redirectUri: `${ORIGIN}/api/v1/oauth-callback/${id}` },
+ code: 'CODE',
+ state: await stateFor(srv.name),
+ },
+ h.deps
+ )
+
+ expect(result).toEqual({ kind: 'invalid_state', reason: 'binding_mismatch' })
+ expect(h.tokenPosts).toHaveLength(0)
+ })
+
+ it.each([
+ ['no configured origin', null],
+ ['a configured origin that is not bare', `${ORIGIN}/base`],
+ ])('%s → callback_base_url_unconfigured, no exchange', async (_label, origin) => {
+ const srv = await installDcr('atlassian')
+ const h = harness()
+
+ const result = await handleOAuthCallback(
+ {
+ target: perServer(srv.name, srv.nonce, origin),
+ code: 'CODE',
+ state: await stateFor(srv.name),
+ },
+ h.deps
+ )
+
+ expect(result).toEqual({ kind: 'callback_base_url_unconfigured' })
+ expect(h.tokenPosts).toHaveLength(0)
+ })
+})
+
+describe('per-server callback — an iss the AS sends anyway (I8)', () => {
+ async function deliverWithIss(iss: unknown) {
+ const srv = await installDcr('atlassian')
+ const h = harness()
+ const result = await handleOAuthCallback(
+ {
+ target: perServer(srv.name, srv.nonce),
+ code: 'CODE-VALUE',
+ state: await stateFor(srv.name),
+ iss,
+ },
+ h.deps
+ )
+ return { result, h }
+ }
+
+ it('equal to the pinned issuer → exchanges', async () => {
+ const { result, h } = await deliverWithIss(atlassian.issuer)
+ expect(result.kind).toBe('ok')
+ expect(h.tokenPosts).toHaveLength(1)
+ })
+
+ it('absent → exchanges (the AS does not implement RFC 9207)', async () => {
+ const { result, h } = await deliverWithIss(undefined)
+ expect(result.kind).toBe('ok')
+ expect(h.tokenPosts).toHaveLength(1)
+ })
+
+ it.each<[string, () => unknown]>([
+ ['a different issuer', () => 'https://evil.example.test'],
+ ['an empty value', () => ''],
+ ['a repeated parameter', () => [atlassian.issuer, 'https://evil.example.test']],
+ ['a repeated parameter with equal values', () => [atlassian.issuer, atlassian.issuer]],
+ ['a bracketed parameter', () => ({ a: 'b' })],
+ ])('%s → issuer_mismatch, no exchange, log carries only server and reason', async (_l, iss) => {
+ const { result, h } = await deliverWithIss(iss())
+
+ expect(result).toEqual({ kind: 'issuer_mismatch' })
+ expect(h.tokenPosts).toHaveLength(0)
+ expect(logged.warns).toHaveLength(1)
+ const [fields] = logged.warns[0] as [Record<string, unknown>]
+ expect(Object.keys(fields).sort()).toEqual(['reason', 'serverName'])
+ expect(fields.serverName).toBe('atlassian')
+ expect(JSON.stringify(logged.warns[0])).not.toContain('CODE-VALUE')
+ })
+})
diff --git a/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts b/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
index 53a0266b2..cc13b9201 100644
--- a/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
@@ -208,7 +208,7 @@ describeRealPostgres(
transport: ReturnType<typeof recordingAs>['transport']
) {
const input: CallbackInput = {
- oauthClientId: 'remote',
+ target: { kind: 'remote-shared', origin: 'https://control.example.com' },
code: 'AUTH_CODE',
state: signOAuthState(STATE_SECRET, {
subjectKind: 'mcp',
@@ -218,7 +218,6 @@ describeRealPostgres(
grantKind: 'user',
background: false,
} as Parameters<typeof signOAuthState>[1]),
- redirectUri: 'https://control.example.com/api/v1/oauth-callback/remote',
iss: discovery.issuer,
}
const deps: CallbackDeps = {
diff --git a/control-api/test/oauth.perServerCallback.realPostgres.integration.test.ts b/control-api/test/oauth.perServerCallback.realPostgres.integration.test.ts
new file mode 100644
index 000000000..93e417470
--- /dev/null
+++ b/control-api/test/oauth.perServerCallback.realPostgres.integration.test.ts
@@ -0,0 +1,424 @@
+/**
+ * Per-server remote callback end to end, against a real Postgres: the `dynamic_clients`
+ * row that binds a DCR redirect URI to one installation is SQL state, so the checks
+ * that read it are certified on the real store.
+ *
+ * - I4, the redirect-URI triad: the `redirect_uris` the install POSTs to the AS, the
+ * `redirect_uri` of the authorize URL, the path Express routes the AS redirect to,
+ * and the `redirect_uri` replayed on the token POST are one and the same string.
+ * - I11, same-name reinstall: a code sent to the previous installation's URI (old
+ * nonce) is refused; so is any URI of a server whose row carries no nonce.
+ * - I16, DCR vs pre-registered comes from the CR: a public CR without secret refs and
+ * without a row is never treated as pre-registered, and a row registered for
+ * another client id is never used.
+ *
+ * Real producers (T1): discovery by `discoverRemoteOAuth` over probe fixtures; CR,
+ * uid, row and nonce by the real install route; the state by the real authorize-url
+ * mint; teardown by the uninstall's own store call. The AS registration response and
+ * the token endpoint are the only external edges. Context membership is answered on the
+ * app pool as the sibling route suites do (it is not what this suite certifies).
+ *
+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \
+ * test/oauth.perServerCallback.realPostgres.integration.test.ts
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import request from 'supertest'
+import { createApp } from '../src/app.js'
+import { config } from '../src/config.js'
+import type { DbClient } from '../src/db.js'
+import { initDb } from '../src/db.js'
+import type { DiscoveryResult } from '../src/oauth/discovery.js'
+import {
+ claimDeleteDynamicClientForResource,
+ upsertDynamicClient,
+} from '../src/oauth/dynamicClientStore.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
+import { discoverPilot, installRemoteServer, seedContext } from './fixtures/perServerInstall.js'
+import {
+ ATLASSIAN_V2_PILOT,
+ DCR_PUBLIC_REGISTRATION_RESPONSE,
+ PILOTS,
+} from './fixtures/remoteOAuthDiscovery.js'
+import { MockGateway } from './mockGateway.js'
+
+const testDb = vi.hoisted(() => ({
+ pool: undefined as import('pg').Pool | undefined,
+ context: 'ctx-a',
+}))
+
+vi.mock('../src/db.js', async () => {
+ const actual = await vi.importActual<typeof import('../src/db.js')>('../src/db.js')
+ const current = () => {
+ if (!testDb.pool) throw new Error('test pool not initialised')
+ return testDb.pool
+ }
+ return {
+ ...actual,
+ pool: {
+ query: (text: string, values?: unknown[]) => {
+ if (text.includes('FROM user_contexts')) {
+ return Promise.resolve({ rows: [{ context_id: testDb.context }], rowCount: 1 })
+ }
+ return current().query(text, values)
+ },
+ connect: () => current().connect(),
+ },
+ }
+})
+
+vi.mock('../src/services/rateLimiterService.js', () => ({
+ checkAndIncrement: vi.fn().mockResolvedValue({
+ allowed: true,
+ backendAvailable: true,
+ remaining: 59,
+ resetMs: Date.now() + 60_000,
+ windowStartMs: Date.now(),
+ count: 1,
+ }),
+}))
+
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn(async () => [{ address: '93.184.216.34', family: 4 }]),
+}))
+
+const tokenEndpoint = vi.hoisted(() => ({ posts: [] as { url: string; body: string }[] }))
+vi.mock('../src/http/pinnedFetch.js', async () => {
+ const actual = await vi.importActual<typeof import('../src/http/pinnedFetch.js')>(
+ '../src/http/pinnedFetch.js'
+ )
+ return {
+ ...actual,
+ pinnedFetch: (url: string, field: string, options: Parameters<typeof actual.pinnedFetch>[2]) =>
+ options?.transport
+ ? actual.pinnedFetch(url, field, options)
+ : actual.pinnedFetch(url, field, {
+ ...options,
+ resolveDns: async () => ['93.184.216.34'],
+ transport: async input => {
+ tokenEndpoint.posts.push({ url: input.url, body: input.body ?? '' })
+ return {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ bodyText: JSON.stringify({
+ access_token: 'AT',
+ refresh_token: 'RT',
+ expires_in: 3600,
+ }),
+ }
+ },
+ }),
+ }
+})
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+const NS = config.mcpServersNamespace
+const ORIGIN = 'https://control.example.com'
+const CONTEXT = 'ctx-a'
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+const DCR_CLIENT_ID = DCR_PUBLIC_REGISTRATION_RESPONSE.client_id
+
+describeRealPostgres('per-server remote callback (real Postgres)', () => {
+ const database = `control_api_per_server_cb_${randomUUID().replace(/-/g, '')}`
+ let adminPool: Pool
+ let dbPool: Pool
+ let db: DbClient
+ let atlassian: DiscoveryResult
+ let notion: DiscoveryResult
+ let gateway: MockGateway
+ let app: ReturnType<typeof createApp>
+ let savedBaseUrl: string
+
+ beforeAll(async () => {
+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })
+ await initDb({ connect: () => dbPool.connect() })
+ db = { query: (text, values) => dbPool.query(text, values) }
+ testDb.pool = dbPool
+ atlassian = await discoverPilot(ATLASSIAN_V2_PILOT)
+ notion = await discoverPilot(PILOTS.notion)
+ })
+
+ afterAll(async () => {
+ testDb.pool = undefined
+ await dbPool?.end()
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ }
+ })
+
+ beforeEach(async () => {
+ await dbPool.query('DELETE FROM dynamic_clients')
+ await dbPool.query('DELETE FROM oauth_grants')
+ savedBaseUrl = config.oauthCallbackBaseUrl
+ config.oauthCallbackBaseUrl = ORIGIN
+ gateway = new MockGateway(NS)
+ await seedContext(gateway, NS, CONTEXT)
+ app = createApp(gateway as never)
+ tokenEndpoint.posts.length = 0
+ })
+
+ afterEach(() => {
+ config.oauthCallbackBaseUrl = savedBaseUrl
+ })
+
+ async function installAtlassian(name: string) {
+ const res = await installRemoteServer({
+ gateway,
+ db,
+ discovery: atlassian,
+ body: {
+ serverName: name,
+ contextRef: CONTEXT,
+ baseUrl: ATLASSIAN_V2_PILOT.mcpUrl,
+ mode: 'dcr',
+ },
+ })
+ expect(res.status).toBe(201)
+ const post = res.dcrCalls.find(c => c.method === 'POST')
+ const registered = (JSON.parse(post?.body ?? '{}') as { redirect_uris?: string[] })
+ .redirect_uris
+ return { registered, reported: String(res.body.redirectUri) }
+ }
+
+ /** The authorize URL the real mint returns; its state is what the AS round-trips. */
+ async function mint(name: string): Promise<{ redirectUri: string; state: string }> {
+ const res = await request(app)
+ .post('/api/v1/internal/mcp-oauth/authorize-url')
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+ .send({ mcpServerName: name, userId: 'user-9' })
+ if (res.status !== 200)
+ throw new Error(`mint failed: ${res.status} ${JSON.stringify(res.body)}`)
+ const url = new URL(res.body.authorizeUrl)
+ return {
+ redirectUri: String(url.searchParams.get('redirect_uri')),
+ state: String(url.searchParams.get('state')),
+ }
+ }
+
+ /** The AS redirect: GET the redirect URI's path with the code and the state. */
+ function asRedirect(path: string, state: string) {
+ return request(app).get(path).query({ code: 'CODE', state })
+ }
+
+ it('I4: DCR registration, authorize, routed callback and token POST share one redirect URI', async () => {
+ const { registered, reported } = await installAtlassian('atlassian')
+ expect(registered).toHaveLength(1)
+ const [registeredUri] = registered as string[]
+
+ const minted = await mint('atlassian')
+ const routedPath = new URL(minted.redirectUri).pathname
+ const res = await asRedirect(routedPath, minted.state)
+
+ expect(res.status).toBe(200)
+ expect(res.text).toContain('mcpServerName=atlassian')
+ expect(tokenEndpoint.posts).toHaveLength(1)
+ const replayed = new URLSearchParams(tokenEndpoint.posts[0].body).get('redirect_uri')
+ expect(minted.redirectUri).toBe(registeredUri)
+ expect(`${ORIGIN}${routedPath}`).toBe(registeredUri)
+ expect(replayed).toBe(registeredUri)
+ expect(reported).toBe(registeredUri)
+ expect(registeredUri).toMatch(
+ new RegExp(`^${ORIGIN}/api/v1/oauth-callback/remote/atlassian/[0-9a-f-]{36}$`)
+ )
+ const grants = await dbPool.query('SELECT recipe_name FROM oauth_grants')
+ expect(grants.rows).toEqual([{ recipe_name: 'atlassian' }])
+ })
+
+ it('I4 pre-registered: install report, authorize, routed callback and token POST agree', async () => {
+ const install = await installRemoteServer({
+ gateway,
+ db,
+ discovery: notion,
+ body: {
+ serverName: 'notion',
+ contextRef: CONTEXT,
+ baseUrl: PILOTS.notion.mcpUrl,
+ mode: 'pre-registered',
+ clientId: 'client-notion',
+ clientSecret: 'secret-notion',
+ },
+ })
+ expect(install.status).toBe(201)
+ const registered = String(install.body.redirectUri)
+
+ const minted = await mint('notion')
+ const res = await asRedirect(new URL(minted.redirectUri).pathname, minted.state)
+
+ expect(res.status).toBe(200)
+ expect(minted.redirectUri).toBe(registered)
+ expect(new URLSearchParams(tokenEndpoint.posts[0].body).get('redirect_uri')).toBe(registered)
+ expect(registered).toBe(`${ORIGIN}/api/v1/oauth-callback/remote/notion`)
+ })
+
+ it('I11: after a same-name reinstall, a code sent to the old nonce is refused', async () => {
+ const first = await installAtlassian('atlassian')
+ const oldUri = first.reported
+ // Uninstall: the CR goes, and the teardown claims the row bound to its uid.
+ const oldCr = (await gateway.getResource('mcpservers', 'atlassian', NS)) as {
+ metadata: { uid: string }
+ }
+ await gateway.deleteResource('mcpservers', 'atlassian', NS)
+ const { deleted } = await claimDeleteDynamicClientForResource(
+ db,
+ KEY,
+ { serverNamespace: NS, serverName: 'atlassian' },
+ oldCr.metadata.uid
+ )
+ expect(deleted).toBe(true)
+ const second = await installAtlassian('atlassian')
+ expect(second.reported).not.toBe(oldUri)
+
+ const minted = await mint('atlassian')
+ expect(minted.redirectUri).toBe(second.reported)
+ const stale = await asRedirect(new URL(oldUri).pathname, minted.state)
+
+ expect(stale.status).toBe(400)
+ expect(stale.body).toEqual({ error: 'invalid_state', reason: 'binding_mismatch' })
+ expect(tokenEndpoint.posts).toHaveLength(0)
+
+ const fresh = await asRedirect(new URL(second.reported).pathname, minted.state)
+ expect(fresh.status).toBe(200)
+ })
+
+ it('I11: a row without an install nonce binds no URI (legacy row, never sealed)', async () => {
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: 'legacy' },
+ spec: {
+ contextRef: CONTEXT,
+ auth: { type: 'oauth' },
+ oauth: buildRemoteOAuthSpec(atlassian, {
+ clientMode: 'public',
+ grantScope: 'user',
+ dynamicClientId: DCR_CLIENT_ID,
+ }),
+ },
+ },
+ NS
+ )
+ // The only producer of a nonce-less row: the pre-install-identity upsert.
+ await upsertDynamicClient(db, KEY, {
+ serverNamespace: NS,
+ serverName: 'legacy',
+ issuer: atlassian.issuer,
+ clientId: DCR_CLIENT_ID,
+ clientMode: 'public',
+ })
+ const row = await dbPool.query(
+ `SELECT install_id, cr_uid FROM dynamic_clients WHERE server_name = 'legacy'`
+ )
+ expect(row.rows).toEqual([{ install_id: null, cr_uid: null }])
+
+ const mintRes = await request(app)
+ .post('/api/v1/internal/mcp-oauth/authorize-url')
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+ .send({ mcpServerName: 'legacy', userId: 'user-9' })
+ expect(mintRes.status).toBe(503)
+
+ const state = await signedStateFor('legacy')
+ for (const path of ['/remote/legacy', `/remote/legacy/${randomUUID()}`]) {
+ const res = await asRedirect(`/api/v1/oauth-callback${path}`, state)
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'invalid_state', reason: 'binding_mismatch' })
+ }
+ expect(tokenEndpoint.posts).toHaveLength(0)
+ })
+
+ it('I16: a public CR without refs and without a row is not pre-registered → binding_mismatch', async () => {
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: 'gitops' },
+ spec: {
+ contextRef: CONTEXT,
+ auth: { type: 'oauth' },
+ oauth: buildRemoteOAuthSpec(atlassian, {
+ clientMode: 'public',
+ grantScope: 'user',
+ dynamicClientId: DCR_CLIENT_ID,
+ }),
+ },
+ },
+ NS
+ )
+
+ const res = await asRedirect(
+ '/api/v1/oauth-callback/remote/gitops',
+ await signedStateFor('gitops')
+ )
+
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'invalid_state', reason: 'binding_mismatch' })
+ expect(tokenEndpoint.posts).toHaveLength(0)
+ })
+
+ it('I16: a bound row registered for another client id → binding_mismatch', async () => {
+ const { reported } = await installAtlassian('atlassian')
+ const minted = await mint('atlassian')
+ // A write that bypassed the install (and the CRD's immutability) points the CR at
+ // another client; the row still holds the client its nonce was registered for.
+ await gateway.mutateResource(
+ 'mcpservers',
+ 'atlassian',
+ current => ({
+ spec: {
+ ...(current.spec as Record<string, unknown>),
+ oauth: {
+ ...(current.spec as { oauth: Record<string, unknown> }).oauth,
+ id: 'another-client',
+ },
+ },
+ }),
+ NS
+ )
+
+ const res = await asRedirect(new URL(reported).pathname, await signedStateFor('atlassian'))
+
+ expect(minted.redirectUri).toBe(reported)
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'invalid_state', reason: 'binding_mismatch' })
+ expect(tokenEndpoint.posts).toHaveLength(0)
+ })
+
+ /**
+ * A state for a server the mint refuses (no usable registration). Signed by the same
+ * signer the mint uses, with the CR's current client id — what a state minted just
+ * before the row went away would carry.
+ */
+ async function signedStateFor(name: string): Promise<string> {
+ const { signOAuthState } = await import('../src/oauth/state.js')
+ const cr = (await gateway.getResource('mcpservers', name, NS)) as {
+ spec: { oauth: { id: string } }
+ }
+ return signOAuthState(config.oauthStateHmacSecret, {
+ subjectKind: 'mcp',
+ mcpServerName: name,
+ userId: 'user-9',
+ oauthClientId: cr.spec.oauth.id,
+ grantKind: 'user',
+ background: false,
+ } as Parameters<typeof signOAuthState>[1])
+ }
+})
diff --git a/control-api/test/oauth.pkce.test.ts b/control-api/test/oauth.pkce.test.ts
index a7d8c78c4..39d950f18 100644
--- a/control-api/test/oauth.pkce.test.ts
+++ b/control-api/test/oauth.pkce.test.ts
@@ -181,11 +181,14 @@ async function roundTrip(provider: OAuthProvider): Promise<{
const cbResult = await handleOAuthCallback(
{
- oauthClientId: 'oauth1',
+ target: {
+ kind: 'client',
+ id: 'oauth1',
+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/oauth1',
+ },
code: 'AUTH_CODE',
// The EXACT round-tripped state string.
state: state as string,
- redirectUri: 'https://control.example.com/api/v1/oauth-callback/oauth1',
},
deps
)
diff --git a/control-api/test/oauth.remoteSpecCoherence.test.ts b/control-api/test/oauth.remoteSpecCoherence.test.ts
index b53baa246..1a8679350 100644
--- a/control-api/test/oauth.remoteSpecCoherence.test.ts
+++ b/control-api/test/oauth.remoteSpecCoherence.test.ts
@@ -430,6 +430,31 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i
expect(grantWrites).toHaveLength(0)
})
+ // The per-server route reads the same subject: the incoherence is refused before any
+ // binding check or exchange, whichever remote callback the AS used.
+ it(`${c.label}: GET /oauth-callback/remote/srv → 409, nothing persisted`, async () => {
+ const oauth = c.oauth()
+ await seed('srv', oauth)
+ const state = signOAuthState(config.oauthStateHmacSecret, {
+ subjectKind: 'mcp',
+ mcpServerName: 'srv',
+ userId: 'user-1',
+ oauthClientId: oauth.id,
+ grantKind: 'user',
+ background: false,
+ } as Parameters<typeof signOAuthState>[1])
+ const res = await request(app)
+ .get('/api/v1/oauth-callback/remote/srv')
+ .query({ code: 'AUTH_CODE', state })
+ expect(res.status).toBe(409)
+ expect(res.body).toEqual({ error: 'remote_oauth_spec_incoherent', reason: c.reason })
+ const grantWrites = mockPoolQuery.mock.calls.filter(
+ ([sql]) =>
+ typeof sql === 'string' && /INSERT INTO oauth_grants|UPDATE oauth_grants/.test(sql)
+ )
+ expect(grantWrites).toHaveLength(0)
+ })
+
it(`${c.label}: DELETE /internal/mcp-oauth/grant still revokes (204)`, async () => {
await seed('srv', c.oauth())
const res = await request(app)
diff --git a/control-api/test/routes.oauthCallback.remotePerServer.test.ts b/control-api/test/routes.oauthCallback.remotePerServer.test.ts
new file mode 100644
index 000000000..1bb92060c
--- /dev/null
+++ b/control-api/test/routes.oauthCallback.remotePerServer.test.ts
@@ -0,0 +1,443 @@
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import request from 'supertest'
+import { createApp } from '../src/app.js'
+import { config } from '../src/config.js'
+import type { DiscoveryResult } from '../src/oauth/discovery.js'
+import { claimDeleteDynamicClientForResource } from '../src/oauth/dynamicClientStore.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { signOAuthState } from '../src/oauth/state.js'
+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
+import {
+ discoverPilot,
+ installRemoteServer,
+ seedContext,
+ withRfc9207,
+} from './fixtures/perServerInstall.js'
+import {
+ ATLASSIAN_V2_PILOT,
+ PILOTS,
+ dcrPilot,
+ makeInMemoryDynamicClientsDb,
+} from './fixtures/remoteOAuthDiscovery.js'
+import { MockGateway } from './mockGateway.js'
+
+/**
+ * The per-server remote callback and authorize-url through the real app (`createApp`):
+ * the public route `GET /api/v1/oauth-callback/remote/:serverName/:installNonce?`, its
+ * segment validation, what it reports back (the desktop deep link and the
+ * not-configured body name the integration `remote`, as the shared callback does), and
+ * the redirect URI the mint puts in the authorize URL.
+ *
+ * T1: servers are installed by the real admin install route over the same
+ * `dynamic_clients` harness the app's pool is pointed at; discovery by the real client.
+ * The AS token endpoint is the only network edge, answered by a recording transport.
+ */
+
+const dbHolder = vi.hoisted(() => ({
+ db: undefined as undefined | { query: (text: string, values?: unknown[]) => Promise<unknown> },
+ context: 'ctx-a',
+}))
+
+vi.mock('../src/db.js', async importActual => {
+ const actual = await importActual<typeof import('../src/db.js')>()
+ return {
+ ...actual,
+ pool: {
+ query: (text: string, values?: unknown[]) => {
+ // Membership is the only non-OAuth read on these paths.
+ if (text.includes('FROM user_contexts')) {
+ return Promise.resolve({ rows: [{ context_id: dbHolder.context }], rowCount: 1 })
+ }
+ if (!dbHolder.db) throw new Error('test db not initialised')
+ return dbHolder.db.query(text, values)
+ },
+ },
+ }
+})
+
+vi.mock('../src/services/rateLimiterService.js', () => ({
+ checkAndIncrement: vi.fn().mockResolvedValue({
+ allowed: true,
+ backendAvailable: true,
+ remaining: 59,
+ resetMs: Date.now() + 60_000,
+ windowStartMs: Date.now(),
+ count: 1,
+ }),
+}))
+
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn(async () => [{ address: '93.184.216.34', family: 4 }]),
+}))
+
+const tokenEndpoint = vi.hoisted(() => ({ posts: [] as { url: string; body: string }[] }))
+vi.mock('../src/http/pinnedFetch.js', async importActual => {
+ const actual = await importActual<typeof import('../src/http/pinnedFetch.js')>()
+ return {
+ ...actual,
+ // Only calls that would reach the real network (the callback route injects no
+ // transport) are answered here; callers that bring their own keep it.
+ pinnedFetch: (url: string, field: string, options: Parameters<typeof actual.pinnedFetch>[2]) =>
+ options?.transport
+ ? actual.pinnedFetch(url, field, options)
+ : actual.pinnedFetch(url, field, {
+ ...options,
+ resolveDns: async () => ['93.184.216.34'],
+ transport: async input => {
+ tokenEndpoint.posts.push({ url: input.url, body: input.body ?? '' })
+ return {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ bodyText: JSON.stringify({
+ access_token: 'AT',
+ refresh_token: 'RT',
+ expires_in: 3600,
+ }),
+ }
+ },
+ }),
+ }
+})
+
+const NS = config.mcpServersNamespace
+const ORIGIN = 'https://control.example.com'
+const CONTEXT = 'ctx-a'
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+const NONCE = '0f8fad5b-d9cb-469f-a165-70867728950e'
+
+let atlassian: DiscoveryResult
+let notion: DiscoveryResult
+let notionWithIss: DiscoveryResult
+let sharedDcr: DiscoveryResult
+
+beforeAll(async () => {
+ atlassian = await discoverPilot(ATLASSIAN_V2_PILOT)
+ notion = await discoverPilot(PILOTS.notion)
+ notionWithIss = await discoverPilot(withRfc9207(PILOTS.notion))
+ sharedDcr = await discoverPilot(withRfc9207(dcrPilot('public')))
+})
+
+let gateway: MockGateway
+let app: ReturnType<typeof createApp>
+let db: ReturnType<typeof makeInMemoryDynamicClientsDb>['db']
+let savedBaseUrl: string
+
+beforeEach(async () => {
+ savedBaseUrl = config.oauthCallbackBaseUrl
+ config.oauthCallbackBaseUrl = ORIGIN
+ gateway = new MockGateway(NS)
+ await seedContext(gateway, NS, CONTEXT)
+ db = makeInMemoryDynamicClientsDb().db
+ dbHolder.db = db
+ app = createApp(gateway as never)
+ tokenEndpoint.posts.length = 0
+})
+
+afterEach(() => {
+ config.oauthCallbackBaseUrl = savedBaseUrl
+ dbHolder.db = undefined
+})
+
+async function install(
+ name: string,
+ mode: 'dcr' | 'pre-registered',
+ discovery: DiscoveryResult,
+ baseUrl: string
+): Promise<string> {
+ const res = await installRemoteServer({
+ gateway,
+ db,
+ discovery,
+ body: {
+ serverName: name,
+ contextRef: CONTEXT,
+ baseUrl,
+ mode,
+ ...(mode === 'pre-registered'
+ ? { clientId: `client-${name}`, clientSecret: `secret-${name}` }
+ : {}),
+ },
+ })
+ if (res.status !== 201) throw new Error(`install failed: ${JSON.stringify(res.body)}`)
+ return String(res.body.redirectUri)
+}
+
+async function oauthOf(name: string): Promise<Record<string, unknown>> {
+ const cr = (await gateway.getResource('mcpservers', name, NS)) as {
+ spec: { oauth: Record<string, unknown> }
+ }
+ return cr.spec.oauth
+}
+
+async function stateFor(name: string): Promise<string> {
+ return signOAuthState(config.oauthStateHmacSecret, {
+ subjectKind: 'mcp',
+ mcpServerName: name,
+ userId: 'user-9',
+ oauthClientId: String((await oauthOf(name)).id),
+ grantKind: 'user',
+ background: false,
+ } as Parameters<typeof signOAuthState>[1])
+}
+
+function deepLinkOf(html: string): URL {
+ const match = /url=([^"]+)"/.exec(html)
+ if (!match) throw new Error('no deep link in the success page')
+ return new URL(match[1].replace(/&amp;/g, '&'))
+}
+
+function mint(name: string) {
+ return request(app)
+ .post('/api/v1/internal/mcp-oauth/authorize-url')
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+ .send({ mcpServerName: name, userId: 'user-9' })
+}
+
+function redirectUriOfMint(res: { body: { authorizeUrl?: string } }): string | null {
+ return new URL(String(res.body.authorizeUrl)).searchParams.get('redirect_uri')
+}
+
+describe('GET /api/v1/oauth-callback/remote/:serverName/:installNonce?', () => {
+ it.each([
+ ['an uppercase server name', '/remote/Atlassian'],
+ ['an underscore in the name', '/remote/atl_assian'],
+ ['a name longer than an RFC 1123 label', `/remote/${'a'.repeat(64)}`],
+ ['a trailing hyphen', '/remote/atlassian-'],
+ ['an encoded traversal', '/remote/..%2Fadmin'],
+ ['a dotted (subdomain) name', '/remote/atlassian.v2'],
+ ['a double-encoded slash', '/remote/a%252Fb'],
+ ['an uppercase nonce', `/remote/atlassian/${NONCE.toUpperCase()}`],
+ ['a nonce that is not a UUID', '/remote/atlassian/not-a-uuid'],
+ ])('%s → 404 before any CR is read', async (_label, path) => {
+ const read = vi.spyOn(gateway, 'getResource')
+ const res = await request(app)
+ .get(`/api/v1/oauth-callback${path}`)
+ .query({ code: 'CODE', state: 'STATE' })
+ expect(res.status).toBe(404)
+ expect(res.body).toEqual({ error: 'Not Found' })
+ expect(read).not.toHaveBeenCalled()
+ })
+
+ it('I2: /remote/a/<nonceA> with the state of b → 400 binding_mismatch, b never read, no exchange', async () => {
+ const a = await install('server-a', 'dcr', atlassian, ATLASSIAN_V2_PILOT.mcpUrl)
+ await install('server-b', 'dcr', atlassian, ATLASSIAN_V2_PILOT.mcpUrl)
+ const stateOfB = await stateFor('server-b')
+ const read = vi.spyOn(gateway, 'getResource')
+
+ const res = await request(app).get(new URL(a).pathname).query({ code: 'CODE', state: stateOfB })
+
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'invalid_state', reason: 'binding_mismatch' })
+ expect(read).not.toHaveBeenCalledWith('mcpservers', 'server-b', NS)
+ expect(tokenEndpoint.posts).toHaveLength(0)
+ })
+
+ it('is public: valid segments with no service token reach the handler', async () => {
+ const res = await request(app).get(`/api/v1/oauth-callback/remote/atlassian/${NONCE}`)
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'missing_code_or_state' })
+ })
+
+ it('per-server DCR: success page deep link names clientId=remote and the signed server', async () => {
+ const redirectUri = await install('atlassian', 'dcr', atlassian, ATLASSIAN_V2_PILOT.mcpUrl)
+
+ const res = await request(app)
+ .get(new URL(redirectUri).pathname)
+ .query({ code: 'CODE', state: await stateFor('atlassian') })
+
+ expect(res.status).toBe(200)
+ const link = deepLinkOf(res.text)
+ expect(link.searchParams.get('clientId')).toBe('remote')
+ expect(link.searchParams.get('mcpServerName')).toBe('atlassian')
+ expect(link.searchParams.get('source')).toBe('mcp')
+ expect(tokenEndpoint.posts).toHaveLength(1)
+ expect(new URLSearchParams(tokenEndpoint.posts[0].body).get('redirect_uri')).toBe(redirectUri)
+ })
+
+ it('shared: success page deep link names clientId=remote (unchanged)', async () => {
+ await install('shared-dcr', 'dcr', sharedDcr, dcrPilot('public').mcpUrl)
+
+ const res = await request(app)
+ .get('/api/v1/oauth-callback/remote')
+ .query({
+ code: 'CODE',
+ state: await stateFor('shared-dcr'),
+ iss: String((await oauthOf('shared-dcr')).issForCallback),
+ })
+
+ expect(res.status).toBe(200)
+ expect(deepLinkOf(res.text).searchParams.get('clientId')).toBe('remote')
+ })
+
+ it.each([
+ ['per-server', () => notion, (name: string) => `/api/v1/oauth-callback/remote/${name}`],
+ ['shared', () => notionWithIss, () => '/api/v1/oauth-callback/remote'],
+ ])(
+ '%s pre-registered with its client Secret gone → 503 naming the integration "remote"',
+ async (_label, discovery, path) => {
+ await install('hubspot', 'pre-registered', discovery(), PILOTS.notion.mcpUrl)
+ const oauth = await oauthOf('hubspot')
+ const secretName = (oauth.clientSecretRef as { name: string }).name
+ await gateway.deleteSecret(secretName, NS)
+
+ const res = await request(app)
+ .get(path('hubspot'))
+ .query({
+ code: 'CODE',
+ state: await stateFor('hubspot'),
+ ...(oauth.issForCallback ? { iss: String(oauth.issForCallback) } : {}),
+ })
+
+ expect(res.status).toBe(503)
+ expect(res.body).toMatchObject({ error: 'integration_not_configured', integration: 'remote' })
+ expect(tokenEndpoint.posts).toHaveLength(0)
+ }
+ )
+
+ it('no configured public origin → 503 callback_base_url_unconfigured, no exchange', async () => {
+ const redirectUri = await install('atlassian', 'dcr', atlassian, ATLASSIAN_V2_PILOT.mcpUrl)
+ config.oauthCallbackBaseUrl = ''
+
+ const res = await request(app)
+ .get(new URL(redirectUri).pathname)
+ .query({ code: 'CODE', state: await stateFor('atlassian') })
+
+ expect(res.status).toBe(503)
+ expect(res.body).toEqual({ error: 'callback_base_url_unconfigured' })
+ expect(tokenEndpoint.posts).toHaveLength(0)
+ })
+
+ it('a repeated iss reaches the per-server check raw → 400 issuer_mismatch', async () => {
+ const redirectUri = await install('atlassian', 'dcr', atlassian, ATLASSIAN_V2_PILOT.mcpUrl)
+ const state = await stateFor('atlassian')
+
+ const res = await request(app).get(
+ `${new URL(redirectUri).pathname}?code=CODE&state=${encodeURIComponent(state)}` +
+ `&iss=${encodeURIComponent(atlassian.issuer)}&iss=${encodeURIComponent(atlassian.issuer)}`
+ )
+
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'issuer_mismatch' })
+ expect(tokenEndpoint.posts).toHaveLength(0)
+ })
+
+ it('shared keeps reading a repeated iss as absent → 400 issuer_mismatch (unchanged)', async () => {
+ await install('shared-dcr', 'dcr', sharedDcr, dcrPilot('public').mcpUrl)
+ const iss = String((await oauthOf('shared-dcr')).issForCallback)
+ const state = await stateFor('shared-dcr')
+
+ const res = await request(app).get(
+ `/api/v1/oauth-callback/remote?code=CODE&state=${encodeURIComponent(state)}` +
+ `&iss=${encodeURIComponent(iss)}&iss=${encodeURIComponent(iss)}`
+ )
+
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'issuer_mismatch' })
+ })
+})
+
+describe('POST /api/v1/internal/mcp-oauth/authorize-url — remote redirect URI', () => {
+ it('per-server DCR: the authorize redirect_uri is the URI the install registered', async () => {
+ const registered = await install('atlassian', 'dcr', atlassian, ATLASSIAN_V2_PILOT.mcpUrl)
+
+ const res = await mint('atlassian')
+
+ expect(res.status).toBe(200)
+ expect(redirectUriOfMint(res)).toBe(registered)
+ expect(registered).toMatch(/\/api\/v1\/oauth-callback\/remote\/atlassian\/[0-9a-f-]{36}$/)
+ })
+
+ it('per-server pre-registered: /remote/<name>, the URI the install reported', async () => {
+ const registered = await install('hubspot', 'pre-registered', notion, PILOTS.notion.mcpUrl)
+
+ const res = await mint('hubspot')
+
+ expect(res.status).toBe(200)
+ expect(redirectUriOfMint(res)).toBe(`${ORIGIN}/api/v1/oauth-callback/remote/hubspot`)
+ expect(redirectUriOfMint(res)).toBe(registered)
+ })
+
+ it('shared: the stable /remote URI (unchanged)', async () => {
+ const registered = await install('shared-dcr', 'dcr', sharedDcr, dcrPilot('public').mcpUrl)
+
+ const res = await mint('shared-dcr')
+
+ expect(res.status).toBe(200)
+ expect(redirectUriOfMint(res)).toBe(`${ORIGIN}/api/v1/oauth-callback/remote`)
+ expect(redirectUriOfMint(res)).toBe(registered)
+ })
+
+ it('shared without a configured origin keeps falling back to the request Host', async () => {
+ await install('shared-dcr', 'dcr', sharedDcr, dcrPilot('public').mcpUrl)
+ config.oauthCallbackBaseUrl = ''
+
+ const res = await mint('shared-dcr').set('Host', 'cp.internal.test')
+
+ expect(res.status).toBe(200)
+ expect(redirectUriOfMint(res)).toBe('http://cp.internal.test/api/v1/oauth-callback/remote')
+ })
+
+ it.each([
+ ['unset', ''],
+ ['not a bare origin', `${ORIGIN}/base/`],
+ ])('per-server with the callback base URL %s → 503, no URL minted', async (_l, baseUrl) => {
+ await install('atlassian', 'dcr', atlassian, ATLASSIAN_V2_PILOT.mcpUrl)
+ config.oauthCallbackBaseUrl = baseUrl
+
+ const res = await mint('atlassian')
+
+ expect(res.status).toBe(503)
+ expect(res.body).toEqual({ error: 'callback_base_url_unconfigured' })
+ })
+
+ it('per-server DCR whose row is gone → 503 integration_not_configured, no URL minted', async () => {
+ await install('atlassian', 'dcr', atlassian, ATLASSIAN_V2_PILOT.mcpUrl)
+ const cr = (await gateway.getResource('mcpservers', 'atlassian', NS)) as {
+ metadata: { uid: string }
+ }
+ const { deleted } = await claimDeleteDynamicClientForResource(
+ db,
+ KEY,
+ { serverNamespace: NS, serverName: 'atlassian' },
+ cr.metadata.uid
+ )
+ expect(deleted).toBe(true)
+
+ const res = await mint('atlassian')
+
+ expect(res.status).toBe(503)
+ expect(res.body).toEqual({
+ error: 'integration_not_configured',
+ integration: String((await oauthOf('atlassian')).id),
+ hint: 'reinstall the remote MCP server atlassian to register its OAuth client again',
+ })
+ expect(res.body.authorizeUrl).toBeUndefined()
+ })
+
+ // A CR can only carry a non-label name when written outside the install; its callback
+ // route would never match, so there is nothing to mint.
+ it('per-server server whose name is not an RFC 1123 label → 400 invalid_request', async () => {
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: 'atlassian.v2' },
+ spec: {
+ contextRef: CONTEXT,
+ auth: { type: 'oauth' },
+ oauth: buildRemoteOAuthSpec(atlassian, {
+ clientMode: 'public',
+ grantScope: 'user',
+ dynamicClientId: 'dyn-public-6f1c2a',
+ }),
+ },
+ },
+ NS
+ )
+
+ const res = await mint('atlassian.v2')
+
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'invalid_request' })
+ })
+})
diff --git a/control-ui/lib/remoteMcp.types.ts b/control-ui/lib/remoteMcp.types.ts
index fa573098f..1bf4ad5b6 100644
--- a/control-ui/lib/remoteMcp.types.ts
+++ b/control-ui/lib/remoteMcp.types.ts
@@ -37,7 +37,8 @@ export interface RemoteDetectedEndpoints {
}
/**
- * Hostnames of the AS endpoints an install would trust. Reported only for a
+ * Hosts (hostname plus any non-default port) of the AS endpoints an install
+ * would trust. Reported only for a
* `per-server` callback (no RFC 9207 `iss`), where the same-site rule is all that
* ties them to the issuer and cannot tell two hosts of one domain apart.
*/
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 6cf07b947..36ad3dd9a 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.663",
+ "version": "0.1.664",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.663",
+ "version": "0.1.664",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index 42dfc7727..fa162db2a 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.663",
+ "version": "0.1.664",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.projection.test.ts b/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.projection.test.ts
index 99dfec756..d197c54d7 100644
--- a/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.projection.test.ts
+++ b/control-ui/test/fixtures/__tests__/remoteMcpDiscovery.projection.test.ts
@@ -50,9 +50,9 @@ describe('remote MCP `/discover` goldens carry the callback contract the wizard
}
const { authorization, token, registration } = body.detected.endpoints
expect(hosts).toEqual({
- authorization: new URL(authorization).hostname,
- token: new URL(token).hostname,
- ...(registration ? { registration: new URL(registration).hostname } : {}),
+ authorization: new URL(authorization).host,
+ token: new URL(token).host,
+ ...(registration ? { registration: new URL(registration).host } : {}),
})
})