Skip to content

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

TypeScript

feat(control-api): generic OAuth carril runtime (source:'generic') (S3.2)

Diego Zacariasb1f7f76c0405
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 457f61f6a..cc624b3db 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.598",
+ "version": "0.1.599",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.598",
+ "version": "0.1.599",
"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 393630037..944361935 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.598",
+ "version": "0.1.599",
"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/authorizeUrlHelper.ts b/control-api/src/oauth/authorizeUrlHelper.ts
index a43a90781..6d6ffbe04 100644
--- a/control-api/src/oauth/authorizeUrlHelper.ts
+++ b/control-api/src/oauth/authorizeUrlHelper.ts
@@ -10,6 +10,7 @@ import {
} from './callback.js'
import { computeCodeChallengeS256, deriveCodeVerifier } from './pkce.js'
import {
+ buildAdapterFromConfig,
buildRemoteAuthorizeUrl,
getOAuthProviderAdapter,
isKnownOAuthProvider,
@@ -186,6 +187,26 @@ async function mintAuthorizeUrl(
return { kind: 'ok', authorizeUrl }
}
+ // Generic self-hosted lane (`source:'generic'`, DEC-28): the authorize URL is
+ // composed from the pinned `authorizationEndpoint` + wire knobs
+ // (`buildAdapterFromConfig`) with the PUBLIC client_id (`decl.id`). PKCE S256 is
+ // gated on `usePkce`; when off, no challenge is computed or emitted. No K8s
+ // Secret is read (the client_id rides `oauth.id`, not a Secret).
+ if (decl.generic) {
+ const state = signOAuthState(deps.stateSecret, stateInput)
+ const codeChallenge = decl.generic.usePkce
+ ? computeCodeChallengeS256(deriveCodeVerifier(deps.stateSecret, state))
+ : undefined
+ const authorizeUrl = buildAdapterFromConfig(decl.generic).buildAuthorizeUrl({
+ clientId: decl.id,
+ redirectUri: input.redirectUri,
+ state,
+ scopes: decl.scopes ?? [],
+ codeChallenge,
+ })
+ return { kind: 'ok', authorizeUrl }
+ }
+
if (!isKnownOAuthProvider(decl.provider)) {
return { kind: 'unsupported_provider', provider: decl.provider }
}
diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.ts
index d6e3d73fa..2f079b3c0 100644
--- a/control-api/src/oauth/callback.ts
+++ b/control-api/src/oauth/callback.ts
@@ -5,8 +5,10 @@ import type { DnsResolver } from '../http/validateMcpServerSpec.js'
import { getDynamicClient } from './dynamicClientStore.js'
import { deriveCodeVerifier } from './pkce.js'
import {
+ type GenericAdapterConfig,
type OAuthProvider,
type ParsedTokenResponse,
+ buildAdapterFromConfig,
buildRemoteTokenRequest,
getOAuthProviderAdapter,
isKnownOAuthProvider,
@@ -64,6 +66,20 @@ export interface RemoteClientRouting {
issForCallback?: string
}
+/**
+ * Generic self-hosted OAuth routing pinned on the CR (`source:'generic'`, DEC-28).
+ * Present only for a `source:'generic'` client; drives a KNOB-configured
+ * exchange/refresh/authorize via `buildAdapterFromConfig` instead of a baked
+ * provider adapter. Like the remote lane, the operator-supplied endpoints are
+ * attacker-influenced ⇒ every token/refresh POST is IP-pinned (DEC-17). Extends
+ * the pure wire knobs (`GenericAdapterConfig`, single source of truth in
+ * providers.ts) with the fail-closed `supportsRefresh` flag (D-8).
+ */
+export interface GenericClientRouting extends GenericAdapterConfig {
+ /** D-8: fail-closed — false ⇒ NEVER attempt a refresh. */
+ supportsRefresh: boolean
+}
+
/**
* End-to-end handler for the auth-code OAuth callback. Independent of Express
* so we can unit-test it with stubs for K8s + DB + fetch. The route handler
@@ -104,8 +120,16 @@ export interface OAuthClientDecl {
*/
remote?: RemoteClientRouting
/**
- * Where the remote client credentials live (DEC-18). Present only alongside
- * `remote`; absent ⇒ the legacy K8s `clientIdRef`/`clientSecretRef` path.
+ * Generic self-hosted OAuth routing (`source:'generic'`, DEC-28). Present ⇒ the
+ * knob-configured lane: exchange/refresh/authorize use the pinned endpoints +
+ * `buildAdapterFromConfig` + `secretSource` instead of a baked provider adapter.
+ * Mutually exclusive with `remote`. Absent ⇒ baked/recipe (byte-identical).
+ */
+ generic?: GenericClientRouting
+ /**
+ * Where the remote/generic client credentials live (DEC-18). Present alongside
+ * `remote` or `generic`; absent ⇒ the legacy K8s `clientIdRef`/`clientSecretRef`
+ * path. For the generic lane it is `public` (no refs) or `k8s-secret` (both refs).
*/
secretSource?: ServerOAuthSecretSource
}
@@ -238,8 +262,11 @@ export interface CallbackDeps {
pinnedTransport?: PinnedTransport
}
-/** Provider label persisted / displayed. `'remote'` for the discovery-derived lane. */
-export type GrantProviderLabel = OAuthProvider | 'remote'
+/**
+ * Provider label persisted / displayed. `'remote'` for the discovery-derived lane,
+ * `'generic'` for the knob-configured self-hosted lane (DEC-28).
+ */
+export type GrantProviderLabel = OAuthProvider | 'remote' | 'generic'
export type CallbackResult =
| {
@@ -605,6 +632,13 @@ async function exchangeAuthCode(
return exchangeRemoteAuthCode(decl, secretNamespace, serverName, input, 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, serverName, input, deps)
+ }
+
// Baked/recipe lane. clientIdRef is always present here (remote is the only
// decl that omits it); guard fail-closed rather than dereference undefined.
if (!decl.clientIdRef) {
@@ -747,6 +781,74 @@ async function exchangeRemoteAuthCode(
}
}
+/**
+ * Generic-lane auth-code exchange (`source:'generic'`, DEC-28). Operator-pinned
+ * token endpoint ⇒ IP-pinned POST (DEC-17). The request is composed from the CR
+ * knobs via `buildAdapterFromConfig`; credentials come from `secretSource`
+ * (public ⇒ no `client_secret`; k8s-secret ⇒ both read from the named Secret).
+ * PKCE is gated on the `usePkce` knob.
+ */
+async function exchangeGenericAuthCode(
+ decl: OAuthClientDecl,
+ secretNamespace: string,
+ serverName: string | undefined,
+ input: CallbackInput,
+ deps: CallbackDeps
+): Promise<ExchangeAuthCodeResult> {
+ // `decl.generic` presence is the branch guard in the caller.
+ const generic = decl.generic as GenericClientRouting
+ const credResult = await resolveRemoteClientCredential(decl, secretNamespace, serverName, deps)
+ if (!credResult.ok) return { kind: 'secret_missing', secret: credResult.secret }
+
+ const adapter = buildAdapterFromConfig(generic)
+ // 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)
+ : undefined
+
+ let tokenRequest: ReturnType<typeof adapter.buildTokenRequest>
+ try {
+ // 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,
+ clientId: credResult.cred.clientId,
+ clientSecret: credResult.cred.clientSecret,
+ redirectUri: input.redirectUri,
+ codeVerifier,
+ })
+ } catch (err) {
+ return { kind: 'provider_response_invalid', detail: (err as Error).message }
+ }
+
+ const posted = await postRemoteTokenForm(
+ tokenRequest.url,
+ 'spec.oauth.tokenEndpoint',
+ tokenRequest,
+ {
+ resolveDns: deps.resolveDns,
+ pinnedTransport: deps.pinnedTransport,
+ timeoutMs: deps.tokenRequestTimeoutMs,
+ }
+ )
+ if (!posted.ok) {
+ if (typeof posted.status === 'number') {
+ return { kind: 'provider_token_exchange_failed', status: posted.status, body: posted.detail }
+ }
+ return { kind: 'provider_response_invalid', detail: posted.detail }
+ }
+ try {
+ return {
+ kind: 'ok',
+ provider: 'generic',
+ parsed: adapter.parseTokenResponse(JSON.parse(posted.bodyText)),
+ }
+ } catch (err) {
+ return { kind: 'provider_response_invalid', detail: (err as Error).message }
+ }
+}
+
/** Resolved remote client credentials for a token/refresh POST. */
export interface RemoteClientCredential {
clientId: string
@@ -818,10 +920,13 @@ export type RemotePostResult =
| { ok: false; status?: number; detail: string }
/**
- * POST a form-encoded token/refresh request to a discovery-derived endpoint
- * through the IP-pinned `pinnedFetch` (DEC-17). Adds `content-length` (the pinned
- * `node:https` transport needs an explicit length rather than chunked) on top of
- * the builder's `content-type: application/x-www-form-urlencoded`. Any pin-level
+ * POST a token/refresh request to a discovery-derived (remote) or operator-pinned
+ * (generic) endpoint through the IP-pinned `pinnedFetch` (DEC-17). Body-agnostic:
+ * the builder owns the `content-type` (`application/x-www-form-urlencoded` for the
+ * remote/baked and generic form path, `application/json` for a generic
+ * `tokenRequestFormat:'json'` server); this helper only adds `content-length` (the
+ * pinned `node:https` transport needs an explicit length rather than chunked) from
+ * `Buffer.byteLength` of the builder's body. Any pin-level
* failure (kernel-rejected, transport, non-identity encoding) is a fail-closed
* `ok:false` with a NAME-only detail — never secret material. Shared by exchange
* + refresh (D4).
diff --git a/control-api/src/oauth/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.ts
index 0ba9c0205..22da664d0 100644
--- a/control-api/src/oauth/mcpServerOAuthSpec.ts
+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts
@@ -11,7 +11,12 @@
* All read the SAME fields the SAME way and derive the SAME `oauth_grants` key
* (`buildMcpServerGrantKey`), so the rule lives here once.
*/
-import type { OAuthClientDecl, RemoteClientRouting, ServerOAuthSecretSource } from './callback.js'
+import type {
+ GenericClientRouting,
+ OAuthClientDecl,
+ RemoteClientRouting,
+ ServerOAuthSecretSource,
+} from './callback.js'
import type { OAuthGrantKey } from './store.js'
export interface McpServerOAuthDecl {
@@ -32,6 +37,16 @@ export interface McpServerOAuthDecl {
bearerInBody?: unknown
supportsRefresh?: unknown
issForCallback?: unknown
+ // Generic self-hosted lane (`source:'generic'`, DEC-28). Untrusted CR data →
+ // every field is validated before use; a malformed generic block fails closed.
+ refreshEndpoint?: unknown
+ tokenRequestFormat?: unknown
+ tokenAuthMethod?: unknown
+ scopeSeparator?: unknown
+ sendScope?: unknown
+ usePkce?: unknown
+ includeResponseType?: unknown
+ extraAuthorizeParams?: unknown
}
/** Minimal structural shape needed to resolve a server's OAuth grant coordinate. */
@@ -197,6 +212,71 @@ function resolveRemoteSecretSource(
return clientMode === 'confidential' ? { kind: 'dcr-store' } : { kind: 'public' }
}
+/** Read the optional `extraAuthorizeParams` map, keeping only string-valued keys. */
+function extractExtraAuthorizeParams(raw: unknown): Record<string, string> | undefined {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined
+ const out: Record<string, string> = {}
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
+ if (typeof v === 'string') out[k] = v
+ }
+ return Object.keys(out).length > 0 ? out : undefined
+}
+
+/**
+ * Extract + type-validate the generic routing block from an untrusted `spec.oauth`
+ * (DEC-28). The three wire enums (`tokenRequestFormat`/`tokenAuthMethod`/
+ * `scopeSeparator`) fail closed to null when malformed; the booleans read as
+ * `=== true` (absent ⇒ false), mirroring the remote block's boolean handling.
+ */
+function extractGenericRouting(oauth: McpServerOAuthDecl): GenericClientRouting | null {
+ const authorizationEndpoint = oauth.authorizationEndpoint
+ const tokenEndpoint = oauth.tokenEndpoint
+ if (typeof authorizationEndpoint !== 'string' || authorizationEndpoint.length === 0) return null
+ if (typeof tokenEndpoint !== 'string' || tokenEndpoint.length === 0) return null
+ const tokenRequestFormat = oauth.tokenRequestFormat
+ if (tokenRequestFormat !== 'form' && tokenRequestFormat !== 'json') return null
+ const tokenAuthMethod = oauth.tokenAuthMethod
+ if (tokenAuthMethod !== 'body' && tokenAuthMethod !== 'basic') return null
+ const scopeSeparator = oauth.scopeSeparator
+ if (scopeSeparator !== 'space' && scopeSeparator !== 'comma') return null
+ const refreshEndpoint =
+ typeof oauth.refreshEndpoint === 'string' && oauth.refreshEndpoint.length > 0
+ ? oauth.refreshEndpoint
+ : undefined
+ const resource =
+ typeof oauth.resource === 'string' && oauth.resource.length > 0 ? oauth.resource : undefined
+ return {
+ authorizationEndpoint,
+ tokenEndpoint,
+ refreshEndpoint,
+ resource,
+ tokenRequestFormat,
+ tokenAuthMethod,
+ scopeSeparator,
+ sendScope: oauth.sendScope === true,
+ usePkce: oauth.usePkce === true,
+ includeResponseType: oauth.includeResponseType === true,
+ supportsRefresh: oauth.supportsRefresh === true,
+ extraAuthorizeParams: extractExtraAuthorizeParams(oauth.extraAuthorizeParams),
+ }
+}
+
+/**
+ * Classify a generic client's secret source (DEC-28): NEITHER ref ⇒ public (no
+ * secret; `client_id` IS `oauth.id`); BOTH refs ⇒ k8s-secret (reuse the shared
+ * shape). Exactly one ref is a half-declared config ⇒ null (fail closed), never
+ * silently treated as public.
+ */
+function resolveGenericSecretSource(oauth: McpServerOAuthDecl): ServerOAuthSecretSource | null {
+ const clientIdRef = readRef(oauth.clientIdRef)
+ const clientSecretRef = readRef(oauth.clientSecretRef)
+ if (clientIdRef && clientSecretRef) {
+ return { kind: 'k8s-secret', clientIdRef, clientSecretRef }
+ }
+ if (clientIdRef || clientSecretRef) return null
+ return { kind: 'public' }
+}
+
function normalizeScopes(scopes: unknown): string[] | undefined {
return Array.isArray(scopes)
? scopes.filter((s): s is string => typeof s === 'string')
@@ -255,6 +335,30 @@ export function resolveServerOAuthSubject(
return { decl, grantScope, contextRef }
}
+ // ─── Generic self-hosted lane (`source:'generic'`, DEC-28) ────────────────
+ if (oauth.source === 'generic') {
+ const generic = extractGenericRouting(oauth)
+ if (!generic) return null
+ const secretSource = resolveGenericSecretSource(oauth)
+ if (!secretSource) return null
+ const decl: OAuthClientDecl = {
+ id: oauth.id,
+ // No baked provider on the generic lane; exchange/refresh/authorize branch on
+ // `generic` before any provider-adapter lookup. `'generic'` is the persisted /
+ // displayed label only — it NEVER reaches ADAPTERS/KNOWN_OAUTH_PROVIDERS.
+ provider: 'generic',
+ scopes: normalizeScopes(oauth.scopes),
+ backgroundAccess: oauth.backgroundAccess === true,
+ generic,
+ secretSource,
+ }
+ if (secretSource.kind === 'k8s-secret') {
+ decl.clientIdRef = secretSource.clientIdRef
+ decl.clientSecretRef = secretSource.clientSecretRef
+ }
+ return { decl, grantScope, contextRef }
+ }
+
// ─── Baked lane (byte-identical to before) ───────────────────────────────
if (typeof oauth.provider !== 'string' || oauth.provider.length === 0) return null
const clientIdRef = readRef(oauth.clientIdRef)
diff --git a/control-api/src/oauth/providers.ts b/control-api/src/oauth/providers.ts
index c873af98b..448fdfff6 100644
--- a/control-api/src/oauth/providers.ts
+++ b/control-api/src/oauth/providers.ts
@@ -681,3 +681,199 @@ export function buildRemoteRefreshRequest(
/** Remote token responses are standard OAuth2 — reuse the baked parser. */
export const parseRemoteTokenResponse = parseStandardOAuth2
+
+// ─── Generic self-hosted OAuth composer (S3.2 / DEC-28) ─────────────────────
+//
+// The `source:'generic'` lane speaks OAuth to operator-pinned endpoints whose
+// wire shape is described by a fixed set of KNOBS rather than a baked adapter.
+// `buildAdapterFromConfig` is a PURE knob→wire composer: given the knobs it
+// returns a per-call `{ buildAuthorizeUrl, buildTokenRequest, buildRefreshRequest,
+// parseTokenResponse }`. It is NOT a decision module — each knob independently
+// selects ONE fixed behavior (no precedence/merge/ordering resolution) — and it is
+// deliberately NOT added to `OAuthProvider`/`ADAPTERS`/`KNOWN_OAUTH_PROVIDERS`:
+// the 8 baked adapters and the provider enum stay byte-frozen (T1 golden). It
+// reuses the existing `standardTokenRequest`/`standardRefreshRequest`/
+// `parseStandardOAuth2` + `appendResource` primitives, so the `form`+`body` combo
+// is byte-identical to the baked/remote form shape.
+
+/** The wire knobs a generic client is configured with (mirrors the CRD generic fields). */
+export interface GenericAdapterConfig {
+ authorizationEndpoint: string
+ tokenEndpoint: string
+ /** Optional; the refresh POST targets this, defaulting to `tokenEndpoint`. */
+ refreshEndpoint?: string
+ /** RFC 8707 resource indicator, echoed on authorize + token/refresh when present. */
+ resource?: string
+ /** Token/refresh POST body encoding. */
+ tokenRequestFormat: 'form' | 'json'
+ /** `client_secret` placement: form/JSON body vs HTTP Basic header. */
+ tokenAuthMethod: 'body' | 'basic'
+ /** Separator joining scopes on the authorize URL. */
+ scopeSeparator: 'space' | 'comma'
+ /** Whether to emit the `scope` param on the authorize URL at all. */
+ sendScope: boolean
+ /** PKCE S256 on authorize + `code_verifier` on exchange. */
+ usePkce: boolean
+ /** Emit `response_type=code` on the authorize URL. */
+ includeResponseType: boolean
+ /** Static extra query params appended to the authorize URL (reserved params win). */
+ extraAuthorizeParams?: Record<string, string>
+}
+
+/** Per-call generic adapter: same four capabilities a baked adapter exposes. */
+export interface GenericAdapter {
+ buildAuthorizeUrl(input: AuthorizeUrlInput): string
+ buildTokenRequest(input: TokenExchangeInput): TokenRequest
+ buildRefreshRequest(input: RefreshTokenInput): TokenRequest
+ parseTokenResponse(body: unknown): ParsedTokenResponse
+}
+
+function basicAuthHeader(clientId: string, clientSecret: string): string {
+ return `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`
+}
+
+/** Append `resource` as a JSON field (RFC 8707) without disturbing key order. */
+function withJsonResource(body: Record<string, string>, resource?: string): Record<string, string> {
+ if (!resource) return body
+ return { ...body, resource }
+}
+
+/**
+ * Compose a per-call generic OAuth adapter from its wire knobs. Pure: the same
+ * `(config, input)` always yields the same request/URL, and it never reads I/O.
+ */
+export function buildAdapterFromConfig(config: GenericAdapterConfig): GenericAdapter {
+ const scopeSep = config.scopeSeparator === 'comma' ? ',' : ' '
+ const useJson = config.tokenRequestFormat === 'json'
+ const useBasic = config.tokenAuthMethod === 'basic'
+
+ return {
+ buildAuthorizeUrl(input: AuthorizeUrlInput): string {
+ // Reserved OAuth params first; `extraAuthorizeParams` may only FILL GAPS,
+ // never clobber a reserved param (an operator's static extras must not be
+ // able to override `state`, `code_challenge`, `client_id`, …). One fixed
+ // rule, not a precedence table.
+ const params: Record<string, string> = {}
+ if (config.includeResponseType) params.response_type = 'code'
+ params.client_id = input.clientId
+ params.redirect_uri = input.redirectUri
+ params.state = input.state
+ if (config.usePkce && input.codeChallenge) {
+ params.code_challenge = input.codeChallenge
+ params.code_challenge_method = 'S256'
+ }
+ if (config.sendScope && input.scopes.length > 0) {
+ params.scope = input.scopes.join(scopeSep)
+ }
+ if (config.resource) params.resource = config.resource
+ for (const [k, v] of Object.entries(config.extraAuthorizeParams ?? {})) {
+ if (!(k in params)) params[k] = v
+ }
+ const sep = config.authorizationEndpoint.includes('?') ? '&' : '?'
+ return `${config.authorizationEndpoint}${sep}${urlEncode(params)}`
+ },
+
+ buildTokenRequest(input: TokenExchangeInput): TokenRequest {
+ // form + body → the standard OAuth2 shape verbatim (byte-identical to the
+ // baked/remote form adapters), then RFC 8707 resource.
+ if (!useJson && !useBasic) {
+ return appendResource(standardTokenRequest(config.tokenEndpoint, input), config.resource)
+ }
+ const extraHeaders: Record<string, string> = {}
+ if (useBasic) {
+ if (!input.clientSecret) {
+ // Basic client authentication needs a secret; a public generic client
+ // must use tokenAuthMethod=body. Fail closed (like the notion adapter).
+ throw new Error('generic OAuth tokenAuthMethod=basic requires a client secret')
+ }
+ extraHeaders.authorization = basicAuthHeader(input.clientId, input.clientSecret)
+ }
+ if (useJson) {
+ const body: Record<string, string> = { grant_type: 'authorization_code' }
+ // Basic auth carries the credentials in the header; omit them from the body.
+ if (!useBasic) {
+ body.client_id = input.clientId
+ if (input.clientSecret) body.client_secret = input.clientSecret
+ }
+ body.code = input.code
+ body.redirect_uri = input.redirectUri
+ if (input.codeVerifier) body.code_verifier = input.codeVerifier
+ return {
+ url: config.tokenEndpoint,
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ accept: 'application/json',
+ ...extraHeaders,
+ },
+ body: JSON.stringify(withJsonResource(body, config.resource)),
+ }
+ }
+ // form + basic: form body without client creds (they ride the Basic header).
+ const params: Record<string, string> = {
+ grant_type: 'authorization_code',
+ code: input.code,
+ redirect_uri: input.redirectUri,
+ }
+ if (input.codeVerifier) params.code_verifier = input.codeVerifier
+ const request: TokenRequest = {
+ url: config.tokenEndpoint,
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded',
+ accept: 'application/json',
+ ...extraHeaders,
+ },
+ body: urlEncode(params),
+ }
+ return appendResource(request, config.resource)
+ },
+
+ buildRefreshRequest(input: RefreshTokenInput): TokenRequest {
+ const url = config.refreshEndpoint ?? config.tokenEndpoint
+ // form + body → standard refresh verbatim + resource.
+ if (!useJson && !useBasic) {
+ return appendResource(standardRefreshRequest(url, input), config.resource)
+ }
+ const extraHeaders: Record<string, string> = {}
+ if (useBasic) {
+ if (!input.clientSecret) {
+ throw new Error('generic OAuth tokenAuthMethod=basic requires a client secret')
+ }
+ extraHeaders.authorization = basicAuthHeader(input.clientId, input.clientSecret)
+ }
+ if (useJson) {
+ const body: Record<string, string> = { grant_type: 'refresh_token' }
+ if (!useBasic) {
+ body.client_id = input.clientId
+ if (input.clientSecret) body.client_secret = input.clientSecret
+ }
+ body.refresh_token = input.refreshToken
+ return {
+ url,
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ accept: 'application/json',
+ ...extraHeaders,
+ },
+ body: JSON.stringify(withJsonResource(body, config.resource)),
+ }
+ }
+ // form + basic refresh: creds in the Basic header, omit from the body.
+ const request: TokenRequest = {
+ url,
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded',
+ accept: 'application/json',
+ ...extraHeaders,
+ },
+ body: urlEncode({ grant_type: 'refresh_token', refresh_token: input.refreshToken }),
+ }
+ return appendResource(request, config.resource)
+ },
+
+ parseTokenResponse: parseStandardOAuth2,
+ }
+}
diff --git a/control-api/src/oauth/tokenHelper.ts b/control-api/src/oauth/tokenHelper.ts
index e8732a9a4..88914d8e7 100644
--- a/control-api/src/oauth/tokenHelper.ts
+++ b/control-api/src/oauth/tokenHelper.ts
@@ -13,6 +13,7 @@ import {
} from './callback.js'
import {
type ParsedTokenResponse,
+ buildAdapterFromConfig,
buildRemoteRefreshRequest,
getOAuthProviderAdapter,
isKnownOAuthProvider,
@@ -112,6 +113,14 @@ export async function getAccessToken(
return refreshRemoteGrant(grant.refreshToken, decl, input, deps)
}
+ // Generic self-hosted lane (`source:'generic'`, DEC-28): same fail-closed
+ // no-refresh gate (D-8) and IP-pinned refresh POST (DEC-17) as the remote lane,
+ // but the request is composed from the CR knobs (`buildAdapterFromConfig`).
+ if (decl.generic) {
+ if (!decl.generic.supportsRefresh) return { kind: 'no_grant' }
+ return refreshGenericGrant(grant.refreshToken, decl, input, deps)
+ }
+
if (!isKnownOAuthProvider(decl.provider)) {
return { kind: 'unsupported_provider', provider: decl.provider }
}
@@ -287,3 +296,81 @@ async function refreshRemoteGrant(
: undefined
return { kind: 'ok', accessToken: parsed.accessToken, expiresAt }
}
+
+/**
+ * Generic-lane refresh (`source:'generic'`, `supportsRefresh:true`, DEC-28). The
+ * refresh request is composed from the CR knobs (`buildAdapterFromConfig`),
+ * credentials come from `secretSource` (public/k8s-secret), and the POST is
+ * IP-pinned to the pinned `refreshEndpoint` (defaulting to `tokenEndpoint`,
+ * DEC-17). Persists via the SAME `refreshOAuthGrantTokens` UPDATE (never
+ * resurrects a concurrently-deleted grant). `refreshToken` is already narrowed
+ * non-null by the caller.
+ */
+async function refreshGenericGrant(
+ refreshToken: string,
+ decl: OAuthClientDecl,
+ input: GetAccessTokenInput,
+ deps: GetAccessTokenDeps
+): Promise<GetAccessTokenResult> {
+ const generic = decl.generic
+ if (!generic) return { kind: 'no_grant' }
+ const credResult = await resolveRemoteClientCredential(
+ decl,
+ input.recipeNamespace,
+ input.recipeName,
+ {
+ db: deps.db,
+ encryptionKey: deps.encryptionKey,
+ secretReader: deps.secretReader,
+ }
+ )
+ if (!credResult.ok) return { kind: 'secret_missing', secret: credResult.secret }
+
+ const adapter = buildAdapterFromConfig(generic)
+ let refreshRequest: ReturnType<typeof adapter.buildRefreshRequest>
+ try {
+ // The build can throw (tokenAuthMethod=basic without a secret); wrap it into a
+ // typed fail-closed result rather than an opaque 500 (symmetric with baked).
+ refreshRequest = adapter.buildRefreshRequest({
+ refreshToken,
+ clientId: credResult.cred.clientId,
+ clientSecret: credResult.cred.clientSecret,
+ })
+ } catch (err) {
+ return { kind: 'refresh_failed', detail: (err as Error).message }
+ }
+
+ const posted = await postRemoteTokenForm(
+ refreshRequest.url,
+ 'spec.oauth.refreshEndpoint',
+ refreshRequest,
+ {
+ resolveDns: deps.resolveDns,
+ pinnedTransport: deps.pinnedTransport,
+ timeoutMs: deps.refreshTimeoutMs,
+ }
+ )
+ if (!posted.ok) return { kind: 'refresh_failed', status: posted.status, detail: posted.detail }
+
+ let parsed: ParsedTokenResponse
+ try {
+ parsed = adapter.parseTokenResponse(JSON.parse(posted.bodyText))
+ } catch (err) {
+ return { kind: 'refresh_failed', detail: (err as Error).message }
+ }
+
+ const refreshed = await refreshOAuthGrantTokens(deps.db, deps.encryptionKey, {
+ ...input,
+ provider: 'generic',
+ accessToken: parsed.accessToken,
+ refreshToken: parsed.refreshToken ?? refreshToken,
+ accessTokenExpiresInSec: parsed.expiresIn,
+ })
+ if (!refreshed.updated) return { kind: 'no_grant' }
+
+ const expiresAt =
+ typeof parsed.expiresIn === 'number'
+ ? new Date(Date.now() + parsed.expiresIn * 1000)
+ : undefined
+ return { kind: 'ok', accessToken: parsed.accessToken, expiresAt }
+}
diff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.ts
index 7d9917163..ec47d23c1 100644
--- a/control-api/src/routes/mcpOauth.ts
+++ b/control-api/src/routes/mcpOauth.ts
@@ -91,6 +91,15 @@ export function normalizeMcpServerOwnerDecl(
if (!resolved) return null
return { metadata: server.metadata, spec: { oauthClients: [resolved.decl] } }
}
+ // Generic self-hosted lane (`source:'generic'`, DEC-28): delegate to the SAME
+ // subject resolver (D4 — no drift with mint + callback) so the refresh reader
+ // gets the pinned `generic` routing + secretSource that `getAccessToken`
+ // branches on.
+ if (oauth.source === 'generic') {
+ const resolved = resolveServerOAuthSubject(server)
+ if (!resolved) return null
+ return { metadata: server.metadata, spec: { oauthClients: [resolved.decl] } }
+ }
// Baked lane (unchanged; a public baked client is tolerated per E-19.2).
if (typeof oauth.id !== 'string' || typeof oauth.provider !== 'string') return null
const clientIdRef = oauth.clientIdRef
diff --git a/control-api/test/oauth.authorizeUrl.generic.test.ts b/control-api/test/oauth.authorizeUrl.generic.test.ts
new file mode 100644
index 000000000..f57612dab
--- /dev/null
+++ b/control-api/test/oauth.authorizeUrl.generic.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it, vi } from 'vitest'
+import { type BuildAuthorizeUrlDeps, buildAuthorizeUrl } from '../src/oauth/authorizeUrlHelper.js'
+import type { McpServerOAuthReader, McpServerOAuthSubject } from '../src/oauth/callback.js'
+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'
+
+/**
+ * S3.2 / DEC-28 — the generic authorize-URL mint end-to-end through the helper.
+ * The URL is composed from the pinned `authorizationEndpoint` + wire knobs with
+ * the PUBLIC client_id (`oauth.id`); the knobs (usePkce/sendScope/scopeSeparator/
+ * includeResponseType/extraAuthorizeParams/resource) govern every param. No K8s
+ * Secret is read on the public path. Subject decl comes from the REAL resolver.
+ */
+
+const STATE_SECRET = 'test-state-hmac-secret-32-bytes-padding'
+const MCP_NS = 'mcp-server'
+const CLIENT_ID = 'my-generic-client'
+const REDIRECT_URI = 'https://control.example.com/api/v1/oauth-callback/my-generic-client'
+
+function genericSubject(overrides: Record<string, unknown> = {}): McpServerOAuthSubject {
+ const resolved = resolveServerOAuthSubject({
+ spec: {
+ contextRef: 'ctx-A',
+ oauth: {
+ source: 'generic',
+ id: CLIENT_ID,
+ authorizationEndpoint: 'https://idp.example.com/authorize',
+ tokenEndpoint: 'https://idp.example.com/token',
+ resource: 'https://api.example.com',
+ tokenRequestFormat: 'form',
+ tokenAuthMethod: 'body',
+ scopeSeparator: 'comma',
+ sendScope: true,
+ usePkce: true,
+ includeResponseType: true,
+ supportsRefresh: true,
+ grantScope: 'user',
+ scopes: ['read', 'write'],
+ extraAuthorizeParams: { audience: 'aud-1' },
+ ...overrides,
+ },
+ },
+ })
+ if (!resolved) throw new Error('fixture: generic resolve returned null')
+ return { namespace: MCP_NS, ...resolved }
+}
+
+async function mint(subject: McpServerOAuthSubject, secretRead = vi.fn(async () => ({}))) {
+ const mcpServerReader: McpServerOAuthReader = { read: vi.fn(async () => subject) }
+ const deps: BuildAuthorizeUrlDeps = {
+ recipeReader: { read: vi.fn(async () => null) },
+ mcpServerReader,
+ secretReader: { read: secretRead } as unknown as BuildAuthorizeUrlDeps['secretReader'],
+ stateSecret: STATE_SECRET,
+ }
+ const result = await buildAuthorizeUrl(
+ {
+ subjectKind: 'mcp',
+ mcpServerName: 'gen-server',
+ oauthClientId: CLIENT_ID,
+ userId: 'user-9',
+ grantKind: 'user',
+ background: false,
+ redirectUri: REDIRECT_URI,
+ },
+ deps
+ )
+ return { result, secretRead }
+}
+
+describe('buildAuthorizeUrl — generic mcp subject (DEC-28)', () => {
+ it('honors all knobs and reads no Secret on the public path', async () => {
+ const { result, secretRead } = await mint(genericSubject())
+ expect(result.kind).toBe('ok')
+ if (result.kind !== 'ok') return
+ const url = new URL(result.authorizeUrl)
+ expect(`${url.origin}${url.pathname}`).toBe('https://idp.example.com/authorize')
+ expect(url.searchParams.get('response_type')).toBe('code')
+ expect(url.searchParams.get('client_id')).toBe(CLIENT_ID)
+ expect(url.searchParams.get('redirect_uri')).toBe(REDIRECT_URI)
+ expect(url.searchParams.get('code_challenge_method')).toBe('S256')
+ expect(url.searchParams.get('code_challenge')).toBeTruthy()
+ expect(url.searchParams.get('resource')).toBe('https://api.example.com')
+ // scopeSeparator=comma
+ expect(url.searchParams.get('scope')).toBe('read,write')
+ expect(url.searchParams.get('audience')).toBe('aud-1')
+ expect(url.searchParams.get('state')).toBeTruthy()
+ expect(url.searchParams.get('client_secret')).toBeNull()
+ expect(secretRead).not.toHaveBeenCalled()
+ })
+
+ it('usePkce=false ⇒ no PKCE params and no challenge computed', async () => {
+ const { result } = await mint(genericSubject({ usePkce: false }))
+ expect(result.kind).toBe('ok')
+ if (result.kind !== 'ok') return
+ const url = new URL(result.authorizeUrl)
+ expect(url.searchParams.get('code_challenge')).toBeNull()
+ expect(url.searchParams.get('code_challenge_method')).toBeNull()
+ })
+
+ it('sendScope=false ⇒ no scope param', async () => {
+ const { result } = await mint(genericSubject({ sendScope: false }))
+ expect(result.kind).toBe('ok')
+ if (result.kind !== 'ok') return
+ expect(new URL(result.authorizeUrl).searchParams.get('scope')).toBeNull()
+ })
+})
diff --git a/control-api/test/oauth.callback.generic.test.ts b/control-api/test/oauth.callback.generic.test.ts
new file mode 100644
index 000000000..15cbbf2df
--- /dev/null
+++ b/control-api/test/oauth.callback.generic.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { PinnedRawResponse, PinnedTransportInput } from '../src/http/pinnedFetch.js'
+import {
+ type CallbackDeps,
+ type CallbackInput,
+ type McpServerOAuthReader,
+ type McpServerOAuthSubject,
+ handleOAuthCallback,
+} from '../src/oauth/callback.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'
+import { signOAuthState } from '../src/oauth/state.js'
+
+/**
+ * S3.2 / DEC-28 + DEC-17 — the GENERIC auth-code exchange goes through the
+ * IP-pinned `pinnedFetch`, never `fetchFn` (the operator-supplied endpoint is
+ * attacker-influenced). T5 invariants: a PUBLIC generic client sends NO
+ * client_secret; a CONFIDENTIAL client sends the client_secret read from the k8s
+ * Secret; the token POST connects to the validated IP and is never re-resolved.
+ *
+ * The CR bytes are inline: there is no install-producer for the generic carril in
+ * scope, so `spec.oauth` here is apiserver-stored CR data (the resolver's input).
+ * The REAL producers exercised are `resolveServerOAuthSubject` (the decl),
+ * `buildAdapterFromConfig` (the request) and `pinnedFetch` (the pin).
+ */
+
+const STATE_SECRET = 'test-state-hmac-secret-32-bytes-padding'
+const ENCRYPTION_KEY = deriveOAuthEncryptionKey(
+ '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'
+)
+const MCP_NS = 'mcp-server'
+const VALIDATED_IP = '93.184.216.34'
+const TOKEN_ENDPOINT = 'https://idp.example.com/token'
+const CLIENT_ID = 'my-generic-client'
+
+function genericCr(confidential: boolean) {
+ const oauth: Record<string, unknown> = {
+ source: 'generic',
+ id: CLIENT_ID,
+ authorizationEndpoint: 'https://idp.example.com/authorize',
+ tokenEndpoint: TOKEN_ENDPOINT,
+ resource: 'https://api.example.com',
+ tokenRequestFormat: 'form',
+ tokenAuthMethod: 'body',
+ scopeSeparator: 'space',
+ sendScope: true,
+ usePkce: true,
+ includeResponseType: true,
+ supportsRefresh: true,
+ grantScope: 'user',
+ scopes: ['read'],
+ }
+ if (confidential) {
+ oauth.clientIdRef = { name: 'gen-creds', key: 'client_id' }
+ oauth.clientSecretRef = { name: 'gen-creds', key: 'client_secret' }
+ }
+ return {
+ metadata: { name: 'gen-server', namespace: MCP_NS },
+ spec: { contextRef: 'ctx-A', auth: { type: 'oauth' }, oauth },
+ }
+}
+
+function genericReader(confidential: boolean): McpServerOAuthReader {
+ return {
+ read: vi.fn(async () => {
+ const resolved = resolveServerOAuthSubject(genericCr(confidential))
+ if (!resolved) return null
+ return { namespace: MCP_NS, ...resolved } as McpServerOAuthSubject
+ }),
+ }
+}
+
+function recordingTransport(responseJson: string, status = 200) {
+ const calls: {
+ url: string
+ connectedIP?: string
+ body?: string
+ headers: Record<string, string>
+ }[] = []
+ const transport = async (input: PinnedTransportInput): Promise<PinnedRawResponse> => {
+ let connectedIP: string | undefined
+ input.lookup(
+ 'idp.example.com',
+ { all: true } as never,
+ ((err, addrs) => {
+ if (!err && Array.isArray(addrs)) connectedIP = addrs[0]?.address
+ }) as never
+ )
+ calls.push({ url: input.url, connectedIP, body: input.body, headers: input.headers })
+ return { status, headers: { 'content-type': 'application/json' }, bodyText: responseJson }
+ }
+ return { transport, calls }
+}
+
+function genericInput(): CallbackInput {
+ return {
+ oauthClientId: CLIENT_ID,
+ code: 'AUTH_CODE',
+ state: signOAuthState(STATE_SECRET, {
+ subjectKind: 'mcp',
+ mcpServerName: 'gen-server',
+ userId: 'user-9',
+ oauthClientId: CLIENT_ID,
+ grantKind: 'user',
+ background: false,
+ } as Parameters<typeof signOAuthState>[1]),
+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/my-generic-client',
+ }
+}
+
+function baseDeps(overrides: Partial<CallbackDeps>): CallbackDeps {
+ return {
+ db: {
+ query: vi.fn().mockResolvedValue({ rows: [], rowCount: 1 }),
+ } as unknown as CallbackDeps['db'],
+ recipeReader: { read: vi.fn(async () => null) },
+ userContextsReader: vi.fn(async () => ({ contextIds: ['ctx-A'] })),
+ fetchFn: (async () => {
+ throw new Error('generic lane must NOT use fetchFn (DEC-17)')
+ }) as unknown as typeof fetch,
+ stateSecret: STATE_SECRET,
+ encryptionKey: ENCRYPTION_KEY,
+ ...overrides,
+ } as CallbackDeps
+}
+
+describe('handleOAuthCallback — generic exchange is IP-pinned (DEC-17)', () => {
+ it('PUBLIC: pinned POST to the validated IP, no client_secret, never fetchFn', async () => {
+ const { transport, calls } = recordingTransport(
+ JSON.stringify({ access_token: 'GEN-AT', refresh_token: 'GEN-RT', expires_in: 3600 })
+ )
+ const fetchFn = vi.fn(async () => {
+ throw new Error('generic lane must NOT use fetchFn')
+ })
+ const db = { query: vi.fn().mockResolvedValue({ rows: [], rowCount: 1 }) }
+ const deps = baseDeps({
+ db: db as unknown as CallbackDeps['db'],
+ mcpServerReader: genericReader(false),
+ secretReader: { read: vi.fn(async () => ({})) } as unknown as CallbackDeps['secretReader'],
+ fetchFn: fetchFn as unknown as typeof fetch,
+ resolveDns: async () => [VALIDATED_IP],
+ pinnedTransport: transport,
+ })
+
+ const result = await handleOAuthCallback(genericInput(), deps)
+
+ expect(result.kind).toBe('ok')
+ expect(fetchFn).not.toHaveBeenCalled()
+ expect(calls).toHaveLength(1)
+ expect(calls[0].url).toBe(TOKEN_ENDPOINT)
+ expect(calls[0].connectedIP).toBe(VALIDATED_IP)
+ expect(calls[0].body).toContain(`client_id=${CLIENT_ID}`)
+ expect(calls[0].body).toContain('code_verifier=')
+ expect(calls[0].body).not.toContain('client_secret=')
+
+ const [sql, params] = db.query.mock.calls[0] as [string, unknown[]]
+ expect(sql).toContain('INSERT INTO oauth_grants')
+ expect(params[4]).toBe(CLIENT_ID)
+ expect(params[5]).toBe('generic') // provider label
+ })
+
+ it('CONFIDENTIAL: sends the client_secret read from the k8s Secret', async () => {
+ const { transport, calls } = recordingTransport(
+ JSON.stringify({ access_token: 'GEN-AT', expires_in: 3600 })
+ )
+ const secretReader = {
+ read: vi.fn(async (name: string) => {
+ if (name === 'gen-creds') return { client_id: 'REAL-CID', client_secret: 'REAL-SECRET' }
+ return {}
+ }),
+ }
+ const deps = baseDeps({
+ mcpServerReader: genericReader(true),
+ secretReader: secretReader as unknown as CallbackDeps['secretReader'],
+ resolveDns: async () => [VALIDATED_IP],
+ pinnedTransport: transport,
+ })
+
+ const result = await handleOAuthCallback(genericInput(), deps)
+
+ expect(result.kind).toBe('ok')
+ expect(calls).toHaveLength(1)
+ expect(calls[0].connectedIP).toBe(VALIDATED_IP)
+ // The confidential client_id/secret come from the Secret, not oauth.id.
+ expect(calls[0].body).toContain('client_id=REAL-CID')
+ expect(calls[0].body).toContain('client_secret=REAL-SECRET')
+ })
+})
diff --git a/control-api/test/oauth.mcpServerOAuthSpec.generic.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.generic.test.ts
new file mode 100644
index 000000000..637fd744d
--- /dev/null
+++ b/control-api/test/oauth.mcpServerOAuthSpec.generic.test.ts
@@ -0,0 +1,181 @@
+import { describe, expect, it } from 'vitest'
+import {
+ type McpServerOAuthSpecInput,
+ resolveServerOAuth,
+ resolveServerOAuthSubject,
+} from '../src/oauth/mcpServerOAuthSpec.js'
+import { normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'
+
+/**
+ * S3.2 / DEC-28 — `resolveServerOAuthSubject` gains the generic self-hosted lane.
+ * There is NO install-producer for the generic carril in scope (deferred), so the
+ * `spec.oauth` bytes here represent apiserver-stored CR data (the untrusted INPUT
+ * to the resolver), not another layer's output — the resolver itself is the
+ * producer of the decl under test. This mirrors how the remote lane's callback /
+ * tokenHelper / authorizeUrl tests construct CR bytes inline.
+ *
+ * Invariants: public (neither ref) → secretSource:public + no refs; confidential
+ * (both refs) → secretSource:k8s-secret + refs carried; provider label is the
+ * synthetic 'generic' (never an ADAPTERS key); malformed knobs / half-declared
+ * refs fail closed to null; the baked lane is unaffected; and the refresh reader
+ * (`normalizeMcpServerOwnerDecl`) does not diverge from the subject resolver (D4).
+ */
+
+const KNOBS = {
+ source: 'generic' as const,
+ id: 'my-generic-client',
+ authorizationEndpoint: 'https://idp.example.com/authorize',
+ tokenEndpoint: 'https://idp.example.com/token',
+ tokenRequestFormat: 'form' as const,
+ tokenAuthMethod: 'body' as const,
+ scopeSeparator: 'space' as const,
+ sendScope: true,
+ usePkce: true,
+ includeResponseType: true,
+ supportsRefresh: true,
+ scopes: ['read', 'write'],
+ grantScope: 'user' as const,
+}
+
+function serverFrom(oauth: Record<string, unknown>, contextRef = 'ctx-a'): McpServerOAuthSpecInput {
+ return { spec: { oauth, contextRef } }
+}
+
+describe('resolveServerOAuthSubject — generic lane (DEC-28)', () => {
+ it('public (neither ref) → secretSource:public, no refs, provider label generic', () => {
+ const r = resolveServerOAuthSubject(serverFrom({ ...KNOBS }))
+ expect(r).not.toBeNull()
+ expect(r?.decl.id).toBe('my-generic-client')
+ expect(r?.decl.provider).toBe('generic')
+ expect(r?.decl.clientIdRef).toBeUndefined()
+ expect(r?.decl.clientSecretRef).toBeUndefined()
+ expect(r?.decl.secretSource).toEqual({ kind: 'public' })
+ expect(r?.decl.remote).toBeUndefined()
+ expect(r?.decl.generic).toMatchObject({
+ authorizationEndpoint: 'https://idp.example.com/authorize',
+ tokenEndpoint: 'https://idp.example.com/token',
+ tokenRequestFormat: 'form',
+ tokenAuthMethod: 'body',
+ scopeSeparator: 'space',
+ sendScope: true,
+ usePkce: true,
+ includeResponseType: true,
+ supportsRefresh: true,
+ })
+ })
+
+ it('confidential (both refs) → secretSource:k8s-secret, refs carried', () => {
+ const r = resolveServerOAuthSubject(
+ serverFrom({
+ ...KNOBS,
+ clientIdRef: { name: 'gen-creds', key: 'client_id' },
+ clientSecretRef: { name: 'gen-creds', key: 'client_secret' },
+ })
+ )
+ expect(r?.decl.clientIdRef).toEqual({ name: 'gen-creds', key: 'client_id' })
+ expect(r?.decl.clientSecretRef).toEqual({ name: 'gen-creds', key: 'client_secret' })
+ expect(r?.decl.secretSource).toEqual({
+ kind: 'k8s-secret',
+ clientIdRef: { name: 'gen-creds', key: 'client_id' },
+ clientSecretRef: { name: 'gen-creds', key: 'client_secret' },
+ })
+ })
+
+ it('optional knobs (refreshEndpoint, resource, extraAuthorizeParams) are carried', () => {
+ const r = resolveServerOAuthSubject(
+ serverFrom({
+ ...KNOBS,
+ refreshEndpoint: 'https://idp.example.com/refresh',
+ resource: 'https://api.example.com',
+ extraAuthorizeParams: { audience: 'aud-1', dropped: 42 },
+ })
+ )
+ expect(r?.decl.generic?.refreshEndpoint).toBe('https://idp.example.com/refresh')
+ expect(r?.decl.generic?.resource).toBe('https://api.example.com')
+ // Only string-valued extra params survive.
+ expect(r?.decl.generic?.extraAuthorizeParams).toEqual({ audience: 'aud-1' })
+ })
+
+ it('half-declared refs (only one) fail closed to null', () => {
+ expect(
+ resolveServerOAuthSubject(serverFrom({ ...KNOBS, clientIdRef: { name: 'x', key: 'y' } }))
+ ).toBeNull()
+ expect(
+ resolveServerOAuthSubject(serverFrom({ ...KNOBS, clientSecretRef: { name: 'x', key: 'y' } }))
+ ).toBeNull()
+ })
+
+ it('malformed wire enum fails closed to null', () => {
+ expect(
+ resolveServerOAuthSubject(serverFrom({ ...KNOBS, tokenRequestFormat: 'xml' }))
+ ).toBeNull()
+ expect(
+ resolveServerOAuthSubject(serverFrom({ ...KNOBS, tokenAuthMethod: 'header' }))
+ ).toBeNull()
+ expect(
+ resolveServerOAuthSubject(serverFrom({ ...KNOBS, scopeSeparator: 'semicolon' }))
+ ).toBeNull()
+ })
+
+ it('missing required endpoint fails closed to null', () => {
+ const { tokenEndpoint: _drop, ...noToken } = KNOBS
+ expect(resolveServerOAuthSubject(serverFrom(noToken))).toBeNull()
+ })
+
+ it('resolveServerOAuth keys the grant coordinate by oauth.id (grantScope respected)', () => {
+ const r = resolveServerOAuth(serverFrom({ ...KNOBS, grantScope: 'context' }))
+ expect(r).toEqual({
+ oauthClientId: 'my-generic-client',
+ grantScope: 'context',
+ contextRef: 'ctx-a',
+ })
+ })
+})
+
+describe('baked lane is unaffected by the generic branch', () => {
+ it('a baked confidential server still resolves to the confidential-K8s decl', () => {
+ const r = resolveServerOAuthSubject(
+ serverFrom({
+ id: 'google-drive',
+ provider: 'google',
+ clientIdRef: { name: 'creds', key: 'client-id' },
+ clientSecretRef: { name: 'creds', key: 'client-secret' },
+ scopes: ['a'],
+ backgroundAccess: true,
+ })
+ )
+ expect(r?.decl.provider).toBe('google')
+ expect('generic' in (r?.decl ?? {})).toBe(false)
+ expect('secretSource' in (r?.decl ?? {})).toBe(false)
+ })
+})
+
+describe('normalizeMcpServerOwnerDecl (refresh reader) matches the subject resolver (D4)', () => {
+ it('generic public: carries the generic routing + secretSource:public', () => {
+ const normalized = normalizeMcpServerOwnerDecl({
+ metadata: { name: 'gen-server', namespace: 'mcp-server' },
+ spec: { oauth: { ...KNOBS } as never },
+ })
+ const decl = normalized?.spec?.oauthClients?.[0]
+ expect(decl?.id).toBe('my-generic-client')
+ expect(decl?.generic?.tokenEndpoint).toBe('https://idp.example.com/token')
+ expect(decl?.secretSource).toEqual({ kind: 'public' })
+ })
+
+ it('generic confidential: carries secretSource:k8s-secret', () => {
+ const normalized = normalizeMcpServerOwnerDecl({
+ spec: {
+ oauth: {
+ ...KNOBS,
+ clientIdRef: { name: 'gen-creds', key: 'client_id' },
+ clientSecretRef: { name: 'gen-creds', key: 'client_secret' },
+ } as never,
+ },
+ })
+ expect(normalized?.spec?.oauthClients?.[0]?.secretSource).toEqual({
+ kind: 'k8s-secret',
+ clientIdRef: { name: 'gen-creds', key: 'client_id' },
+ clientSecretRef: { name: 'gen-creds', key: 'client_secret' },
+ })
+ })
+})
diff --git a/control-api/test/oauth.providers.generic.test.ts b/control-api/test/oauth.providers.generic.test.ts
new file mode 100644
index 000000000..4c7868587
--- /dev/null
+++ b/control-api/test/oauth.providers.generic.test.ts
@@ -0,0 +1,294 @@
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import {
+ type GenericAdapterConfig,
+ buildAdapterFromConfig,
+ buildRemoteRefreshRequest,
+ buildRemoteTokenRequest,
+ getOAuthProviderAdapter,
+} from '../src/oauth/providers.js'
+
+/**
+ * S3.2 / DEC-28 — `buildAdapterFromConfig` is the PURE knob→wire composer for the
+ * generic self-hosted OAuth lane. T4: assert the OBSERVABLE emitted request bytes
+ * / authorize URL. T2 (fast-check): the mapping (config, input) → request is a
+ * pure function; a config that re-expresses a baked adapter's form shape emits the
+ * SAME bytes as the real remote form producer (`buildRemoteTokenRequest`), and the
+ * knob branches (form/json, body/basic, scopeSeparator, sendScope) each select one
+ * fixed behavior. The 8 baked adapters and the provider enum stay byte-frozen
+ * (pinned by `oauth.providers.golden.test.ts`); here we only prove the composer.
+ */
+
+const AUTH_ENDPOINT = 'https://idp.example.com/authorize'
+const TOKEN_ENDPOINT = 'https://idp.example.com/token'
+const RESOURCE = 'https://api.example.com'
+
+function cfg(overrides: Partial<GenericAdapterConfig> = {}): GenericAdapterConfig {
+ return {
+ authorizationEndpoint: AUTH_ENDPOINT,
+ tokenEndpoint: TOKEN_ENDPOINT,
+ tokenRequestFormat: 'form',
+ tokenAuthMethod: 'body',
+ scopeSeparator: 'space',
+ sendScope: true,
+ usePkce: true,
+ includeResponseType: true,
+ ...overrides,
+ }
+}
+
+const TOKEN_INPUT = {
+ code: 'CODE',
+ clientId: 'CID',
+ clientSecret: 'SEC',
+ redirectUri: 'https://cb.example.com/generic',
+ codeVerifier: 'VER',
+}
+
+describe('buildAdapterFromConfig.buildAuthorizeUrl (knob-gated, T4)', () => {
+ const AUTH_INPUT = {
+ clientId: 'CID',
+ redirectUri: 'https://cb.example.com/generic',
+ state: 'signed-state',
+ scopes: ['read', 'write'],
+ codeChallenge: 'CHAL',
+ }
+
+ it('honors usePkce=true / sendScope=true (space) / includeResponseType=true + resource', () => {
+ const url = new URL(
+ buildAdapterFromConfig(cfg({ resource: RESOURCE })).buildAuthorizeUrl(AUTH_INPUT)
+ )
+ expect(`${url.origin}${url.pathname}`).toBe(AUTH_ENDPOINT)
+ expect(url.searchParams.get('response_type')).toBe('code')
+ expect(url.searchParams.get('client_id')).toBe('CID')
+ expect(url.searchParams.get('code_challenge')).toBe('CHAL')
+ expect(url.searchParams.get('code_challenge_method')).toBe('S256')
+ expect(url.searchParams.get('scope')).toBe('read write')
+ expect(url.searchParams.get('resource')).toBe(RESOURCE)
+ })
+
+ it('usePkce=false ⇒ no code_challenge even when a challenge is supplied', () => {
+ const url = new URL(
+ buildAdapterFromConfig(cfg({ usePkce: false })).buildAuthorizeUrl(AUTH_INPUT)
+ )
+ expect(url.searchParams.get('code_challenge')).toBeNull()
+ expect(url.searchParams.get('code_challenge_method')).toBeNull()
+ })
+
+ it('sendScope=false ⇒ no scope param', () => {
+ const url = new URL(
+ buildAdapterFromConfig(cfg({ sendScope: false })).buildAuthorizeUrl(AUTH_INPUT)
+ )
+ expect(url.searchParams.get('scope')).toBeNull()
+ })
+
+ it('scopeSeparator=comma joins scopes with a comma', () => {
+ const url = new URL(
+ buildAdapterFromConfig(cfg({ scopeSeparator: 'comma' })).buildAuthorizeUrl(AUTH_INPUT)
+ )
+ expect(url.searchParams.get('scope')).toBe('read,write')
+ })
+
+ it('includeResponseType=false ⇒ no response_type param', () => {
+ const url = new URL(
+ buildAdapterFromConfig(cfg({ includeResponseType: false })).buildAuthorizeUrl(AUTH_INPUT)
+ )
+ expect(url.searchParams.get('response_type')).toBeNull()
+ })
+
+ it('merges extraAuthorizeParams but reserved params always win (no clobber of state/PKCE)', () => {
+ const url = new URL(
+ buildAdapterFromConfig(
+ cfg({ extraAuthorizeParams: { audience: 'aud-1', state: 'ATTACKER', prompt: 'consent' } })
+ ).buildAuthorizeUrl(AUTH_INPUT)
+ )
+ expect(url.searchParams.get('audience')).toBe('aud-1')
+ expect(url.searchParams.get('prompt')).toBe('consent')
+ // extraAuthorizeParams cannot override the signed state binding.
+ expect(url.searchParams.get('state')).toBe('signed-state')
+ })
+
+ it('appends to an authorize endpoint that already has a query string', () => {
+ const url = buildAdapterFromConfig(
+ cfg({ authorizationEndpoint: 'https://idp.example.com/authorize?tenant=acme' })
+ ).buildAuthorizeUrl(AUTH_INPUT)
+ expect(url).toContain('?tenant=acme&')
+ expect(url).toContain('client_id=CID')
+ })
+})
+
+describe('buildAdapterFromConfig.buildTokenRequest (format/authMethod, T4)', () => {
+ it('form + body → standard form shape verbatim (byte-identical to the remote form producer)', () => {
+ const req = buildAdapterFromConfig(cfg({ resource: RESOURCE })).buildTokenRequest(TOKEN_INPUT)
+ expect(req.headers['content-type']).toBe('application/x-www-form-urlencoded')
+ expect(req.body).toBe(buildRemoteTokenRequest(TOKEN_ENDPOINT, TOKEN_INPUT, RESOURCE).body)
+ expect(req.body).toContain('client_secret=SEC')
+ expect(req.body).toContain('code_verifier=VER')
+ expect(req.body.endsWith('&resource=https%3A%2F%2Fapi.example.com')).toBe(true)
+ })
+
+ it('form + basic → creds in the Authorization header, omitted from the body', () => {
+ const req = buildAdapterFromConfig(cfg({ tokenAuthMethod: 'basic' })).buildTokenRequest(
+ TOKEN_INPUT
+ )
+ expect(req.headers.authorization).toBe(`Basic ${Buffer.from('CID:SEC').toString('base64')}`)
+ expect(req.headers['content-type']).toBe('application/x-www-form-urlencoded')
+ expect(req.body).not.toContain('client_secret')
+ expect(req.body).not.toContain('client_id')
+ expect(req.body).toContain('code_verifier=VER')
+ })
+
+ it('json + body → JSON body with client creds', () => {
+ const req = buildAdapterFromConfig(
+ cfg({ tokenRequestFormat: 'json', resource: RESOURCE })
+ ).buildTokenRequest(TOKEN_INPUT)
+ expect(req.headers['content-type']).toBe('application/json')
+ expect(JSON.parse(req.body)).toEqual({
+ grant_type: 'authorization_code',
+ client_id: 'CID',
+ client_secret: 'SEC',
+ code: 'CODE',
+ redirect_uri: 'https://cb.example.com/generic',
+ code_verifier: 'VER',
+ resource: RESOURCE,
+ })
+ })
+
+ it('json + basic → JSON body without creds + Basic header', () => {
+ const req = buildAdapterFromConfig(
+ cfg({ tokenRequestFormat: 'json', tokenAuthMethod: 'basic' })
+ ).buildTokenRequest(TOKEN_INPUT)
+ expect(req.headers.authorization).toBe(`Basic ${Buffer.from('CID:SEC').toString('base64')}`)
+ const parsed = JSON.parse(req.body)
+ expect(parsed.client_secret).toBeUndefined()
+ expect(parsed.client_id).toBeUndefined()
+ expect(parsed.code).toBe('CODE')
+ })
+
+ it('public client (no secret, body) omits client_secret', () => {
+ const req = buildAdapterFromConfig(cfg()).buildTokenRequest({
+ code: 'CODE',
+ clientId: 'CID',
+ redirectUri: 'https://cb.example.com/generic',
+ codeVerifier: 'VER',
+ })
+ expect(req.body).not.toContain('client_secret')
+ expect(req.body).toContain('client_id=CID')
+ })
+
+ it('tokenAuthMethod=basic without a secret fails closed (throws)', () => {
+ expect(() =>
+ buildAdapterFromConfig(cfg({ tokenAuthMethod: 'basic' })).buildTokenRequest({
+ code: 'CODE',
+ clientId: 'CID',
+ redirectUri: 'https://cb.example.com/generic',
+ })
+ ).toThrow(/basic requires a client secret/)
+ })
+})
+
+describe('buildAdapterFromConfig.buildRefreshRequest', () => {
+ const REFRESH_INPUT = { refreshToken: 'RT', clientId: 'CID', clientSecret: 'SEC' }
+
+ it('form + body → standard refresh shape (byte-identical to the remote form producer)', () => {
+ const req = buildAdapterFromConfig(cfg({ resource: RESOURCE })).buildRefreshRequest(
+ REFRESH_INPUT
+ )
+ expect(req.url).toBe(TOKEN_ENDPOINT)
+ expect(req.body).toBe(buildRemoteRefreshRequest(TOKEN_ENDPOINT, REFRESH_INPUT, RESOURCE).body)
+ })
+
+ it('refreshEndpoint overrides tokenEndpoint as the POST target', () => {
+ const req = buildAdapterFromConfig(
+ cfg({ refreshEndpoint: 'https://idp.example.com/refresh' })
+ ).buildRefreshRequest(REFRESH_INPUT)
+ expect(req.url).toBe('https://idp.example.com/refresh')
+ })
+
+ it('json + basic refresh → JSON body without creds + Basic header', () => {
+ const req = buildAdapterFromConfig(
+ cfg({ tokenRequestFormat: 'json', tokenAuthMethod: 'basic' })
+ ).buildRefreshRequest(REFRESH_INPUT)
+ expect(req.headers.authorization).toBe(`Basic ${Buffer.from('CID:SEC').toString('base64')}`)
+ expect(JSON.parse(req.body)).toEqual({ grant_type: 'refresh_token', refresh_token: 'RT' })
+ })
+})
+
+// ─── T2 property-based: the composer is a pure (config,input)→request function ──
+describe('buildAdapterFromConfig — property-based (T2)', () => {
+ const arbInput = fc.record({
+ code: fc.string({ minLength: 1 }),
+ clientId: fc.string({ minLength: 1 }),
+ clientSecret: fc.option(fc.string({ minLength: 1 }), { nil: undefined }),
+ redirectUri: fc.webUrl(),
+ codeVerifier: fc.option(fc.string({ minLength: 1 }), { nil: undefined }),
+ })
+ const arbResource = fc.option(fc.webUrl(), { nil: undefined })
+
+ it('form+body token request re-expresses the baked/remote form shape for any input', () => {
+ fc.assert(
+ fc.property(arbInput, arbResource, (input, resource) => {
+ const generic = buildAdapterFromConfig(cfg({ resource })).buildTokenRequest(input)
+ const remote = buildRemoteTokenRequest(TOKEN_ENDPOINT, input, resource)
+ return generic.body === remote.body && generic.url === remote.url
+ })
+ )
+ })
+
+ it('scopeSeparator selects one fixed join; sendScope=false always omits scope', () => {
+ fc.assert(
+ fc.property(
+ fc.array(
+ fc.string({ minLength: 1 }).filter(s => !/[\s,&=?#]/.test(s)),
+ { minLength: 1, maxLength: 6 }
+ ),
+ fc.constantFrom<'space' | 'comma'>('space', 'comma'),
+ fc.boolean(),
+ (scopes, scopeSeparator, sendScope) => {
+ const url = new URL(
+ buildAdapterFromConfig(cfg({ scopeSeparator, sendScope })).buildAuthorizeUrl({
+ clientId: 'CID',
+ redirectUri: 'https://cb.example.com/generic',
+ state: 'S',
+ scopes,
+ codeChallenge: 'C',
+ })
+ )
+ const scope = url.searchParams.get('scope')
+ if (!sendScope) return scope === null
+ return scope === scopes.join(scopeSeparator === 'comma' ? ',' : ' ')
+ }
+ )
+ )
+ })
+
+ it('is deterministic — identical (config,input) yields identical bytes', () => {
+ fc.assert(
+ fc.property(
+ arbInput,
+ fc.constantFrom<'form' | 'json'>('form', 'json'),
+ fc.constantFrom<'body' | 'basic'>('body', 'basic'),
+ (input, tokenRequestFormat, tokenAuthMethod) => {
+ // basic needs a secret; skip the fail-closed combination for determinism check.
+ const usableInput =
+ tokenAuthMethod === 'basic' ? { ...input, clientSecret: 'SEC' } : input
+ const a = buildAdapterFromConfig(cfg({ tokenRequestFormat, tokenAuthMethod }))
+ const b = buildAdapterFromConfig(cfg({ tokenRequestFormat, tokenAuthMethod }))
+ return a.buildTokenRequest(usableInput).body === b.buildTokenRequest(usableInput).body
+ }
+ )
+ )
+ })
+})
+
+describe('the baked adapters are untouched by the generic composer', () => {
+ it('salesforce token body carries no resource and is unchanged', () => {
+ const body = getOAuthProviderAdapter('salesforce').buildTokenRequest({
+ code: 'thecode',
+ clientId: 'cid',
+ clientSecret: 'csec',
+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/provider',
+ }).body
+ expect(body).not.toContain('resource=')
+ })
+})
diff --git a/control-api/test/oauth.tokenHelper.generic.test.ts b/control-api/test/oauth.tokenHelper.generic.test.ts
new file mode 100644
index 000000000..6090d8005
--- /dev/null
+++ b/control-api/test/oauth.tokenHelper.generic.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { PinnedRawResponse, PinnedTransportInput } from '../src/http/pinnedFetch.js'
+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'
+import * as store from '../src/oauth/store.js'
+import { getAccessToken } from '../src/oauth/tokenHelper.js'
+
+/**
+ * S3.2 / DEC-28 + D-8 — the GENERIC refresh goes through the IP-pinned transport
+ * (never `fetchFn`), targets the pinned refreshEndpoint, and a
+ * `supportsRefresh:false` server NEVER attempts a refresh (fail-closed →
+ * `no_grant` → the desktop re-consents). The owner decl is produced by the REAL
+ * `resolveServerOAuthSubject`.
+ */
+
+const ENCRYPTION_KEY = Buffer.alloc(32)
+const TOKEN_ENDPOINT = 'https://idp.example.com/token'
+const REFRESH_ENDPOINT = 'https://idp.example.com/refresh'
+const VALIDATED_IP = '93.184.216.34'
+const CLIENT_ID = 'my-generic-client'
+
+function genericOwnerDecl(supportsRefresh: boolean, refreshEndpoint?: string) {
+ const resolved = resolveServerOAuthSubject({
+ spec: {
+ contextRef: 'ctx-A',
+ oauth: {
+ source: 'generic',
+ id: CLIENT_ID,
+ authorizationEndpoint: 'https://idp.example.com/authorize',
+ tokenEndpoint: TOKEN_ENDPOINT,
+ refreshEndpoint,
+ resource: 'https://api.example.com',
+ tokenRequestFormat: 'form',
+ tokenAuthMethod: 'body',
+ scopeSeparator: 'space',
+ sendScope: true,
+ usePkce: true,
+ includeResponseType: true,
+ supportsRefresh,
+ grantScope: 'user',
+ scopes: ['read'],
+ },
+ },
+ })
+ if (!resolved) throw new Error('fixture: generic resolve returned null')
+ return { spec: { oauthClients: [resolved.decl] } }
+}
+
+function staleGrant() {
+ return {
+ provider: 'generic',
+ accessToken: 'OLD-AT',
+ refreshToken: 'GEN-RT',
+ accessTokenExpiresAt: new Date(Date.now() - 60_000),
+ } as unknown as Awaited<ReturnType<typeof store.getOAuthGrant>>
+}
+
+function recordingTransport(responseJson: string) {
+ const calls: { url: string; connectedIP?: string; body?: string }[] = []
+ const transport = async (input: PinnedTransportInput): Promise<PinnedRawResponse> => {
+ let connectedIP: string | undefined
+ input.lookup(
+ 'idp.example.com',
+ { all: true } as never,
+ ((err, addrs) => {
+ if (!err && Array.isArray(addrs)) connectedIP = addrs[0]?.address
+ }) as never
+ )
+ calls.push({ url: input.url, connectedIP, body: input.body })
+ return { status: 200, headers: { 'content-type': 'application/json' }, bodyText: responseJson }
+ }
+ return { transport, calls }
+}
+
+const KEY = {
+ grantKind: 'user' as const,
+ recipeNamespace: 'mcp-server',
+ recipeName: 'gen-server',
+ userId: 'user-9',
+ oauthClientId: CLIENT_ID,
+}
+
+describe('getAccessToken — generic refresh is IP-pinned (DEC-17)', () => {
+ it('refreshes a stale generic grant via pinnedTransport to the validated IP, not fetchFn', async () => {
+ vi.spyOn(store, 'getOAuthGrant').mockResolvedValue(staleGrant())
+ const refreshSpy = vi
+ .spyOn(store, 'refreshOAuthGrantTokens')
+ .mockResolvedValue({ updated: true } as never)
+ const { transport, calls } = recordingTransport(
+ JSON.stringify({ access_token: 'NEW-AT', expires_in: 3600 })
+ )
+ const fetchFn = vi.fn(async () => {
+ throw new Error('generic refresh must NOT use fetchFn')
+ })
+
+ const result = await getAccessToken(KEY, {
+ db: { query: async () => ({ rows: [] }) } as never,
+ recipeReader: { read: async () => genericOwnerDecl(true) },
+ secretReader: { read: async () => ({}) },
+ fetchFn: fetchFn as unknown as typeof fetch,
+ encryptionKey: ENCRYPTION_KEY,
+ resolveDns: async () => [VALIDATED_IP],
+ pinnedTransport: transport,
+ })
+
+ expect(result).toEqual({ kind: 'ok', accessToken: 'NEW-AT', expiresAt: expect.any(Date) })
+ expect(fetchFn).not.toHaveBeenCalled()
+ expect(calls).toHaveLength(1)
+ expect(calls[0].url).toBe(TOKEN_ENDPOINT)
+ expect(calls[0].connectedIP).toBe(VALIDATED_IP)
+ expect(calls[0].body).toContain('grant_type=refresh_token')
+ expect(refreshSpy).toHaveBeenCalledWith(
+ expect.anything(),
+ ENCRYPTION_KEY,
+ expect.objectContaining({ provider: 'generic' })
+ )
+ vi.restoreAllMocks()
+ })
+
+ it('targets the pinned refreshEndpoint when set (defaults to tokenEndpoint otherwise)', async () => {
+ vi.spyOn(store, 'getOAuthGrant').mockResolvedValue(staleGrant())
+ vi.spyOn(store, 'refreshOAuthGrantTokens').mockResolvedValue({ updated: true } as never)
+ const { transport, calls } = recordingTransport(JSON.stringify({ access_token: 'NEW-AT' }))
+
+ await getAccessToken(KEY, {
+ db: { query: async () => ({ rows: [] }) } as never,
+ recipeReader: { read: async () => genericOwnerDecl(true, REFRESH_ENDPOINT) },
+ secretReader: { read: async () => ({}) },
+ fetchFn: (async () => {
+ throw new Error('nope')
+ }) as unknown as typeof fetch,
+ encryptionKey: ENCRYPTION_KEY,
+ resolveDns: async () => [VALIDATED_IP],
+ pinnedTransport: transport,
+ })
+
+ expect(calls[0].url).toBe(REFRESH_ENDPOINT)
+ vi.restoreAllMocks()
+ })
+})
+
+describe('getAccessToken — generic no-refresh is fail-closed (D-8)', () => {
+ it('never attempts a refresh when supportsRefresh=false (returns no_grant)', async () => {
+ vi.spyOn(store, 'getOAuthGrant').mockResolvedValue(staleGrant())
+ const { transport, calls } = recordingTransport('{}')
+
+ const result = await getAccessToken(KEY, {
+ db: { query: async () => ({ rows: [] }) } as never,
+ recipeReader: { read: async () => genericOwnerDecl(false) },
+ secretReader: { read: async () => ({}) },
+ fetchFn: (async () => {
+ throw new Error('no refresh must be attempted')
+ }) as unknown as typeof fetch,
+ encryptionKey: ENCRYPTION_KEY,
+ pinnedTransport: transport,
+ })
+
+ expect(result).toEqual({ kind: 'no_grant' })
+ expect(calls).toHaveLength(0)
+ vi.restoreAllMocks()
+ })
+})
diff --git a/control-api/test/services.access.mcpConnectors.generic.test.ts b/control-api/test/services.access.mcpConnectors.generic.test.ts
new file mode 100644
index 000000000..16fd0d4de
--- /dev/null
+++ b/control-api/test/services.access.mcpConnectors.generic.test.ts
@@ -0,0 +1,134 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { DbClient } from '../src/db.js'
+import type { K8sGateway } from '../src/k8s.js'
+import type { GetOAuthGrantInput } from '../src/oauth/store.js'
+
+/**
+ * S3.2 / DEC-28 — point 7: `classifyConnector` handles a GENERIC connector
+ * UNCHANGED. A generic server has `auth.type==='oauth'` + `spec.oauth.id` (so
+ * `resolveServerOAuth` is non-null → it is an oauth connector) but NO
+ * `spec.oauth.provider` (so the panel provider label is omitted, exactly like the
+ * remote lane today). The tri-state comes solely from grant presence via the same
+ * flavored key derivation the rpc-proxy gate uses (D4). We mock only the
+ * `oauthGrantExists` boolean, as the sibling connector suites do.
+ */
+const grantExists = vi.fn<(db: unknown, input: GetOAuthGrantInput) => Promise<boolean>>()
+vi.mock('../src/oauth/store.js', async importActual => {
+ const actual = await importActual<typeof import('../src/oauth/store.js')>()
+ return {
+ ...actual,
+ oauthGrantExists: (db: unknown, input: GetOAuthGrantInput) => grantExists(db, input),
+ }
+})
+
+const { resolveConnectorsForAgents } = await import('../src/services/access/mcpInvocable.js')
+
+const NS = 'mcp-server'
+const HOSTS_NS = 'mcp-host'
+const USER = 'user-caller'
+const DB: DbClient = { query: async () => ({ rows: [], rowCount: 0 }) }
+
+type Resource = Record<string, unknown>
+
+function gateway(resources: {
+ contexts?: Resource[]
+ mcpservers?: Resource[]
+ hosts?: Resource[]
+}): K8sGateway {
+ const listResource = vi.fn(async (plural: string) => {
+ if (plural === 'contexts') return resources.contexts ?? []
+ if (plural === 'mcpservers') return resources.mcpservers ?? []
+ if (plural === 'hosts') return resources.hosts ?? []
+ return []
+ })
+ const getResource = vi.fn(async (plural: string, name: string) => {
+ if (plural !== 'hosts') return undefined
+ const found = resources.hosts?.find(
+ r => (r.metadata as { name?: string } | undefined)?.name === name
+ )
+ if (!found) throw Object.assign(new Error('not-found'), { statusCode: 404 })
+ return found
+ })
+ return {
+ listResource,
+ getResource,
+ createResource: vi.fn(),
+ updateResource: vi.fn(),
+ deleteResource: vi.fn(),
+ } as unknown as K8sGateway
+}
+
+const host = (name: string, contextRef: string) => ({
+ metadata: { name, namespace: HOSTS_NS },
+ spec: { contextRef },
+})
+const ctx = (contextId: string, servers: string[]) => ({ spec: { contextId, mcpServers: servers } })
+
+// A generic self-hosted oauth server: auth.type oauth, oauth.source generic,
+// oauth.id present, NO provider.
+const genericServer = (name: string, grantScope: 'user' | 'context', contextRef: string) => ({
+ metadata: { name },
+ spec: {
+ enabled: true,
+ auth: { type: 'oauth' },
+ transport: { url: `http://${name}.${NS}.svc:3000/mcp` },
+ contextRef,
+ oauth: {
+ source: 'generic',
+ id: `${name}-client`,
+ authorizationEndpoint: 'https://idp.example.com/authorize',
+ tokenEndpoint: 'https://idp.example.com/token',
+ tokenRequestFormat: 'form',
+ tokenAuthMethod: 'body',
+ scopeSeparator: 'space',
+ sendScope: true,
+ usePkce: true,
+ includeResponseType: true,
+ supportsRefresh: true,
+ grantScope,
+ },
+ },
+})
+
+beforeEach(() => grantExists.mockReset())
+
+async function connectorsFor(g: K8sGateway, agentNames: string[]) {
+ return resolveConnectorsForAgents(
+ g,
+ { mcpServersNamespace: NS, hostsNamespace: HOSTS_NS, agentNames, userId: USER },
+ DB
+ )
+}
+
+describe('classifyConnector — generic connector (DEC-28, point 7)', () => {
+ it('a granted generic user server → authorized, oauth-user, NO provider label', async () => {
+ grantExists.mockResolvedValue(true)
+ const g = gateway({
+ hosts: [host('agent-1', 'ctx-1')],
+ contexts: [ctx('ctx-1', ['gen-srv'])],
+ mcpservers: [genericServer('gen-srv', 'user', 'ctx-1')],
+ })
+ const [agent] = await connectorsFor(g, ['agent-1'])
+ expect(agent.connectors).toHaveLength(1)
+ const c = agent.connectors[0]
+ expect(c.name).toBe('gen-srv')
+ expect(c.status).toBe('authorized')
+ expect(c.authKind).toBe('oauth-user')
+ expect(c.grantScope).toBe('user')
+ expect(c.provider).toBeUndefined()
+ })
+
+ it('an un-granted generic server → requires_setup (never authorized)', async () => {
+ grantExists.mockResolvedValue(false)
+ const g = gateway({
+ hosts: [host('agent-1', 'ctx-1')],
+ contexts: [ctx('ctx-1', ['gen-srv'])],
+ mcpservers: [genericServer('gen-srv', 'context', 'ctx-1')],
+ })
+ const [agent] = await connectorsFor(g, ['agent-1'])
+ const c = agent.connectors[0]
+ expect(c.status).toBe('requires_setup')
+ expect(c.authKind).toBe('oauth-context')
+ expect(c.provider).toBeUndefined()
+ })
+})