Skip to content

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

TypeScript

feat(control-api): wire OAuth install-from-UI backend (S1-U2/U3)

Diego Zacariasc3ba28411572
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 5d2665b68..c76225829 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.587",
+ "version": "0.1.588",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.587",
+ "version": "0.1.588",
"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 9ac84821c..d3cc0edd9 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.587",
+ "version": "0.1.588",
"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/providers.ts b/control-api/src/oauth/providers.ts
index c7da71e62..1a0432cdf 100644
--- a/control-api/src/oauth/providers.ts
+++ b/control-api/src/oauth/providers.ts
@@ -561,3 +561,56 @@ export const KNOWN_OAUTH_PROVIDERS: ReadonlySet<OAuthProvider> = new Set(
export function isKnownOAuthProvider(value: string): value is OAuthProvider {
return KNOWN_OAUTH_PROVIDERS.has(value as OAuthProvider)
}
+
+// ─── Credential manifest (install-from-UI, D-B1) ─────────────────────────
+//
+// The manifest declares WHICH fields the operator fills in the install form for
+// a given provider — the control-ui form is rendered from it. It is deliberately
+// kept OUT of the adapter objects above: those encode the wire flow and are
+// golden-frozen (DEC-3), so the install-UI metadata lives beside them, keyed by
+// provider, instead of mutating the frozen literals.
+//
+// The `name` of each field is the CANONICAL Secret key control-api writes in the
+// managed-Secret mode (`OAUTH_CLIENT_ID_KEY`/`OAUTH_CLIENT_SECRET_KEY` in the
+// install saga), so the form field and the stored key never drift.
+
+/** One field the operator supplies in the install-from-UI credential form. */
+export interface OAuthCredentialField {
+ /** Field id AND canonical Secret key for the managed-Secret mode. */
+ name: string
+ /** Human label rendered by control-ui. */
+ label: string
+ /** Masked in the UI and never echoed back (client_secret). */
+ secret: boolean
+ required: boolean
+ help?: string
+}
+
+// All 8 baked providers are confidential clients (the mcpserver CRD requires
+// clientSecretRef), so each asks for client_id + client_secret and nothing more:
+// none of them needs a tenant/instance field (google/microsoft use the common
+// authority, salesforce/slack/etc. have fixed endpoints). The public-client
+// variant + dynamic manifest is 'generic' (S3), out of Slice 1 scope.
+const CONFIDENTIAL_CLIENT_MANIFEST: ReadonlyArray<OAuthCredentialField> = [
+ { name: 'client_id', label: 'Client ID', secret: false, required: true },
+ { name: 'client_secret', label: 'Client Secret', secret: true, required: true },
+]
+
+const CREDENTIAL_MANIFESTS: Record<OAuthProvider, ReadonlyArray<OAuthCredentialField>> = {
+ salesforce: CONFIDENTIAL_CLIENT_MANIFEST,
+ slack: CONFIDENTIAL_CLIENT_MANIFEST,
+ notion: CONFIDENTIAL_CLIENT_MANIFEST,
+ 'microsoft-graph': CONFIDENTIAL_CLIENT_MANIFEST,
+ google: CONFIDENTIAL_CLIENT_MANIFEST,
+ monday: CONFIDENTIAL_CLIENT_MANIFEST,
+ clickup: CONFIDENTIAL_CLIENT_MANIFEST,
+ vercel: CONFIDENTIAL_CLIENT_MANIFEST,
+}
+
+/**
+ * The credential-form manifest for a baked provider. Returns a defensive copy so
+ * callers (and the HTTP layer) cannot mutate the shared definition.
+ */
+export function getCredentialManifest(provider: OAuthProvider): OAuthCredentialField[] {
+ return CREDENTIAL_MANIFESTS[provider].map(field => ({ ...field }))
+}
diff --git a/control-api/src/routes/admin/index.ts b/control-api/src/routes/admin/index.ts
index 445e10caa..7ca31e5e4 100644
--- a/control-api/src/routes/admin/index.ts
+++ b/control-api/src/routes/admin/index.ts
@@ -10,6 +10,7 @@ import { createAdminHostEnvRouter } from './hostEnv.js'
import { createAdminHostsOverviewRouter } from './hostsOverview.js'
import { createAdminLlmModelsRouter } from './llmModels.js'
import { createAdminLlmPricesRouter } from './llmPrices.js'
+import { createAdminOauthProvidersRouter } from './oauthProviders.js'
import { createAdminOutputsRouter } from './outputs.js'
import { createAdminPersonalizationRouter } from './personalization.js'
import { createAdminPluginWorkloadSdkRouter } from './pluginWorkloadSdk.js'
@@ -36,6 +37,7 @@ export function createAdminRouter(gateway: K8sGateway): Router {
router.use(createAdminResourcesRouter(gateway))
router.use(createAdminRecipesRouter(gateway))
router.use(createAdminRecipeOauthRouter(gateway))
+ router.use(createAdminOauthProvidersRouter())
router.use(createAdminRegistryRouter(gateway))
router.use(createRegistryConnectRouter())
router.use(createAdminSharedFilesystemsRouter(gateway))
diff --git a/control-api/src/routes/admin/oauthProviders.ts b/control-api/src/routes/admin/oauthProviders.ts
new file mode 100644
index 000000000..1b229247e
--- /dev/null
+++ b/control-api/src/routes/admin/oauthProviders.ts
@@ -0,0 +1,32 @@
+import { Router } from 'express'
+import { asyncHandler } from '../../http/asyncHandler.js'
+import { getCredentialManifest, isKnownOAuthProvider } from '../../oauth/providers.js'
+
+/**
+ * Admin router for OAuth provider metadata consumed by the install-from-UI
+ * wizard (Slice 1, S1-U2). Today it serves only the per-provider credential
+ * manifest; the `POST /admin/oauth/discover` prefill endpoint (D-A6) lands here
+ * in Slice 3 alongside the `'generic'` adapter.
+ */
+export function createAdminOauthProvidersRouter(): Router {
+ const router = Router()
+
+ // GET /admin/oauth/providers/:id/credential-manifest
+ // Returns the credential-form field list for a baked provider so control-ui
+ // can render the install form. 404 for an unknown provider id — Slice 1 only
+ // serves the 8 baked adapters (isKnownOAuthProvider is the single source of
+ // truth, derived from ADAPTERS).
+ router.get(
+ '/admin/oauth/providers/:id/credential-manifest',
+ asyncHandler(async (req, res) => {
+ const id = req.params.id
+ if (!isKnownOAuthProvider(id)) {
+ res.status(404).json({ error: `Unknown OAuth provider "${id}"` })
+ return
+ }
+ res.status(200).json({ provider: id, fields: getCredentialManifest(id) })
+ })
+ )
+
+ return router
+}
diff --git a/control-api/src/routes/admin/registry.ts b/control-api/src/routes/admin/registry.ts
index a477fd59c..96107e2df 100644
--- a/control-api/src/routes/admin/registry.ts
+++ b/control-api/src/routes/admin/registry.ts
@@ -3,6 +3,7 @@ import type { NextFunction, Request, Response } from 'express'
import { createHash } from 'node:crypto'
import { isIP } from 'node:net'
import { parse as parseYaml } from 'yaml'
+import { z } from 'zod'
import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import { extractK8sError } from '../../http/k8sError.js'
@@ -10,6 +11,8 @@ import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec
import { K8sGateway } from '../../k8s.js'
import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'
+import { getOAuthProviderAdapter, isKnownOAuthProvider } from '../../oauth/providers.js'
+import { rootLogger } from '../../observability/logger.js'
import { type AdminUserRecord, findAdminById } from '../../services/adminAuthService.js'
import {
addHookRefToHost,
@@ -549,11 +552,15 @@ async function loadRegistryCredentialSchema(entry: {
}
}
+const log = rootLogger.child({ module: 'admin-registry' })
+
/** Audit log for security-sensitive operations (finding #10). */
function auditLog(action: string, details: Record<string, unknown>): void {
- const safe: Record<string, unknown> = { timestamp: new Date().toISOString(), action, ...details }
+ const safe: Record<string, unknown> = { ...details }
+ // Drop value-bearing fields defensively; only key NAMES are ever passed in.
+ // pino's redact layer strips token/secret keys on top of this.
for (const k of ['credentials', 'clientSecret', 'stringData', 'password']) delete safe[k]
- console.log(`[AUDIT] ${JSON.stringify(safe)}`)
+ log.info({ event: 'audit', action, ...safe }, `audit: ${action}`)
}
/**
@@ -657,6 +664,155 @@ function validateRemoteUrl(url: string): void {
}
}
+// ─── OAuth install-from-UI (Slice 1, S1-U2/S1-U3) ───────────────────────────
+
+// Canonical Secret keys control-api writes for the managed-Secret mode (D-B3).
+// They match the credential-manifest field names in oauth/providers.ts, so the
+// form field, the stored key, and the clientIdRef/clientSecretRef never drift.
+const OAUTH_CLIENT_ID_KEY = 'client_id'
+const OAUTH_CLIENT_SECRET_KEY = 'client_secret'
+
+// Frozen catalog contract (S1-U1 deferred): the entry MAY carry an `oauth` block
+// under mcp_server_meta. `genericConfig` is Slice-3-only — accepted here but
+// NEVER read in Slice 1 (S-4: the catalog suggests, it never auto-configures).
+const CatalogOAuthBlockSchema = z.object({
+ provider: z.string(),
+ grantScope: z.enum(['user', 'context']).optional(),
+ scopes: z.array(z.string()).optional(),
+ genericConfig: z.unknown().optional(),
+})
+
+// Operator-supplied OAuth input on the install request. The credential Secret is
+// either MANAGED (operator types values → control-api creates the Secret) or a
+// REFERENCE to an existing Secret whose id/secret keys the operator names.
+const InstallOAuthSecretSchema = z.discriminatedUnion('mode', [
+ z.object({
+ mode: z.literal('managed'),
+ clientId: z.string().min(1),
+ clientSecret: z.string().min(1),
+ }),
+ z.object({
+ mode: z.literal('reference'),
+ secretName: z.string().min(1),
+ clientIdKey: z.string().min(1),
+ clientSecretKey: z.string().min(1),
+ }),
+])
+
+const InstallOAuthInputSchema = z.object({
+ // Editable scopes (D-B6/E-19.3): the wizard prefills from the catalog and the
+ // admin may override them per server (the Google family shares one provider
+ // with different scopes per server).
+ scopes: z.array(z.string()).optional(),
+ // grantScope is immutable once set (D-B7); the selector is offered only at
+ // create, which is where this saga runs.
+ grantScope: z.enum(['user', 'context']).optional(),
+ secret: InstallOAuthSecretSchema,
+})
+
+type InstallOAuthInput = z.infer<typeof InstallOAuthInputSchema>
+
+/**
+ * Derive the immutable `spec.oauth.id` from the server name (D-B5). The operator
+ * never types it: the id is the OAuth callback path segment, so control-api owns
+ * it and pre-checks uniqueness. The mcpserver CRD constrains it to
+ * `^[a-z0-9-]{1,63}$`; the server name is already a valid K8s name, so this only
+ * normalises separators and truncates.
+ */
+export function deriveOAuthClientId(serverName: string): string {
+ return serverName
+ .toLowerCase()
+ .replace(/[^a-z0-9-]/g, '-')
+ .replace(/-+/g, '-')
+ .replace(/^-+/, '')
+ .slice(0, 63)
+ .replace(/-+$/, '')
+}
+
+/**
+ * Resolve the effective OAuth scopes for an install (D-B6/GAP-6). Precedence:
+ * operator-edited scopes → catalog prefill → the baked adapter's defaultScopes.
+ * Returns `[]` only when every source is empty (the google/salesforce/slack/…
+ * family with no scopes supplied), which the caller rejects: a baked OAuth server
+ * must never be created with `scopes: []` when its provider demands explicit ones.
+ */
+export function computeInstallOAuthScopes(args: {
+ operatorScopes?: string[]
+ catalogScopes?: string[]
+ defaultScopes: ReadonlyArray<string>
+}): string[] {
+ // An empty list at any level (operator cleared it, or the catalog carries [])
+ // falls THROUGH to the next source, ending at defaultScopes, then rejection.
+ const clean = (list: string[] | undefined): string[] | undefined => {
+ if (!Array.isArray(list)) return undefined
+ const filtered = list.map(s => s.trim()).filter(s => s.length > 0)
+ return filtered.length > 0 ? filtered : undefined
+ }
+ const prefill = clean(args.operatorScopes) ?? clean(args.catalogScopes)
+ if (prefill) return prefill
+ return [...args.defaultScopes]
+}
+
+/**
+ * Pre-check that `spec.oauth.id` is unique among installed servers in the
+ * namespace (D-B5). The id is the callback path segment, so a collision would
+ * route two servers' callbacks to the same coordinate. The CRD validates the id
+ * FORMAT but not uniqueness, so control-api owns this gate. A read failure
+ * propagates (asyncHandler → 500): a green install on an unverified id could
+ * hijack another server's callback route.
+ */
+async function oauthClientIdInUse(
+ gateway: K8sGateway,
+ namespace: string,
+ oauthId: string
+): Promise<boolean> {
+ const servers = (await gateway.listResource('mcpservers', namespace)) as Array<{
+ spec?: { oauth?: { id?: unknown } }
+ }>
+ return servers.some(server => server.spec?.oauth?.id === oauthId)
+}
+
+/**
+ * Verify a referenced client Secret and its named keys EXIST before the CR is
+ * written (D-B3 reference mode / Fam. B(1) invariant). A dangling
+ * clientIdRef/clientSecretRef would leave the broker unable to exchange tokens,
+ * discovered only at first connect; fail closed at admission instead. A 404
+ * Secret and a missing key are both operator-fixable 400s; any other read error
+ * propagates.
+ */
+async function verifyReferencedOAuthSecret(
+ gateway: K8sGateway,
+ namespace: string,
+ ref: { secretName: string; clientIdKey: string; clientSecretKey: string }
+): Promise<{ ok: true } | { ok: false; status: number; error: string }> {
+ let secret: { data?: Record<string, string>; stringData?: Record<string, string> }
+ try {
+ secret = (await gateway.getSecret(ref.secretName, namespace)) as typeof secret
+ } catch (err) {
+ if (extractK8sError(err)?.status === 404) {
+ return {
+ ok: false,
+ status: 400,
+ error: `oauth.secret.reference: Secret "${ref.secretName}" not found in ${namespace}`,
+ }
+ }
+ throw err
+ }
+ const presentKeys = new Set<string>([
+ ...Object.keys(secret.data ?? {}),
+ ...Object.keys(secret.stringData ?? {}),
+ ])
+ const missing = [ref.clientIdKey, ref.clientSecretKey].filter(key => !presentKeys.has(key))
+ if (missing.length > 0) {
+ return {
+ ok: false,
+ status: 400,
+ error: `oauth.secret.reference: Secret "${ref.secretName}" is missing key(s): ${missing.join(', ')}`,
+ }
+ }
+ return { ok: true }
+}
+
type RegistryEgressSummary = {
domains?: unknown
ports?: unknown
@@ -892,6 +1048,12 @@ export interface RegistryInstallRequest {
registryEntryVersion: string
credentials?: Record<string, string>
egressBindings?: RegistryEgressBinding[]
+ /**
+ * OAuth wiring for an entry whose catalog carries an `oauth` block (S1-U2/U3).
+ * Absent for non-OAuth installs. Required when the catalog declares OAuth: the
+ * operator must supply the client Secret (managed values or a reference).
+ */
+ oauth?: InstallOAuthInput
}
export async function getInstalledRegistryState(gateway?: K8sGateway): Promise<{
@@ -1430,6 +1592,140 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {
return
}
+ // ── OAuth wiring (S1-U2/U3): generate spec.oauth from the catalog block
+ // + operator input. Only runs when the entry declares OAuth. `genericConfig`
+ // is NEVER read here (Slice 1 = 8 baked providers; the generic adapter is S3).
+ let managedOAuthSecret: { name: string; data: Record<string, string> } | undefined
+ let oauthClientSecretCreated = false
+ const catalogOAuthRaw = (meta as { oauth?: unknown } | null)?.oauth
+ if (catalogOAuthRaw !== undefined && catalogOAuthRaw !== null) {
+ const parsedCatalog = CatalogOAuthBlockSchema.safeParse(catalogOAuthRaw)
+ if (!parsedCatalog.success) {
+ res.status(400).json({ error: 'Invalid catalog oauth block', pendingAllowed: false })
+ return
+ }
+ const catalogOAuth = parsedCatalog.data
+
+ // Slice 1 serves only the 8 baked providers. 'generic' and any unknown
+ // value fail closed here (isKnownOAuthProvider excludes the sentinel).
+ if (!isKnownOAuthProvider(catalogOAuth.provider)) {
+ res.status(400).json({
+ error: `oauth.provider "${catalogOAuth.provider}" is not a supported baked provider`,
+ })
+ return
+ }
+ const provider = catalogOAuth.provider
+
+ // D-B4: the public callback base URL MUST be configured. Without it the
+ // callback would derive from the internal Host behind the funnel and the
+ // operator would register a broken redirect URI at the provider.
+ if (!config.oauthCallbackBaseUrl || config.oauthCallbackBaseUrl.trim().length === 0) {
+ res.status(400).json({
+ error:
+ 'oauth: CONTROL_API_OAUTH_CALLBACK_BASE_URL is not configured; cannot install an OAuth server',
+ })
+ return
+ }
+
+ if (body.oauth === undefined || body.oauth === null) {
+ res.status(400).json({
+ error:
+ 'oauth: client credentials are required (managed values or a Secret reference)',
+ })
+ return
+ }
+ const parsedInput = InstallOAuthInputSchema.safeParse(body.oauth)
+ if (!parsedInput.success) {
+ // Describe the real validation failure. Zod issue paths/messages are
+ // field names and type descriptions — never the submitted values — so
+ // this cannot leak a client secret.
+ const detail = parsedInput.error.issues
+ .map(issue => {
+ const path = issue.path.join('.')
+ return path ? `${path}: ${issue.message}` : issue.message
+ })
+ .join('; ')
+ res.status(400).json({ error: `oauth: invalid oauth input: ${detail}` })
+ return
+ }
+ const oauthInput = parsedInput.data
+
+ // grantScope: operator selector wins, else catalog, else 'user'. Immutable
+ // once set (D-B7) — this saga only ever creates.
+ const grantScope = oauthInput.grantScope ?? catalogOAuth.grantScope ?? 'user'
+
+ // Scopes: operator edit → catalog prefill → baked defaultScopes (D-B6).
+ const adapter = getOAuthProviderAdapter(provider)
+ const scopes = computeInstallOAuthScopes({
+ operatorScopes: oauthInput.scopes,
+ catalogScopes: catalogOAuth.scopes,
+ defaultScopes: adapter.defaultScopes,
+ })
+ if (scopes.length === 0) {
+ // GAP-6: google/salesforce/slack/notion/monday/clickup have empty
+ // defaultScopes, so a server with no scopes supplied is rejected rather
+ // than created inert with scopes: [].
+ res.status(400).json({
+ error: `oauth: provider "${provider}" requires explicit scopes; none supplied`,
+ })
+ return
+ }
+
+ // D-B5: control-api derives the immutable id and pre-checks uniqueness.
+ const oauthId = deriveOAuthClientId(serverName)
+ if (!oauthId) {
+ res
+ .status(400)
+ .json({ error: 'oauth: could not derive a valid oauth.id from serverName' })
+ return
+ }
+ if (await oauthClientIdInUse(gateway, targetNs, oauthId)) {
+ res.status(409).json({
+ error: `oauth.id "${oauthId}" is already in use by another server; choose a different serverName`,
+ })
+ return
+ }
+
+ // Secret refs by mode (D-B3).
+ let clientIdRef: { name: string; key: string }
+ let clientSecretRef: { name: string; key: string }
+ if (oauthInput.secret.mode === 'reference') {
+ const verify = await verifyReferencedOAuthSecret(gateway, targetNs, oauthInput.secret)
+ if (!verify.ok) {
+ res.status(verify.status).json({ error: verify.error })
+ return
+ }
+ clientIdRef = { name: oauthInput.secret.secretName, key: oauthInput.secret.clientIdKey }
+ clientSecretRef = {
+ name: oauthInput.secret.secretName,
+ key: oauthInput.secret.clientSecretKey,
+ }
+ } else {
+ const oauthSecretName = `${serverName}-oauth-client`
+ clientIdRef = { name: oauthSecretName, key: OAUTH_CLIENT_ID_KEY }
+ clientSecretRef = { name: oauthSecretName, key: OAUTH_CLIENT_SECRET_KEY }
+ managedOAuthSecret = {
+ name: oauthSecretName,
+ data: {
+ [OAUTH_CLIENT_ID_KEY]: oauthInput.secret.clientId,
+ [OAUTH_CLIENT_SECRET_KEY]: oauthInput.secret.clientSecret,
+ },
+ }
+ }
+
+ // The CRD couples auth.type=='oauth' iff spec.oauth is present and
+ // forbids a static auth.secretRef alongside oauth.
+ mcpServerSpec.auth = { type: 'oauth' }
+ mcpServerSpec.oauth = {
+ id: oauthId,
+ provider,
+ clientIdRef,
+ clientSecretRef,
+ scopes,
+ grantScope,
+ }
+ }
+
const preflightErrors = await validateMcpServerSpecPreflight(mcpServerSpec, {
allowedImagePrefixes: config.allowedPluginImagePrefixes,
enforceImageAllowlist: config.enforcePluginImageAllowlist,
@@ -1505,6 +1801,50 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {
}
}
+ // ── Step 3b: Create the managed OAuth client Secret (D-B3) ────────
+ // Only for managed mode; reference mode was verified above and creates
+ // nothing. Written before the CR that references it, and rolled back with
+ // the CR/context on any later failure.
+ if (managedOAuthSecret) {
+ const oauthSecretReq: SecretUpsertRequest = {
+ name: managedOAuthSecret.name,
+ namespace: targetNs,
+ type: 'Opaque',
+ labels: registryLabels,
+ annotations: registryAnnotations,
+ stringData: managedOAuthSecret.data,
+ }
+ try {
+ await gateway.createSecret(oauthSecretReq)
+ } catch (err) {
+ // Roll back the envSecret created in Step 3 (if any) so a failed OAuth
+ // Secret write leaves nothing behind.
+ if (secretCreated) {
+ try {
+ await gateway.deleteSecret(secretName, targetNs)
+ } catch {
+ // Best-effort rollback; do not mask the original error.
+ }
+ }
+ const k8sErr = extractK8sError(err)
+ if (k8sErr) {
+ res
+ .status(k8sErr.status)
+ .json({ error: `OAuth client Secret creation failed: ${k8sErr.message}` })
+ return
+ }
+ throw err
+ }
+ oauthClientSecretCreated = true
+ // Key NAMES only; the client_id/client_secret VALUES are never logged.
+ auditLog('oauth_client_secret_created', {
+ secretName: managedOAuthSecret.name,
+ namespace: targetNs,
+ registryEntry: body.registryEntryName,
+ credentialKeys: Object.keys(managedOAuthSecret.data),
+ })
+ }
+
// ── Step 4: Create McpServer CRD (rollback Secret on failure) ─────
try {
await gateway.createResource(
@@ -1520,7 +1860,7 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {
targetNs
)
} catch (err) {
- // Rollback: delete the Secret if we created one
+ // Rollback: delete the Secret(s) if we created any
if (secretCreated) {
try {
await gateway.deleteSecret(secretName, targetNs)
@@ -1528,6 +1868,13 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {
// Best-effort rollback; log but do not mask the original error
}
}
+ if (oauthClientSecretCreated && managedOAuthSecret) {
+ try {
+ await gateway.deleteSecret(managedOAuthSecret.name, targetNs)
+ } catch {
+ // Best-effort rollback; log but do not mask the original error
+ }
+ }
const k8sErr = extractK8sError(err)
if (k8sErr) {
res.status(k8sErr.status).json({ error: k8sErr.message })
@@ -1579,6 +1926,17 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {
// Best-effort rollback; preserve the original context-update error.
}
}
+ if (oauthClientSecretCreated && managedOAuthSecret) {
+ try {
+ await gateway.deleteSecret(managedOAuthSecret.name, targetNs)
+ await waitForDeletion(
+ () => gateway.getSecret(managedOAuthSecret.name, targetNs),
+ `Secret/${managedOAuthSecret.name}`
+ )
+ } catch {
+ // Best-effort rollback; preserve the original context-update error.
+ }
+ }
const k8sErr = extractK8sError(err)
const message =
k8sErr?.message ||
@@ -2480,7 +2838,10 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {
config.hostsNamespace
)
} catch (err) {
- console.error(`[Admin] upgrade-hook "${body.hookName}": Host ref sync failed:`, err)
+ log.error(
+ { err, event: 'upgrade-hook-host-ref-sync-failed', hookName: body.hookName },
+ 'upgrade-hook: Host ref sync failed'
+ )
res.status(207).json({
hookName: body.hookName,
digest: newDigest,
@@ -2594,6 +2955,23 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {
// Secret may not exist (no credentials)
}
+ // Delete the managed OAuth client Secret (S1-U3, Step 3b). The name is
+ // DERIVED (`${serverName}-oauth-client`), so it can only exist if this
+ // server was installed in OAuth managed mode; reference mode points the
+ // clientIdRef/clientSecretRef at an operator-named Secret and never
+ // creates this name. Best-effort by-name, same as `-credentials` above:
+ // a no-op when the server had no OAuth block or used reference mode.
+ try {
+ await gateway.deleteSecret(`${resourceName}-oauth-client`, namespace)
+ await waitForDeletion(
+ () => gateway.getSecret(`${resourceName}-oauth-client`, namespace),
+ `Secret/${resourceName}-oauth-client`
+ )
+ deleted.push(`Secret/${resourceName}-oauth-client`)
+ } catch {
+ // Secret may not exist (no OAuth block, or reference mode)
+ }
+
// Remove from Context allowlists
try {
const ctxList = (await gateway.listResource('contexts', namespace)) as Array<{
diff --git a/control-api/src/routes/admin/secrets.ts b/control-api/src/routes/admin/secrets.ts
index 0169b7062..8253cd61e 100644
--- a/control-api/src/routes/admin/secrets.ts
+++ b/control-api/src/routes/admin/secrets.ts
@@ -457,6 +457,31 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
)
// ── MCP Server Secrets ──────────────────────────────────────────────────────
+ // List MCP Server Secrets as NAMES + KEYS only — never values (E-16.1). The
+ // OAuth install-from-UI "reference an existing Secret" mode uses this to check
+ // that the Secret and the id/secret keys exist BEFORE the operator submits, so
+ // the wizard never writes a CR whose clientIdRef/clientSecretRef dangle. The
+ // server-side install saga re-verifies existence at submit; this is the UI's
+ // pre-check. Values are structurally impossible here: listSecrets projects only
+ // metadata + key names, and this route forwards only name + keys.
+ router.get(
+ '/admin/mcp-secrets',
+ enforceNamespace(config.mcpServersNamespace),
+ asyncHandler(async (_req, res) => {
+ const rows = await gateway.listSecrets(config.mcpServersNamespace)
+ const items = rows.map(row => {
+ const record = asRecord(row)
+ const metadata = asRecord(record?.metadata)
+ const name = typeof metadata?.name === 'string' ? metadata.name : ''
+ const keys = Array.isArray(record?.keys)
+ ? (record.keys as unknown[]).filter((k): k is string => typeof k === 'string')
+ : []
+ return { name, keys }
+ })
+ res.status(200).json({ items })
+ })
+ )
+
// Create an Opaque K8s Secret in the mcp-server namespace.
// Used by the Control UI when the operator provides secret values inline
// in the Create MCP Server form.
diff --git a/control-api/test/oauth.credentialManifest.test.ts b/control-api/test/oauth.credentialManifest.test.ts
new file mode 100644
index 000000000..235532778
--- /dev/null
+++ b/control-api/test/oauth.credentialManifest.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest'
+import {
+ KNOWN_OAUTH_PROVIDERS,
+ type OAuthProvider,
+ getCredentialManifest,
+} from '../src/oauth/providers.js'
+
+const ALL_PROVIDERS: OAuthProvider[] = [...KNOWN_OAUTH_PROVIDERS]
+
+describe('getCredentialManifest (D-B1)', () => {
+ it('every baked provider exposes a manifest with at least client_id + client_secret', () => {
+ expect(ALL_PROVIDERS.length).toBeGreaterThanOrEqual(8)
+ for (const provider of ALL_PROVIDERS) {
+ const manifest = getCredentialManifest(provider)
+ const names = manifest.map(f => f.name)
+ expect(names).toContain('client_id')
+ expect(names).toContain('client_secret')
+ }
+ })
+
+ it('marks client_secret as secret + required and client_id as non-secret + required', () => {
+ const manifest = getCredentialManifest('google')
+ const byName = Object.fromEntries(manifest.map(f => [f.name, f]))
+ expect(byName['client_id'].secret).toBe(false)
+ expect(byName['client_id'].required).toBe(true)
+ expect(byName['client_secret'].secret).toBe(true)
+ expect(byName['client_secret'].required).toBe(true)
+ })
+
+ it('returns a defensive copy — mutating the result never mutates the shared definition', () => {
+ const first = getCredentialManifest('slack')
+ first[0].label = 'MUTATED'
+ first.push({ name: 'injected', label: 'x', secret: false, required: false })
+ const second = getCredentialManifest('slack')
+ expect(second[0].label).not.toBe('MUTATED')
+ expect(second.map(f => f.name)).not.toContain('injected')
+ })
+})
diff --git a/control-api/test/routes.mcpSecrets.list.test.ts b/control-api/test/routes.mcpSecrets.list.test.ts
new file mode 100644
index 000000000..26c9036db
--- /dev/null
+++ b/control-api/test/routes.mcpSecrets.list.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'
+import { SecretService } from '../src/services/secretService.js'
+
+// Derive the gateway.listSecrets fixture from the REAL producer
+// (SecretService.listSecrets), fed underlying Secrets that DO carry base64
+// values. The producer projects to metadata + key NAMES only, so this proves
+// the GET route forwards exactly what the producer emits — never values. A
+// hand-built row (e.g. one with a stray `data` field the producer never emits)
+// would test an impossible leak path instead of the real one.
+async function listSecretsOutput(
+ secrets: Array<{ name: string; data: Record<string, string> }>
+): Promise<unknown[]> {
+ const fakeCoreApi = {
+ listNamespacedSecret: async ({ namespace }: { namespace: string }) => ({
+ items: secrets.map(s => ({
+ metadata: { name: s.name, namespace, labels: {}, annotations: {} },
+ type: 'Opaque',
+ data: s.data,
+ })),
+ }),
+ }
+ const service = new SecretService(fakeCoreApi as never, 'mcp-server')
+ return service.listSecrets('mcp-server')
+}
+
+function makeApp(rows: unknown[]) {
+ const gateway = {
+ listSecrets: vi.fn(async () => rows),
+ }
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminSecretsRouter(gateway as never))
+ app.use(
+ (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
+ res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })
+ }
+ )
+ return { app, gateway }
+}
+
+describe('GET /admin/mcp-secrets (E-16.1)', () => {
+ it('forwards names + keys from the real listSecrets producer', async () => {
+ const rows = await listSecretsOutput([
+ // base64 of 'idval' / 'secval' — real stored values the producer must strip.
+ { name: 'gmail-oauth-client', data: { client_id: 'aWR2YWw=', client_secret: 'c2VjdmFs' } },
+ { name: 'other-creds', data: { API_KEY: 'a2V5' } },
+ ])
+ const { app, gateway } = makeApp(rows)
+ const res = await request(app).get('/admin/mcp-secrets').expect(200)
+ expect(gateway.listSecrets).toHaveBeenCalledWith('mcp-server')
+ expect(res.body.items).toEqual([
+ { name: 'gmail-oauth-client', keys: ['client_id', 'client_secret'] },
+ { name: 'other-creds', keys: ['API_KEY'] },
+ ])
+ })
+
+ it('never surfaces Secret values (producer strips them, route forwards names-only)', async () => {
+ const rows = await listSecretsOutput([
+ { name: 'gmail-oauth-client', data: { client_id: 'aWR2YWw=', client_secret: 'c2VjdmFs' } },
+ ])
+ const { app } = makeApp(rows)
+ const res = await request(app).get('/admin/mcp-secrets').expect(200)
+ const raw = JSON.stringify(res.body)
+ // Neither the base64 nor the projected item carries any value.
+ expect(raw).not.toContain('c2VjdmFs')
+ expect(raw).not.toContain('aWR2YWw=')
+ expect(res.body.items[0]).not.toHaveProperty('data')
+ expect(res.body.items[0]).not.toHaveProperty('stringData')
+ })
+})
diff --git a/control-api/test/routes.oauthProviders.test.ts b/control-api/test/routes.oauthProviders.test.ts
new file mode 100644
index 000000000..bff972772
--- /dev/null
+++ b/control-api/test/routes.oauthProviders.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { createAdminOauthProvidersRouter } from '../src/routes/admin/oauthProviders.js'
+
+function makeApp() {
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminOauthProvidersRouter())
+ app.use(
+ (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
+ res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })
+ }
+ )
+ return app
+}
+
+describe('GET /admin/oauth/providers/:id/credential-manifest', () => {
+ it('returns the manifest for a known baked provider', async () => {
+ const res = await request(makeApp())
+ .get('/admin/oauth/providers/google/credential-manifest')
+ .expect(200)
+ expect(res.body.provider).toBe('google')
+ expect(Array.isArray(res.body.fields)).toBe(true)
+ const names = res.body.fields.map((f: { name: string }) => f.name)
+ expect(names).toContain('client_id')
+ expect(names).toContain('client_secret')
+ })
+
+ it('404s for an unknown provider id', async () => {
+ const res = await request(makeApp())
+ .get('/admin/oauth/providers/not-a-provider/credential-manifest')
+ .expect(404)
+ expect(res.body.error).toMatch(/Unknown OAuth provider/)
+ })
+
+ it("404s for the 'generic' sentinel (Slice 1 serves only the 8 baked)", async () => {
+ await request(makeApp()).get('/admin/oauth/providers/generic/credential-manifest').expect(404)
+ })
+})
diff --git a/control-api/test/routes.registryInstall.oauth.test.ts b/control-api/test/routes.registryInstall.oauth.test.ts
new file mode 100644
index 000000000..df36460dd
--- /dev/null
+++ b/control-api/test/routes.registryInstall.oauth.test.ts
@@ -0,0 +1,570 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { config } from '../src/config.js'
+import {
+ computeInstallOAuthScopes,
+ createAdminRegistryRouter,
+ deriveOAuthClientId,
+} from '../src/routes/admin/registry.js'
+import {
+ getCredentialSchema,
+ getDigest,
+ getEntryVersion,
+ reportInstall,
+} from '../src/services/registryClient.js'
+import { MockGateway } from './mockGateway.js'
+
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn(async () => [{ address: '93.184.216.34', family: 4 }]),
+}))
+
+vi.mock('../src/services/registryClient.js', () => ({
+ searchEntries: vi.fn(),
+ getEntry: vi.fn(),
+ getEntryVersion: vi.fn(),
+ getCredentialSchema: vi.fn(),
+ getCategories: vi.fn(),
+ reportInstall: vi.fn(),
+ downloadBundle: vi.fn(),
+ getDigest: vi.fn(),
+ uploadArtifacts: vi.fn(),
+ updateVersionMetadata: vi.fn(),
+ deleteVersion: vi.fn(),
+ publishEntry: vi.fn(),
+ resolvePublishScope: vi.fn(),
+ applyPublishScope: vi.fn((name: string | undefined) => name),
+}))
+
+let savedCallbackBaseUrl: string
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ vi.mocked(getDigest).mockResolvedValue({ digest: null })
+ vi.mocked(getCredentialSchema).mockRejectedValue(new Error('No credential schema endpoint'))
+ vi.mocked(reportInstall).mockResolvedValue({ acknowledged: true, stored: true })
+ savedCallbackBaseUrl = config.oauthCallbackBaseUrl
+ config.oauthCallbackBaseUrl = 'https://control.example.com'
+})
+
+afterEach(() => {
+ config.oauthCallbackBaseUrl = savedCallbackBaseUrl
+})
+
+function makeApp(gateway: MockGateway) {
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminRegistryRouter(gateway as unknown as import('../src/k8s.js').K8sGateway))
+ app.use(
+ (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
+ res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })
+ }
+ )
+ return app
+}
+
+function makeInstallApp() {
+ const gw = new MockGateway('mcp-server')
+ gw.createResource('contexts', {
+ metadata: { name: 'default-context' },
+ spec: { contextId: 'default-context', mcpServers: [] },
+ })
+ return { app: makeApp(gw), gw }
+}
+
+/** Build a baked-OAuth catalog entry. `oauth` lives under mcp_server_meta. */
+function oauthEntry(oauth: Record<string, unknown>, imageRef = 'clerum/gmail-mcp:1.0.0') {
+ return {
+ id: '1',
+ name: 'gmail-mcp',
+ version: '1.0.0',
+ entry_type: 'mcp-server',
+ description: 'Gmail MCP server',
+ author: 'clerum',
+ origin: 'official',
+ category: 'productivity',
+ tags: ['gmail'],
+ trust_level: 'high',
+ quality_tier: 'verified',
+ status: 'published',
+ server_mode: 'local',
+ transport: 'streamableHttp',
+ recipe_type: null,
+ mcp_server_meta: { imageRef, port: 3000, oauth },
+ recipe_meta: null,
+ artifact_refs: null,
+ downloads: 0,
+ installs: 0,
+ created_at: '2026-03-01T00:00:00Z',
+ }
+}
+
+async function readServerOAuth(gw: MockGateway, name: string) {
+ const mcp = (await gw.getResource('mcpservers', name, 'mcp-server')) as {
+ spec: { auth?: { type?: string }; oauth?: Record<string, unknown> }
+ }
+ return mcp.spec
+}
+
+describe('pure helpers', () => {
+ it('deriveOAuthClientId normalises to the CRD id pattern and truncates to 63', () => {
+ expect(deriveOAuthClientId('my-gmail')).toBe('my-gmail')
+ expect(deriveOAuthClientId('mcp-Gmail.v1')).toBe('mcp-gmail-v1')
+ expect(deriveOAuthClientId('a'.repeat(80))).toHaveLength(63)
+ expect(/^[a-z0-9-]{1,63}$/.test(deriveOAuthClientId('mcp-gmail-v1-0-0-abcd1234'))).toBe(true)
+ })
+
+ it('computeInstallOAuthScopes: operator → catalog → defaultScopes precedence', () => {
+ expect(
+ computeInstallOAuthScopes({
+ operatorScopes: ['a'],
+ catalogScopes: ['b'],
+ defaultScopes: ['c'],
+ })
+ ).toEqual(['a'])
+ expect(
+ computeInstallOAuthScopes({
+ operatorScopes: undefined,
+ catalogScopes: ['b'],
+ defaultScopes: ['c'],
+ })
+ ).toEqual(['b'])
+ expect(
+ computeInstallOAuthScopes({ operatorScopes: [], catalogScopes: ['b'], defaultScopes: ['c'] })
+ ).toEqual(['b'])
+ expect(
+ computeInstallOAuthScopes({
+ operatorScopes: undefined,
+ catalogScopes: [],
+ defaultScopes: ['c'],
+ })
+ ).toEqual(['c'])
+ expect(
+ computeInstallOAuthScopes({ operatorScopes: undefined, catalogScopes: [], defaultScopes: [] })
+ ).toEqual([])
+ })
+})
+
+describe('POST /admin/registry/install — OAuth (S1-U2/U3)', () => {
+ // Fam. A(3) / E-19.3 + managed Secret happy path
+ it('generates spec.oauth from catalog + operator input and creates the managed client Secret', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'google', scopes: [] }))
+ const { app, gw } = makeInstallApp()
+
+ await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: {
+ scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
+ grantScope: 'user',
+ secret: { mode: 'managed', clientId: 'cid-value', clientSecret: 'csec-value' },
+ },
+ })
+ .expect(201)
+
+ const spec = await readServerOAuth(gw, 'my-gmail')
+ expect(spec.auth?.type).toBe('oauth')
+ expect(spec.oauth?.id).toBe('my-gmail')
+ expect(spec.oauth?.provider).toBe('google')
+ expect(spec.oauth?.grantScope).toBe('user')
+ // E-19.3: the wizard scopes reach spec.oauth
+ expect(spec.oauth?.scopes).toEqual(['https://www.googleapis.com/auth/gmail.readonly'])
+ expect(spec.oauth?.clientIdRef).toEqual({ name: 'my-gmail-oauth-client', key: 'client_id' })
+ expect(spec.oauth?.clientSecretRef).toEqual({
+ name: 'my-gmail-oauth-client',
+ key: 'client_secret',
+ })
+
+ // Managed Secret created with canonical keys.
+ const secret = (await gw.getSecret('my-gmail-oauth-client', 'mcp-server')) as {
+ stringData?: Record<string, string>
+ }
+ expect(Object.keys(secret.stringData ?? {}).sort()).toEqual(['client_id', 'client_secret'])
+ })
+
+ it('never echoes client_id/client_secret values in the response body', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'google', scopes: [] }))
+ const { app } = makeInstallApp()
+ const res = await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: {
+ scopes: ['gmail.readonly'],
+ secret: {
+ mode: 'managed',
+ clientId: 'super-secret-id',
+ clientSecret: 'super-secret-value',
+ },
+ },
+ })
+ .expect(201)
+ const raw = JSON.stringify(res.body)
+ expect(raw).not.toContain('super-secret-value')
+ expect(raw).not.toContain('super-secret-id')
+ })
+
+ // Fam. B(2) / GAP-6: three google servers, distinct per-server scopes
+ it('carries distinct per-server scopes for three google installs', async () => {
+ const scopeSets = [['gmail.readonly'], ['drive.readonly'], ['calendar.readonly']]
+ const names = ['gmail-a', 'drive-b', 'cal-c']
+ const { app, gw } = makeInstallApp()
+ for (let i = 0; i < names.length; i++) {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(
+ oauthEntry({ provider: 'google', scopes: [] })
+ )
+ await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: names[i],
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: {
+ scopes: scopeSets[i],
+ secret: { mode: 'managed', clientId: `id-${i}`, clientSecret: `sec-${i}` },
+ },
+ })
+ .expect(201)
+ }
+ for (let i = 0; i < names.length; i++) {
+ const spec = await readServerOAuth(gw, names[i])
+ expect(spec.oauth?.scopes).toEqual(scopeSets[i])
+ }
+ })
+
+ // GAP-6: prefill empty + defaultScopes empty ⇒ scopes required
+ it('rejects a google install when no scopes are supplied and defaultScopes is empty', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'google', scopes: [] }))
+ const { app, gw } = makeInstallApp()
+ const res = await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: { secret: { mode: 'managed', clientId: 'id', clientSecret: 'sec' } },
+ })
+ .expect(400)
+ expect(res.body.error).toMatch(/requires explicit scopes/)
+ await expect(gw.getResource('mcpservers', 'my-gmail', 'mcp-server')).rejects.toThrow()
+ })
+
+ it('falls back to the adapter defaultScopes for a provider that has them (microsoft-graph)', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(
+ oauthEntry({ provider: 'microsoft-graph', scopes: [] }, 'clerum/ms-mcp:1.0.0')
+ )
+ const { app, gw } = makeInstallApp()
+ await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'ms-server',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: { secret: { mode: 'managed', clientId: 'id', clientSecret: 'sec' } },
+ })
+ .expect(201)
+ const spec = await readServerOAuth(gw, 'ms-server')
+ expect(spec.oauth?.scopes).toContain('offline_access')
+ })
+
+ // Fam. B(1): reference to a missing Secret/key ⇒ reject BEFORE writing the CR
+ it('rejects reference mode when the referenced Secret does not exist (before writing the CR)', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'google', scopes: [] }))
+ const { app, gw } = makeInstallApp()
+ const createResourceSpy = vi.spyOn(gw, 'createResource')
+ const res = await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: {
+ scopes: ['gmail.readonly'],
+ secret: {
+ mode: 'reference',
+ secretName: 'ghost-secret',
+ clientIdKey: 'CID',
+ clientSecretKey: 'CSEC',
+ },
+ },
+ })
+ .expect(400)
+ expect(res.body.error).toMatch(/not found/)
+ expect(createResourceSpy.mock.calls.some(call => call[0] === 'mcpservers')).toBe(false)
+ })
+
+ it('rejects reference mode when a named key is missing on the Secret', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'google', scopes: [] }))
+ const { app, gw } = makeInstallApp()
+ gw.seedSecret('existing-oauth', 'mcp-server', { data: { CID: 'eA==' } }) // only CID, no CSEC
+ const createResourceSpy = vi.spyOn(gw, 'createResource')
+ const res = await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: {
+ scopes: ['gmail.readonly'],
+ secret: {
+ mode: 'reference',
+ secretName: 'existing-oauth',
+ clientIdKey: 'CID',
+ clientSecretKey: 'CSEC',
+ },
+ },
+ })
+ .expect(400)
+ expect(res.body.error).toMatch(/missing key/)
+ expect(createResourceSpy.mock.calls.some(call => call[0] === 'mcpservers')).toBe(false)
+ })
+
+ it('accepts reference mode when the Secret + both keys exist and creates NO managed Secret', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'google', scopes: [] }))
+ const { app, gw } = makeInstallApp()
+ gw.seedSecret('existing-oauth', 'mcp-server', { data: { CID: 'eA==', CSEC: 'eQ==' } })
+ await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: {
+ scopes: ['gmail.readonly'],
+ secret: {
+ mode: 'reference',
+ secretName: 'existing-oauth',
+ clientIdKey: 'CID',
+ clientSecretKey: 'CSEC',
+ },
+ },
+ })
+ .expect(201)
+ const spec = await readServerOAuth(gw, 'my-gmail')
+ expect(spec.oauth?.clientIdRef).toEqual({ name: 'existing-oauth', key: 'CID' })
+ expect(spec.oauth?.clientSecretRef).toEqual({ name: 'existing-oauth', key: 'CSEC' })
+ // No managed Secret was created under the derived name.
+ await expect(gw.getSecret('my-gmail-oauth-client', 'mcp-server')).rejects.toThrow()
+ })
+
+ // D-B5: id collision rejected by the uniqueness pre-check
+ it('rejects an install whose derived oauth.id collides with an existing server', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'google', scopes: [] }))
+ const { app, gw } = makeInstallApp()
+ await gw.createResource(
+ 'mcpservers',
+ { metadata: { name: 'other-server' }, spec: { oauth: { id: 'my-gmail' } } },
+ 'mcp-server'
+ )
+ const res = await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: {
+ scopes: ['gmail.readonly'],
+ secret: { mode: 'managed', clientId: 'id', clientSecret: 'sec' },
+ },
+ })
+ .expect(409)
+ expect(res.body.error).toMatch(/already in use/)
+ })
+
+ // D-B4: missing callback base URL ⇒ reject
+ it('rejects an OAuth install when CONTROL_API_OAUTH_CALLBACK_BASE_URL is empty', async () => {
+ config.oauthCallbackBaseUrl = ''
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'google', scopes: [] }))
+ const { app, gw } = makeInstallApp()
+ const createResourceSpy = vi.spyOn(gw, 'createResource')
+ const res = await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: {
+ scopes: ['gmail.readonly'],
+ secret: { mode: 'managed', clientId: 'id', clientSecret: 'sec' },
+ },
+ })
+ .expect(400)
+ expect(res.body.error).toMatch(/CALLBACK_BASE_URL/)
+ expect(createResourceSpy.mock.calls.some(call => call[0] === 'mcpservers')).toBe(false)
+ })
+
+ // S-4: genericConfig in the catalog is IGNORED in Slice 1 (never auto-applied)
+ it('ignores a genericConfig block on a baked provider (no endpoints reach spec.oauth)', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(
+ oauthEntry({
+ provider: 'google',
+ scopes: ['gmail.readonly'],
+ genericConfig: {
+ authorizationEndpoint: 'https://evil.example.com/auth',
+ tokenEndpoint: 'https://evil.example.com/token',
+ },
+ })
+ )
+ const { app, gw } = makeInstallApp()
+ await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: { secret: { mode: 'managed', clientId: 'id', clientSecret: 'sec' } },
+ })
+ .expect(201)
+ const spec = await readServerOAuth(gw, 'my-gmail')
+ const raw = JSON.stringify(spec.oauth)
+ expect(raw).not.toContain('evil.example.com')
+ expect(spec.oauth).not.toHaveProperty('authorizationEndpoint')
+ expect(spec.oauth).not.toHaveProperty('genericConfig')
+ })
+
+ it("rejects the 'generic' sentinel provider in Slice 1", async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(
+ oauthEntry({ provider: 'generic', scopes: ['x'] })
+ )
+ const { app } = makeInstallApp()
+ const res = await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-generic',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: { secret: { mode: 'managed', clientId: 'id', clientSecret: 'sec' } },
+ })
+ .expect(400)
+ expect(res.body.error).toMatch(/not a supported baked provider/)
+ })
+
+ it('requires operator oauth credentials when the catalog declares OAuth', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(
+ oauthEntry({ provider: 'google', scopes: ['gmail.readonly'] })
+ )
+ const { app } = makeInstallApp()
+ const res = await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ })
+ .expect(400)
+ expect(res.body.error).toMatch(/client credentials are required/)
+ })
+
+ // FIX 1 (T3): uninstall must reclaim the managed OAuth client Secret, else a
+ // reinstall re-enters Step 3b and 409s on createSecret.
+ it('deletes the managed oauth-client Secret on uninstall', async () => {
+ const gw = new MockGateway('mcp-server')
+ gw.createResource('mcpservers', {
+ metadata: { name: 'my-gmail' },
+ spec: {
+ image: 'clerum/gmail-mcp:1.0.0',
+ auth: { type: 'oauth' },
+ oauth: {
+ id: 'my-gmail',
+ provider: 'google',
+ clientIdRef: { name: 'my-gmail-oauth-client', key: 'client_id' },
+ clientSecretRef: { name: 'my-gmail-oauth-client', key: 'client_secret' },
+ },
+ },
+ })
+ gw.seedSecret('my-gmail-oauth-client', 'mcp-server', {
+ stringData: { client_id: 'id', client_secret: 'sec' },
+ })
+ const app = makeApp(gw)
+
+ const res = await request(app).delete('/admin/registry/uninstall/my-gmail').expect(200)
+
+ expect(res.body.deleted).toContain('Secret/my-gmail-oauth-client')
+ await expect(gw.getSecret('my-gmail-oauth-client', 'mcp-server')).rejects.toThrow()
+ })
+
+ // FIX 2: a present-but-invalid body.oauth must report the real validation
+ // failure, not the "credentials required" message — and must not leak values.
+ it('400s with a descriptive message when body.oauth.grantScope is invalid', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'google', scopes: [] }))
+ const { app } = makeInstallApp()
+ const res = await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: {
+ scopes: ['gmail.readonly'],
+ grantScope: 'nonsense',
+ secret: { mode: 'managed', clientId: 'id', clientSecret: 'leaky-secret-value' },
+ },
+ })
+ .expect(400)
+ expect(res.body.error).toMatch(/invalid oauth input/)
+ expect(res.body.error).toMatch(/grantScope/)
+ expect(res.body.error).not.toMatch(/credentials are required/)
+ expect(res.body.error).not.toContain('leaky-secret-value')
+ })
+
+ it('400s with a descriptive message when body.oauth.scopes is not an array', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'google', scopes: [] }))
+ const { app } = makeInstallApp()
+ const res = await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'my-gmail',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ oauth: {
+ scopes: 'gmail.readonly',
+ secret: { mode: 'managed', clientId: 'id', clientSecret: 'sec' },
+ },
+ })
+ .expect(400)
+ expect(res.body.error).toMatch(/invalid oauth input/)
+ expect(res.body.error).toMatch(/scopes/)
+ })
+
+ it('leaves a non-OAuth install unchanged (no spec.oauth, no auth block)', async () => {
+ const entry = oauthEntry({ provider: 'google', scopes: [] })
+ const noOauth = {
+ ...entry,
+ mcp_server_meta: { imageRef: 'clerum/plain-mcp:1.0.0', port: 3000 },
+ }
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(noOauth)
+ const { app, gw } = makeInstallApp()
+ await request(app)
+ .post('/admin/registry/install')
+ .send({
+ serverName: 'plain-server',
+ contextRef: 'default-context',
+ registryEntryName: 'gmail-mcp',
+ registryEntryVersion: '1.0.0',
+ })
+ .expect(201)
+ const spec = await readServerOAuth(gw, 'plain-server')
+ expect(spec.oauth).toBeUndefined()
+ expect(spec.auth).toBeUndefined()
+ })
+})