Skip to content

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

TypeScript

feat(control-ui): add OAuth install wizard and read-only immutables (S1-U4)

Diego Zacarias3f6437d10efc
diff --git a/control-ui/app/constants/oauthProviders.ts b/control-ui/app/constants/oauthProviders.ts
new file mode 100644
index 000000000..83e279345
--- /dev/null
+++ b/control-ui/app/constants/oauthProviders.ts
@@ -0,0 +1,35 @@
+// Display metadata for the 8 baked OAuth providers (Slice 1). The provider id is
+// the frozen enum control-api serves via isKnownOAuthProvider; these are only
+// labels and the provider's own "where to register the redirect URI" docs shown
+// beside the redirect URI in the install wizard (D-B4). The generic sentinel is
+// Slice 3 and intentionally absent.
+
+export const OAUTH_PROVIDER_LABELS: Record<string, string> = {
+ google: 'Google',
+ 'microsoft-graph': 'Microsoft 365',
+ slack: 'Slack',
+ salesforce: 'Salesforce',
+ notion: 'Notion',
+ monday: 'monday.com',
+ clickup: 'ClickUp',
+ vercel: 'Vercel',
+}
+
+// Where the operator registers the OAuth app + redirect URI for each provider.
+// A missing entry simply renders no docs link (the redirect URI + copy button
+// remain the primary affordance).
+export const OAUTH_PROVIDER_DOC_URLS: Record<string, string> = {
+ google: 'https://console.cloud.google.com/apis/credentials',
+ 'microsoft-graph':
+ 'https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app',
+ slack: 'https://api.slack.com/apps',
+ salesforce: 'https://help.salesforce.com/s/articleView?id=sf.connected_app_create.htm',
+ notion: 'https://www.notion.so/my-integrations',
+ monday: 'https://developer.monday.com/apps/docs/oauth',
+ clickup: 'https://developer.clickup.com/docs/authentication',
+ vercel: 'https://vercel.com/docs/rest-api/reference/integrations',
+}
+
+export function oauthProviderLabel(provider: string): string {
+ return OAUTH_PROVIDER_LABELS[provider] ?? provider
+}
diff --git a/control-ui/app/mcp-servers/[name]/edit/page.tsx b/control-ui/app/mcp-servers/[name]/edit/page.tsx
index e9d1ca7ae..a212ed035 100644
--- a/control-ui/app/mcp-servers/[name]/edit/page.tsx
+++ b/control-ui/app/mcp-servers/[name]/edit/page.tsx
@@ -8,6 +8,7 @@ import { CreateFlowPanel } from '@components/CreateFlowPanel'
import { CreatePageHeader } from '@components/CreatePageHeader'
import { DashboardLayout } from '@components/DashboardLayout'
import { EgressEditor } from '@components/EgressEditor'
+import { OAuthImmutableFields } from '@components/OAuthImmutableFields'
import { IconCable } from '@components/Sidebar/icons'
import { TabBar } from '@components/TabBar'
import { useToast } from '@components/Toast'
@@ -46,6 +47,7 @@ import {
sortAccessPrincipals,
} from '@lib/connectorAccess'
import type { EgressEditorStatus } from '@lib/egressModel'
+import { extractOAuthImmutables, oauthClientSecretRefName } from '@lib/oauthInstall'
/**
* Narrows `server.spec.envSecret` (typed as `unknown` on the generic
@@ -300,6 +302,9 @@ export default function EditMcpServerPage() {
const envSecret = server?.spec
? resolveEnvSecret(server.spec as Record<string, unknown>)
: undefined
+ const oauthImmutables = server?.spec
+ ? extractOAuthImmutables(server.spec as Record<string, unknown>)
+ : null
const registryCredentialSource = useMemo(
() => resolveRegistryCredentialSource(server?.metadata),
[server?.metadata]
@@ -365,17 +370,30 @@ export default function EditMcpServerPage() {
) : server ? (
activeTab === 'credentials' ? (
<div className="cu-connector-edit-form">
- <UpdateConnectorCredentials
- serverName={name}
- envSecret={envSecret}
- registryCredentialSource={registryCredentialSource}
- surface={resolveCredentialSurface(
- server.status?.conditions,
- server.spec as { managed?: boolean } | undefined
- )}
- // Ownership is a spec fact, independent of observed status.
- recipeOwned={isRecipeOwned(server.spec as { managed?: boolean } | undefined)}
- />
+ {oauthImmutables ? (
+ // An OAuth connector's credential lives in its clientSecretRef
+ // Secret, not spec.envSecret — so UpdateConnectorCredentials would
+ // fall to its "nothing to rotate here" branch and mislead. Show the
+ // accurate OAuth panel instead (D-B7; rotation is a follow-up).
+ <OAuthImmutableFields
+ oauth={oauthImmutables}
+ credentialSecretName={oauthClientSecretRefName(
+ server.spec as Record<string, unknown>
+ )}
+ />
+ ) : (
+ <UpdateConnectorCredentials
+ serverName={name}
+ envSecret={envSecret}
+ registryCredentialSource={registryCredentialSource}
+ surface={resolveCredentialSurface(
+ server.status?.conditions,
+ server.spec as { managed?: boolean } | undefined
+ )}
+ // Ownership is a spec fact, independent of observed status.
+ recipeOwned={isRecipeOwned(server.spec as { managed?: boolean } | undefined)}
+ />
+ )}
</div>
) : activeTab === 'access' ? (
<div className="cu-connector-edit-form cu-connector-edit-content">
diff --git a/control-ui/app/registry/install/page.tsx b/control-ui/app/registry/install/page.tsx
index 01fc3e0b9..11e4b19f0 100644
--- a/control-ui/app/registry/install/page.tsx
+++ b/control-ui/app/registry/install/page.tsx
@@ -11,6 +11,7 @@ import { CreateStepFlow } from '@components/CreateStepFlow'
import { DashboardLayout } from '@components/DashboardLayout'
import { EgressEditor } from '@components/EgressEditor'
import { HookInstallForm } from '@components/HookInstallForm'
+import { OAuthInstallForm } from '@components/OAuthInstallForm'
import { RegistryInstallForm } from '@components/RegistryInstallForm'
import { IconStore } from '@components/Sidebar/icons'
import { useToast } from '@components/Toast'
@@ -23,6 +24,7 @@ import type { LlmAllowedModel, RegistryEntry } from '@lib/api'
import { analyzeWorkflowRecipeEgress } from '@lib/egressModel'
import type { EgressBinding, EgressEditorStatus } from '@lib/egressModel'
import { useLlmAllowedModels } from '@lib/hooks/useLlmAllowedModels'
+import { getCatalogOAuthBlock } from '@lib/oauthInstall'
import { validateRecipe } from '@lib/recipeValidator'
type TransportWorkloadEditorTarget = {
@@ -611,6 +613,9 @@ function RegistryInstallPageContent() {
void loadEntry()
}, [entryName, entryVersion])
+ // An mcp-server entry that declares OAuth routes to the OAuth install wizard
+ // instead of the ordinary connector form (S1-U4).
+ const catalogOAuth = useMemo(() => getCatalogOAuthBlock(entry), [entry])
const isPrivate = entry?.visibility === 'private'
const kindLabel =
entry?.entry_type === 'recipe'
@@ -665,6 +670,14 @@ function RegistryInstallPageContent() {
onCancel={() => router.push(CONTROL_ROUTES.marketplace.root)}
onInstalled={() => router.push(CONTROL_ROUTES.guardrails.root)}
/>
+ ) : entry && catalogOAuth ? (
+ <OAuthInstallForm
+ entry={entry}
+ catalogOAuth={catalogOAuth}
+ onCancel={() => router.push(CONTROL_ROUTES.marketplace.root)}
+ onInstalled={() => undefined}
+ onViewConnectors={() => router.push(CONTROL_ROUTES.connectors.root)}
+ />
) : entry ? (
<RegistryInstallForm
entry={entry}
diff --git a/control-ui/components/OAuthImmutableFields/index.tsx b/control-ui/components/OAuthImmutableFields/index.tsx
new file mode 100644
index 000000000..ab5c8e139
--- /dev/null
+++ b/control-ui/components/OAuthImmutableFields/index.tsx
@@ -0,0 +1,67 @@
+'use client'
+
+import React from 'react'
+import { Field, TextInput } from '@components/ui'
+import { oauthProviderLabel } from '@constants/oauthProviders'
+import type { OAuthImmutableFieldsProps } from './types'
+
+const GRANT_SCOPE_LABELS: Record<string, string> = {
+ user: 'Per user',
+ context: 'Shared (context)',
+}
+
+/**
+ * Read-only display of an OAuth connector's immutable fields (D-B7). `id`,
+ * `provider`, and `grantScope` are CEL-immutable on the mcpserver CRD — changing
+ * one means delete + recreate — so the edit form surfaces them but never lets the
+ * operator edit them. `scopes` is editable and lives elsewhere.
+ */
+export function OAuthImmutableFields({ oauth, credentialSecretName }: OAuthImmutableFieldsProps) {
+ return (
+ <section className="cu-form-section" aria-label="OAuth configuration">
+ <div className="cu-form-section__header">
+ <h3 className="cu-form-section__title">OAuth configuration</h3>
+ <p className="cu-form-section__description">
+ These values are fixed for this connector. Changing them requires reinstalling.
+ </p>
+ </div>
+
+ <div className="cu-banner cu-banner--info" role="status">
+ This connector authenticates with OAuth. Its client credential lives in the{' '}
+ {credentialSecretName ? (
+ <>
+ OAuth client Secret <code>{credentialSecretName}</code>
+ </>
+ ) : (
+ <>connector&apos;s OAuth client Secret</>
+ )}{' '}
+ and is read only by the broker, never mounted in the pod. Rotating it from this screen is
+ not available yet — for now, rotate the keys on that Secret with <code>kubectl</code>.
+ </div>
+
+ <Field htmlFor="oauth-immutable-provider" label="Provider">
+ <TextInput
+ id="oauth-immutable-provider"
+ value={oauthProviderLabel(oauth.provider)}
+ readOnly
+ disabled
+ />
+ </Field>
+
+ <Field htmlFor="oauth-immutable-id" label="Callback id">
+ <TextInput id="oauth-immutable-id" value={oauth.id} readOnly disabled monospace />
+ </Field>
+
+ <Field htmlFor="oauth-immutable-grant" label="Grant type">
+ <TextInput
+ id="oauth-immutable-grant"
+ value={
+ oauth.grantScope ? (GRANT_SCOPE_LABELS[oauth.grantScope] ?? oauth.grantScope) : '-'
+ }
+ readOnly
+ disabled
+ />
+ </Field>
+ </section>
+ )
+}
diff --git a/control-ui/components/OAuthImmutableFields/types.ts b/control-ui/components/OAuthImmutableFields/types.ts
new file mode 100644
index 000000000..3a865ab96
--- /dev/null
+++ b/control-ui/components/OAuthImmutableFields/types.ts
@@ -0,0 +1,9 @@
+import type { OAuthImmutableFields as OAuthImmutableValues } from '@lib/oauthInstall'
+
+export type OAuthImmutableFieldsProps = {
+ oauth: OAuthImmutableValues
+ // Name of the Secret holding the OAuth client credential. When provided the
+ // panel names it in the credential-rotation notice; null falls back to a
+ // generic phrasing.
+ credentialSecretName?: string | null
+}
diff --git a/control-ui/components/OAuthInstallForm/index.tsx b/control-ui/components/OAuthInstallForm/index.tsx
new file mode 100644
index 000000000..e62ddb471
--- /dev/null
+++ b/control-ui/components/OAuthInstallForm/index.tsx
@@ -0,0 +1,587 @@
+'use client'
+
+import React, { useEffect, useMemo, useRef, useState } from 'react'
+import { CreateStepFlow } from '@components/CreateStepFlow'
+import { useToast } from '@components/Toast'
+import { IconCheck, IconCopy } from '@components/icons'
+import { Button, Field, SelectInput, TextAreaInput, TextInput } from '@components/ui'
+import { OAUTH_PROVIDER_DOC_URLS, oauthProviderLabel } from '@constants/oauthProviders'
+import { getOAuthCredentialManifest, installFromRegistry, listMcpSecrets } from '@lib/api'
+import { copyTextToClipboard } from '@lib/clipboard'
+import { isValidK8sName, toK8sName } from '@lib/k8sValidation'
+import {
+ buildOAuthRedirectUri,
+ deriveOAuthClientIdPreview,
+ formatScopesForInput,
+ oauthCallbackBaseUrl,
+ parseScopesInput,
+ referenceSecretIssue,
+ scopesAreSatisfied,
+} from '@lib/oauthInstall'
+import type {
+ McpSecretSummary,
+ OAuthCredentialField,
+ OAuthGrantScope,
+ OAuthSecretInput,
+} from '@lib/oauthInstall.types'
+import { createPrivateContext } from '@lib/privateContext'
+import type { OAuthInstallFormProps } from './types'
+
+const STEPS = ['Provider', 'Credentials', 'Install'] as const
+
+const STEP_DETAILS = [
+ {
+ description: 'Register the redirect URI',
+ title: 'Provider setup',
+ subtitle: 'Register this redirect URI in the provider’s OAuth app before you continue.',
+ },
+ {
+ description: 'Add client credentials',
+ title: 'Client credentials',
+ subtitle: 'Provide the OAuth client the broker uses to exchange tokens.',
+ },
+ {
+ description: 'Scopes and install',
+ title: 'Scopes and install',
+ subtitle: 'Set the grant type and scopes, then install the connector.',
+ },
+] as const
+
+// Canonical field names in every baked provider's credential manifest. control-api
+// keys the managed Secret by these exact names (OAUTH_CLIENT_ID_KEY /
+// OAUTH_CLIENT_SECRET_KEY in routes/admin/registry.ts), so the manifest field, the
+// managed-mode submit, and the default reference keys all use one source.
+const CLIENT_ID_FIELD = 'client_id'
+const CLIENT_SECRET_FIELD = 'client_secret'
+
+export function OAuthInstallForm({
+ entry,
+ catalogOAuth,
+ onCancel,
+ onInstalled,
+ onViewConnectors,
+}: OAuthInstallFormProps) {
+ const { showToast } = useToast()
+ const provider = catalogOAuth.provider
+ const providerLabel = oauthProviderLabel(provider)
+ const docUrl = OAUTH_PROVIDER_DOC_URLS[provider]
+
+ const [step, setStep] = useState(0)
+ const [serverName, setServerName] = useState(toK8sName(entry.name))
+ const [secretMode, setSecretMode] = useState<'managed' | 'reference'>('managed')
+ // Managed-mode values, keyed by manifest field name. The client_secret lives
+ // ONLY here (state) and in the submit body — never logged, never re-emitted.
+ const [credValues, setCredValues] = useState<Record<string, string>>({})
+ const [refSecretName, setRefSecretName] = useState('')
+ const [refClientIdKey, setRefClientIdKey] = useState(CLIENT_ID_FIELD)
+ const [refClientSecretKey, setRefClientSecretKey] = useState(CLIENT_SECRET_FIELD)
+ const [grantScope, setGrantScope] = useState<OAuthGrantScope>(catalogOAuth.grantScope ?? 'user')
+ const [scopesText, setScopesText] = useState(formatScopesForInput(catalogOAuth.scopes ?? []))
+
+ const [manifest, setManifest] = useState<OAuthCredentialField[]>([])
+ const [secrets, setSecrets] = useState<McpSecretSummary[]>([])
+ const [loading, setLoading] = useState(true)
+ const [loadError, setLoadError] = useState('')
+ const [installing, setInstalling] = useState(false)
+ const [submitError, setSubmitError] = useState('')
+ const [installed, setInstalled] = useState(false)
+ const installInFlightRef = useRef(false)
+
+ useEffect(() => {
+ let cancelled = false
+ setLoading(true)
+ setLoadError('')
+ ;(async () => {
+ try {
+ // The reference-Secret list is best-effort for managed mode: a failure only
+ // leaves the dropdown empty. In reference mode an empty list does block the
+ // install (referenceSecretIssue can't verify a Secret it can't see) — that
+ // is acceptable fail-closed degradation.
+ const [manifestResult, secretsResult] = await Promise.allSettled([
+ getOAuthCredentialManifest(provider),
+ listMcpSecrets(),
+ ])
+ if (cancelled) return
+ if (manifestResult.status === 'fulfilled') {
+ setManifest(manifestResult.value.fields ?? [])
+ } else {
+ setLoadError(
+ manifestResult.reason instanceof Error
+ ? manifestResult.reason.message
+ : 'Failed to load the provider credential form.'
+ )
+ }
+ setSecrets(secretsResult.status === 'fulfilled' ? (secretsResult.value.items ?? []) : [])
+ } finally {
+ if (!cancelled) setLoading(false)
+ }
+ })()
+ return () => {
+ cancelled = true
+ }
+ }, [provider])
+
+ const derivedId = useMemo(() => deriveOAuthClientIdPreview(serverName), [serverName])
+ const callbackBase = oauthCallbackBaseUrl()
+ const callbackConfigured = callbackBase.length > 0
+ const redirectUri = useMemo(
+ () => buildOAuthRedirectUri(callbackBase, derivedId),
+ [callbackBase, derivedId]
+ )
+ const nameValid = isValidK8sName(serverName)
+
+ const scopes = useMemo(() => parseScopesInput(scopesText), [scopesText])
+ const scopesOk = scopesAreSatisfied(scopes)
+
+ const requiredFields = useMemo(() => manifest.filter(field => field.required), [manifest])
+ // A missing/failed manifest yields an empty field list; without this guard
+ // `[].every(...)` would be vacuously true and let the operator advance and
+ // submit empty managed credentials. Require a loaded manifest instead.
+ const managedComplete =
+ manifest.length > 0 &&
+ requiredFields.every(field => (credValues[field.name] ?? '').trim().length > 0)
+ const referenceIssue =
+ secretMode === 'reference'
+ ? referenceSecretIssue(
+ {
+ secretName: refSecretName,
+ clientIdKey: refClientIdKey,
+ clientSecretKey: refClientSecretKey,
+ },
+ secrets
+ )
+ : null
+ const credentialsComplete = secretMode === 'managed' ? managedComplete : referenceIssue === null
+
+ const canInstall =
+ callbackConfigured &&
+ nameValid &&
+ Boolean(derivedId) &&
+ credentialsComplete &&
+ scopesOk &&
+ !installing
+ const step0Ready = nameValid && Boolean(derivedId)
+ const canContinue = step === 0 ? step0Ready : step === 1 ? credentialsComplete : canInstall
+
+ function canSelectStep(target: number) {
+ if (target <= step) return true
+ if (target === 1) return step0Ready
+ return step0Ready && credentialsComplete
+ }
+
+ async function handleCopyRedirectUri() {
+ if (!redirectUri) return
+ const ok = await copyTextToClipboard(redirectUri)
+ showToast(ok ? 'Redirect URI copied.' : 'Copy failed — select and copy the URI manually.', {
+ tone: ok ? 'success' : 'error',
+ })
+ }
+
+ function buildSecretInput(): OAuthSecretInput {
+ if (secretMode === 'reference') {
+ return {
+ mode: 'reference',
+ secretName: refSecretName.trim(),
+ clientIdKey: refClientIdKey.trim(),
+ clientSecretKey: refClientSecretKey.trim(),
+ }
+ }
+ // Read the managed values by the manifest field names rather than a hardcoded
+ // pair, so this cannot silently drop the values if a manifest ever labels the
+ // fields differently. For the 8 baked providers these resolve to
+ // client_id/client_secret (the canonical Secret keys control-api writes).
+ const idField = manifest.find(f => !f.secret)?.name ?? CLIENT_ID_FIELD
+ const secretField = manifest.find(f => f.secret)?.name ?? CLIENT_SECRET_FIELD
+ return {
+ mode: 'managed',
+ clientId: (credValues[idField] ?? '').trim(),
+ clientSecret: credValues[secretField] ?? '',
+ }
+ }
+
+ async function handleInstall() {
+ if (!canInstall || installInFlightRef.current) return
+ installInFlightRef.current = true
+ setInstalling(true)
+ setSubmitError('')
+ try {
+ const contextRef = await createPrivateContext(
+ {
+ subject: serverName || entry.name,
+ description: `Connector access scope for ${serverName || entry.name}`,
+ },
+ 'We couldn’t prepare this connector’s access — please try again.'
+ )
+ await installFromRegistry({
+ serverName: serverName || undefined,
+ contextRef,
+ registryEntryName: entry.name,
+ registryEntryVersion: entry.version,
+ oauth: {
+ scopes,
+ grantScope,
+ secret: buildSecretInput(),
+ },
+ })
+ // Drop the typed client_secret from component state on success so it is
+ // never held in the DOM after the request that consumed it (S-2).
+ setCredValues({})
+ setInstalled(true)
+ onInstalled()
+ } catch (error) {
+ setSubmitError(error instanceof Error ? error.message : 'Installation failed')
+ } finally {
+ installInFlightRef.current = false
+ setInstalling(false)
+ }
+ }
+
+ return (
+ <>
+ <CreateStepFlow
+ ariaLabel="Install OAuth connector steps"
+ className="cu-create-step-flow--3"
+ currentStep={step}
+ onStepChange={setStep}
+ canSelectStep={canSelectStep}
+ steps={STEP_DETAILS}
+ stepLabels={STEPS}
+ titleId="oauth-install-step-title"
+ >
+ <form
+ className="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide"
+ onSubmit={event => {
+ event.preventDefault()
+ if (step < STEPS.length - 1) {
+ if (canContinue) setStep(current => Math.min(STEPS.length - 1, current + 1))
+ return
+ }
+ void handleInstall()
+ }}
+ >
+ {step === 0 ? (
+ <div className="cu-form-section">
+ <div className="cu-form-section__header">
+ <h3 className="cu-form-section__title">Register the OAuth app</h3>
+ <p className="cu-form-section__description">
+ Create an OAuth app for <strong>{providerLabel}</strong> and register the exact
+ redirect URI below. control-api derives the callback id from the connector name.
+ </p>
+ </div>
+
+ <Field
+ htmlFor="oauth-server-name"
+ label="Connector name"
+ description="Used to derive the OAuth callback id. Lowercase letters, digits, and hyphens."
+ error={
+ serverName && !nameValid
+ ? 'Must be a valid Kubernetes name (max 63 chars).'
+ : undefined
+ }
+ >
+ <TextInput
+ id="oauth-server-name"
+ value={serverName}
+ onChange={event =>
+ setServerName(event.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
+ }
+ placeholder="my-oauth-connector"
+ />
+ </Field>
+
+ <Field
+ htmlFor="oauth-derived-id"
+ label="Callback id (auto-derived)"
+ description="control-api owns this id and checks it is unique; it cannot be typed."
+ >
+ <TextInput id="oauth-derived-id" value={derivedId} readOnly monospace />
+ </Field>
+
+ <Field
+ label="Redirect URI"
+ description="Register this exact URI in the provider’s OAuth app."
+ >
+ {!callbackConfigured ? (
+ // Real config error: the deployment has no public callback base URL.
+ <div className="cu-banner cu-banner--warn" role="alert">
+ The public OAuth callback URL is not configured for this deployment
+ (CONTROL_API_OAUTH_CALLBACK_BASE_URL). Configure it before installing an OAuth
+ connector — the install will be rejected otherwise.
+ </div>
+ ) : redirectUri ? (
+ <div className="cu-table-actions">
+ <TextInput value={redirectUri} readOnly monospace aria-label="Redirect URI" />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ icon
+ onClick={handleCopyRedirectUri}
+ aria-label="Copy redirect URI"
+ >
+ <IconCopy width={16} height={16} />
+ </Button>
+ </div>
+ ) : (
+ // Config is fine; the name is just empty, so there is no id yet.
+ // Prompt for the name instead of a false configuration error.
+ <p className="cu-field__hint" role="status">
+ Enter a connector name above to generate the redirect URI.
+ </p>
+ )}
+ </Field>
+
+ {docUrl ? (
+ <p className="cu-field__hint">
+ <a href={docUrl} target="_blank" rel="noreferrer noopener">
+ {providerLabel} OAuth app documentation
+ </a>
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+
+ {step === 1 ? (
+ <div className="cu-form-section">
+ <div className="cu-form-section__header">
+ <h3 className="cu-form-section__title">Client credentials</h3>
+ <p className="cu-form-section__description">
+ Only the broker reads these — they are never mounted in the connector pod.
+ </p>
+ </div>
+
+ <Field
+ htmlFor="oauth-secret-mode"
+ label="Secret source"
+ description="Type the client credentials, or reference an existing Secret by name and keys."
+ >
+ <SelectInput
+ id="oauth-secret-mode"
+ value={secretMode}
+ onChange={event => setSecretMode(event.target.value as 'managed' | 'reference')}
+ >
+ <option value="managed">Managed — enter client id and secret</option>
+ <option value="reference">Reference — use an existing Secret</option>
+ </SelectInput>
+ </Field>
+
+ {loadError ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ {loadError}
+ </div>
+ ) : null}
+
+ {secretMode === 'managed'
+ ? manifest.map(field => (
+ <Field
+ key={field.name}
+ htmlFor={`oauth-cred-${field.name}`}
+ label={field.label}
+ description={field.help}
+ required={field.required}
+ >
+ <TextInput
+ id={`oauth-cred-${field.name}`}
+ type={field.secret ? 'password' : 'text'}
+ autoComplete={field.secret ? 'new-password' : 'off'}
+ value={credValues[field.name] ?? ''}
+ onChange={event =>
+ setCredValues(previous => ({
+ ...previous,
+ [field.name]: event.target.value,
+ }))
+ }
+ placeholder={field.label}
+ />
+ </Field>
+ ))
+ : null}
+
+ {secretMode === 'reference' ? (
+ <>
+ <Field
+ htmlFor="oauth-ref-secret"
+ label="Existing Secret"
+ description="An existing Secret in the MCP servers namespace."
+ required
+ >
+ <SelectInput
+ id="oauth-ref-secret"
+ value={refSecretName}
+ onChange={event => setRefSecretName(event.target.value)}
+ >
+ <option value="">Select a Secret…</option>
+ {secrets.map(secret => (
+ <option key={secret.name} value={secret.name}>
+ {secret.name}
+ </option>
+ ))}
+ </SelectInput>
+ </Field>
+ <Field htmlFor="oauth-ref-id-key" label="Client ID key" required>
+ <TextInput
+ id="oauth-ref-id-key"
+ value={refClientIdKey}
+ onChange={event => setRefClientIdKey(event.target.value)}
+ monospace
+ />
+ </Field>
+ <Field htmlFor="oauth-ref-secret-key" label="Client Secret key" required>
+ <TextInput
+ id="oauth-ref-secret-key"
+ value={refClientSecretKey}
+ onChange={event => setRefClientSecretKey(event.target.value)}
+ monospace
+ />
+ </Field>
+ {referenceIssue ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ {referenceIssue}
+ </div>
+ ) : (
+ <div className="cu-banner cu-banner--info" role="status">
+ Secret and keys verified.
+ </div>
+ )}
+ </>
+ ) : null}
+ </div>
+ ) : null}
+
+ {step === 2 ? (
+ <div className="cu-form-section">
+ <div className="cu-form-section__header">
+ <h3 className="cu-form-section__title">Scopes and install</h3>
+ <p className="cu-form-section__description">
+ Grant type is fixed once installed. Scopes prefill from the catalog and can be
+ edited per connector.
+ </p>
+ </div>
+
+ <Field
+ htmlFor="oauth-grant-scope"
+ label="Grant type"
+ description="user: a token per end user. context: one shared identity."
+ >
+ <SelectInput
+ id="oauth-grant-scope"
+ value={grantScope}
+ onChange={event => setGrantScope(event.target.value as OAuthGrantScope)}
+ >
+ <option value="user">Per user</option>
+ <option value="context">Shared (context)</option>
+ </SelectInput>
+ </Field>
+
+ <Field
+ htmlFor="oauth-scopes"
+ label="Scopes"
+ description="One scope per line (or space/comma separated). At least one is required."
+ required
+ error={!scopesOk ? 'Add at least one OAuth scope for this connector.' : undefined}
+ >
+ <TextAreaInput
+ id="oauth-scopes"
+ value={scopesText}
+ onChange={event => setScopesText(event.target.value)}
+ rows={4}
+ monospace
+ placeholder="offline_access"
+ />
+ </Field>
+
+ <section className="cu-summary-list" aria-label="OAuth install summary">
+ <div className="cu-summary-list__row">
+ <span>Provider</span>
+ <strong>{providerLabel}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Connector</span>
+ <strong>{serverName || '-'}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Callback id</span>
+ <strong>{derivedId || '-'}</strong>
+ </div>
+ <div className="cu-summary-list__row">
+ <span>Scopes</span>
+ <strong>{scopes.length > 0 ? scopes.join(', ') : '-'}</strong>
+ </div>
+ </section>
+
+ {!callbackConfigured ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ The public OAuth callback URL is not configured, so this install would be
+ rejected. Configure CONTROL_API_OAUTH_CALLBACK_BASE_URL and reload.
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+
+ {submitError ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ {submitError}
+ </div>
+ ) : null}
+
+ <div className="cu-create-actions">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={installing}
+ onClick={() => (step === 0 ? onCancel() : setStep(current => current - 1))}
+ >
+ {step === 0 ? 'Cancel' : 'Back'}
+ </Button>
+ {step < STEPS.length - 1 ? (
+ <Button type="submit" variant="primary" size="sm" disabled={loading || !canContinue}>
+ Continue
+ </Button>
+ ) : (
+ <Button type="submit" variant="primary" size="sm" disabled={!canInstall}>
+ {installing ? 'Installing…' : 'Install connector'}
+ </Button>
+ )}
+ </div>
+ </form>
+ </CreateStepFlow>
+
+ {installed ? (
+ <div className="cu-modal-backdrop" role="presentation">
+ <section
+ className="cu-modal-panel cu-modal-panel--install-success"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="oauth-install-success-title"
+ aria-describedby="oauth-install-success-copy"
+ >
+ <div className="cu-registry-install-success__icon" aria-hidden="true">
+ <IconCheck width={26} height={26} />
+ </div>
+ <div className="cu-registry-install-success__content">
+ <p className="cu-registry-install-success__eyebrow">Connector installed</p>
+ <h2 id="oauth-install-success-title" className="cu-modal-panel__title">
+ OAuth connector installed
+ </h2>
+ <p id="oauth-install-success-copy" className="cu-modal-copy">
+ <strong>{serverName}</strong> is installed. Connect an account and grant agent
+ access from the Installed Connectors list whenever you’re ready.
+ </p>
+ </div>
+ <div className="cu-modal-panel__foot cu-registry-install-success__actions">
+ <Button
+ type="button"
+ variant="primary"
+ onClick={() => onViewConnectors?.()}
+ disabled={!onViewConnectors}
+ >
+ Go to Connectors
+ </Button>
+ </div>
+ </section>
+ </div>
+ ) : null}
+ </>
+ )
+}
diff --git a/control-ui/components/OAuthInstallForm/types.ts b/control-ui/components/OAuthInstallForm/types.ts
new file mode 100644
index 000000000..57e00fd6d
--- /dev/null
+++ b/control-ui/components/OAuthInstallForm/types.ts
@@ -0,0 +1,12 @@
+import type { RegistryEntry } from '@lib/api'
+import type { CatalogOAuthBlock } from '@lib/oauthInstall.types'
+
+export type OAuthInstallFormProps = {
+ entry: RegistryEntry
+ // The validated `mcp_server_meta.oauth` block; presence is what routes the
+ // install here instead of the ordinary connector form.
+ catalogOAuth: CatalogOAuthBlock
+ onCancel: () => void
+ onInstalled: () => void
+ onViewConnectors?: () => void
+}
diff --git a/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx b/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
index 58ea7cb59..5f338e6f0 100644
--- a/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
+++ b/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
@@ -388,6 +388,56 @@ describe('EditMcpServerPage — credential surface wiring', () => {
expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()
})
+ // ─── OAuth connectors: the credentials tab must NOT lie ──────────────────
+ //
+ // An OAuth server keeps its client credential in the clientSecretRef Secret,
+ // not spec.envSecret, so UpdateConnectorCredentials would fall to its
+ // "nothing to rotate here" branch. The page must render the accurate OAuth
+ // panel instead (D-B7; rotation is a follow-up).
+ function oauthServer(): McpServerResource {
+ return {
+ metadata: { name: SERVER_NAME, namespace: NAMESPACE },
+ spec: {
+ image: CONNECTOR_IMAGE,
+ contextRef: 'default',
+ auth: { type: 'oauth' },
+ oauth: {
+ id: SERVER_NAME,
+ provider: 'google',
+ grantScope: 'user',
+ scopes: ['a.read'],
+ clientIdRef: { name: `${SERVER_NAME}-oauth-client`, key: 'client_id' },
+ clientSecretRef: { name: `${SERVER_NAME}-oauth-client`, key: 'client_secret' },
+ },
+ },
+ } as unknown as McpServerResource
+ }
+
+ it('shows the accurate OAuth panel and never the false "nothing to rotate" message', async () => {
+ mockGetMcpServer.mockResolvedValue(oauthServer())
+ render(
+ <ToastProvider>
+ <EditMcpServerPage />
+ </ToastProvider>
+ )
+
+ // The OAuth panel — not UpdateConnectorCredentials — owns the credentials tab.
+ await screen.findByRole('heading', { name: 'OAuth configuration' })
+
+ // The false message must be gone entirely.
+ expect(screen.queryByText(/nothing to rotate/i)).toBeNull()
+ expect(screen.queryByRole('heading', { name: /^(Update|Set) credentials$/ })).toBeNull()
+
+ // The accurate notice names the Secret, says rotation is not available yet,
+ // and points at kubectl.
+ expect(screen.getByText(/authenticates with OAuth/i)).toBeInTheDocument()
+ expect(screen.getByText(`${SERVER_NAME}-oauth-client`)).toBeInTheDocument()
+ expect(
+ screen.getByText(/Rotating it from this screen is not available yet/i)
+ ).toBeInTheDocument()
+ expect(screen.getByText(/kubectl/i)).toBeInTheDocument()
+ })
+
it('honors a NEWER SecretNotFound over a stale clean resolution', async () => {
await renderPage(
mcpServer({
diff --git a/control-ui/components/__tests__/OAuthImmutableFields.test.tsx b/control-ui/components/__tests__/OAuthImmutableFields.test.tsx
new file mode 100644
index 000000000..331a0cedb
--- /dev/null
+++ b/control-ui/components/__tests__/OAuthImmutableFields.test.tsx
@@ -0,0 +1,47 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { cleanup, render, screen } from '@testing-library/react'
+import { OAuthImmutableFields } from '../OAuthImmutableFields'
+
+afterEach(cleanup)
+
+describe('OAuthImmutableFields — immutables read-only in edit (D-B7)', () => {
+ it('renders id, provider, and grantScope read-only and non-editable', () => {
+ render(<OAuthImmutableFields oauth={{ id: 'acme', provider: 'google', grantScope: 'user' }} />)
+
+ const provider = screen.getByLabelText('Provider') as HTMLInputElement
+ const callbackId = screen.getByLabelText('Callback id') as HTMLInputElement
+ const grant = screen.getByLabelText('Grant type') as HTMLInputElement
+
+ // The immutable values are shown…
+ expect(provider.value).toBe('Google')
+ expect(callbackId.value).toBe('acme')
+ expect(grant.value).toBe('Per user')
+
+ // …but every one is read-only and disabled, so the operator cannot change a
+ // CEL-immutable field (a change means delete + recreate).
+ for (const input of [provider, callbackId, grant]) {
+ expect(input).toHaveAttribute('readonly')
+ expect(input).toBeDisabled()
+ }
+ })
+
+ it('does not render an editable scopes control (scopes is not immutable, handled elsewhere)', () => {
+ render(
+ <OAuthImmutableFields oauth={{ id: 'acme', provider: 'slack', grantScope: 'context' }} />
+ )
+ expect(screen.queryByLabelText('Scopes')).toBeNull()
+ })
+
+ it('renders an accurate credential notice naming the Secret, without a false "nothing to rotate"', () => {
+ render(
+ <OAuthImmutableFields
+ oauth={{ id: 'acme', provider: 'google', grantScope: 'user' }}
+ credentialSecretName="acme-oauth-client"
+ />
+ )
+ expect(screen.getByText(/authenticates with OAuth/i)).toBeInTheDocument()
+ expect(screen.getByText('acme-oauth-client')).toBeInTheDocument()
+ expect(screen.getByText(/not available yet/i)).toBeInTheDocument()
+ expect(screen.queryByText(/nothing to rotate/i)).toBeNull()
+ })
+})
diff --git a/control-ui/components/__tests__/OAuthInstallForm.test.tsx b/control-ui/components/__tests__/OAuthInstallForm.test.tsx
new file mode 100644
index 000000000..be2d09cde
--- /dev/null
+++ b/control-ui/components/__tests__/OAuthInstallForm.test.tsx
@@ -0,0 +1,285 @@
+import type { ReactNode } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
+import * as api from '../../lib/api'
+import type { CatalogOAuthBlock } from '../../lib/oauthInstall.types'
+import { OAuthInstallForm } from '../OAuthInstallForm'
+import { ToastProvider } from '../Toast'
+
+// The credential manifest fixture is the exact shape control-api's
+// GET /admin/oauth/providers/:id/credential-manifest returns for a baked
+// provider — verified against CONFIDENTIAL_CLIENT_MANIFEST in
+// control-api/src/oauth/providers.ts (T1: derived from the real producer, not
+// invented). All 8 baked providers share this shape.
+const MANIFEST = {
+ provider: 'google',
+ fields: [
+ { name: 'client_id', label: 'Client ID', secret: false, required: true },
+ { name: 'client_secret', label: 'Client Secret', secret: true, required: true },
+ ],
+}
+
+vi.mock('../../lib/api', () => ({
+ apiSend: vi.fn().mockResolvedValue({}),
+ getOAuthCredentialManifest: vi.fn(),
+ listMcpSecrets: vi.fn(),
+ installFromRegistry: vi.fn().mockResolvedValue({ serverName: 'acme', namespace: 'mcp-server' }),
+}))
+
+const ENTRY = {
+ id: '1',
+ name: 'acme',
+ version: '1.0.0',
+ entry_type: 'mcp-server',
+ description: 'Acme OAuth connector',
+ mcp_server_meta: {},
+} as api.RegistryEntry
+
+function render(children: ReactNode) {
+ return rtlRender(<ToastProvider>{children}</ToastProvider>)
+}
+
+function renderForm(catalogOAuth: CatalogOAuthBlock) {
+ return render(
+ <OAuthInstallForm
+ entry={ENTRY}
+ catalogOAuth={catalogOAuth}
+ onCancel={vi.fn()}
+ onInstalled={vi.fn()}
+ onViewConnectors={vi.fn()}
+ />
+ )
+}
+
+async function waitForLoaded(): Promise<void> {
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Continue' })).not.toBeDisabled())
+}
+
+beforeEach(() => {
+ vi.stubEnv('NEXT_PUBLIC_CONTROL_API_OAUTH_CALLBACK_BASE_URL', 'https://oauth.example.com')
+ vi.mocked(api.getOAuthCredentialManifest).mockResolvedValue(MANIFEST)
+ vi.mocked(api.listMcpSecrets).mockResolvedValue({ items: [] })
+})
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+ vi.unstubAllEnvs()
+})
+
+describe('OAuthInstallForm — scopes reach the submit (Fam A(3)/E-19.3)', () => {
+ it('sends the operator-edited scopes in body.oauth.scopes', async () => {
+ renderForm({ provider: 'google', grantScope: 'user', scopes: ['a.read'] })
+ await waitForLoaded()
+
+ // Provider → Credentials
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ fireEvent.change(screen.getByLabelText('Client ID', { exact: false }), {
+ target: { value: 'cid' },
+ })
+ fireEvent.change(screen.getByLabelText('Client Secret', { exact: false }), {
+ target: { value: 'csecret' },
+ })
+
+ // Credentials → Scopes and install
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ fireEvent.change(screen.getByRole('textbox', { name: /Scopes/i }), {
+ target: { value: 'a.read b.write' },
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'Install connector' }))
+
+ await waitFor(() => expect(api.installFromRegistry).toHaveBeenCalledTimes(1))
+ const req = vi.mocked(api.installFromRegistry).mock.calls[0][0]
+ expect(req.oauth?.scopes).toEqual(['a.read', 'b.write'])
+ expect(req.oauth?.grantScope).toBe('user')
+ // oauth.id is never sent — control-api derives it (D-B5).
+ expect(req.oauth).not.toHaveProperty('id')
+ })
+})
+
+describe('OAuthInstallForm — empty scope prefill forces scopes (GAP-6)', () => {
+ it('blocks Install until at least one scope is entered', async () => {
+ renderForm({ provider: 'google', grantScope: 'user', scopes: [] })
+ await waitForLoaded()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ fireEvent.change(screen.getByLabelText('Client ID', { exact: false }), {
+ target: { value: 'cid' },
+ })
+ fireEvent.change(screen.getByLabelText('Client Secret', { exact: false }), {
+ target: { value: 'csecret' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+
+ // Empty scopes: Install disabled + explicit guidance.
+ const install = screen.getByRole('button', { name: 'Install connector' })
+ expect(install).toBeDisabled()
+ expect(screen.getByText(/Add at least one OAuth scope/i)).toBeInTheDocument()
+
+ fireEvent.change(screen.getByRole('textbox', { name: /Scopes/i }), {
+ target: { value: 'offline_access' },
+ })
+ expect(screen.getByRole('button', { name: 'Install connector' })).not.toBeDisabled()
+ })
+})
+
+describe('OAuthInstallForm — reference mode pre-check (Fam B(1))', () => {
+ it('warns and blocks continue when the referenced key does not exist', async () => {
+ vi.mocked(api.listMcpSecrets).mockResolvedValue({
+ items: [{ name: 'gh-oauth', keys: ['client_id', 'client_secret'] }],
+ })
+ renderForm({ provider: 'google', grantScope: 'user', scopes: ['a.read'] })
+ await waitForLoaded()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ fireEvent.change(screen.getByLabelText('Secret source'), { target: { value: 'reference' } })
+
+ // Pick the existing Secret but a key it does not carry.
+ fireEvent.change(screen.getByLabelText('Existing Secret', { exact: false }), {
+ target: { value: 'gh-oauth' },
+ })
+ fireEvent.change(screen.getByLabelText('Client Secret key', { exact: false }), {
+ target: { value: 'nope' },
+ })
+
+ expect(screen.getByText(/missing key\(s\): nope/i)).toBeInTheDocument()
+ // Continue to the install step is blocked while the reference is invalid.
+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled()
+
+ // Fixing the key clears the warning and unblocks continue.
+ fireEvent.change(screen.getByLabelText('Client Secret key', { exact: false }), {
+ target: { value: 'client_secret' },
+ })
+ expect(screen.getByText(/Secret and keys verified/i)).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Continue' })).not.toBeDisabled()
+ })
+})
+
+describe('OAuthInstallForm — manifest load failure blocks the managed gate', () => {
+ it('keeps Continue disabled on the credentials step when the manifest fails to load', async () => {
+ vi.mocked(api.getOAuthCredentialManifest).mockRejectedValue(new Error('manifest boom'))
+ renderForm({ provider: 'google', grantScope: 'user', scopes: ['a.read'] })
+ await waitForLoaded()
+
+ // Provider → Credentials
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+
+ // The load error is surfaced and no credential fields render…
+ expect(await screen.findByText('manifest boom')).toBeInTheDocument()
+ expect(screen.queryByLabelText('Client ID', { exact: false })).toBeNull()
+ // …so the empty manifest must NOT vacuously satisfy the managed gate.
+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled()
+ })
+})
+
+describe('OAuthInstallForm — callback base URL not configured', () => {
+ it('shows the not-configured notice and disables install', async () => {
+ vi.stubEnv('NEXT_PUBLIC_CONTROL_API_OAUTH_CALLBACK_BASE_URL', '')
+ renderForm({ provider: 'google', grantScope: 'user', scopes: ['a.read'] })
+ await waitForLoaded()
+
+ // Step 0 shows the not-configured warning instead of a (broken) redirect URI.
+ expect(screen.getByText(/public OAuth callback URL is not configured/i)).toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ fireEvent.change(screen.getByLabelText('Client ID', { exact: false }), {
+ target: { value: 'cid' },
+ })
+ fireEvent.change(screen.getByLabelText('Client Secret', { exact: false }), {
+ target: { value: 'csecret' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+
+ // Even with complete credentials and scopes, install is blocked.
+ expect(screen.getByRole('button', { name: 'Install connector' })).toBeDisabled()
+ })
+
+ it('does NOT show the config error when only the name is empty (config is fine)', async () => {
+ // Base URL IS configured (beforeEach), so an empty name must not masquerade
+ // as a configuration error.
+ renderForm({ provider: 'google', grantScope: 'user', scopes: ['a.read'] })
+ await waitForLoaded()
+
+ fireEvent.change(screen.getByLabelText('Connector name'), { target: { value: '' } })
+
+ expect(screen.queryByText(/is not configured/i)).toBeNull()
+ expect(
+ screen.getByText(/Enter a connector name above to generate the redirect URI/i)
+ ).toBeInTheDocument()
+ // No id derivable from a blank name, so Continue is blocked.
+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled()
+ })
+})
+
+describe('OAuthInstallForm — reference mode submit body', () => {
+ it('sends a reference secret with the chosen Secret name and keys', async () => {
+ vi.mocked(api.listMcpSecrets).mockResolvedValue({
+ items: [{ name: 'gh-oauth', keys: ['client_id', 'client_secret'] }],
+ })
+ renderForm({ provider: 'google', grantScope: 'context', scopes: ['a.read'] })
+ await waitForLoaded()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ fireEvent.change(screen.getByLabelText('Secret source'), { target: { value: 'reference' } })
+ fireEvent.change(screen.getByLabelText('Existing Secret', { exact: false }), {
+ target: { value: 'gh-oauth' },
+ })
+ // Default keys (client_id / client_secret) already match the Secret.
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Install connector' }))
+
+ await waitFor(() => expect(api.installFromRegistry).toHaveBeenCalledTimes(1))
+ const req = vi.mocked(api.installFromRegistry).mock.calls[0][0]
+ expect(req.oauth?.secret).toEqual({
+ mode: 'reference',
+ secretName: 'gh-oauth',
+ clientIdKey: 'client_id',
+ clientSecretKey: 'client_secret',
+ })
+ expect(req.oauth?.grantScope).toBe('context')
+ })
+})
+
+describe('OAuthInstallForm — client_secret confidentiality (S-2, UI side)', () => {
+ it('never leaves the typed client_secret in the DOM after submit and never logs it', async () => {
+ const SECRET = 'super-secret-value-42'
+ const consoleSpies = [
+ vi.spyOn(console, 'log').mockImplementation(() => {}),
+ vi.spyOn(console, 'error').mockImplementation(() => {}),
+ vi.spyOn(console, 'warn').mockImplementation(() => {}),
+ vi.spyOn(console, 'info').mockImplementation(() => {}),
+ ]
+
+ renderForm({ provider: 'google', grantScope: 'user', scopes: ['a.read'] })
+ await waitForLoaded()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ fireEvent.change(screen.getByLabelText('Client ID', { exact: false }), {
+ target: { value: 'cid' },
+ })
+ fireEvent.change(screen.getByLabelText('Client Secret', { exact: false }), {
+ target: { value: SECRET },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Install connector' }))
+
+ // The secret rides the submit body once…
+ await waitFor(() => expect(api.installFromRegistry).toHaveBeenCalledTimes(1))
+ const req = vi.mocked(api.installFromRegistry).mock.calls[0][0]
+ expect(req.oauth?.secret).toMatchObject({ mode: 'managed', clientSecret: SECRET })
+
+ // …then the success view renders and the secret is gone from the DOM.
+ await screen.findByRole('heading', { name: 'OAuth connector installed' })
+ expect(screen.queryByDisplayValue(SECRET)).toBeNull()
+ expect(document.body.textContent).not.toContain(SECRET)
+
+ // And it was never written to any console channel.
+ for (const spy of consoleSpies) {
+ for (const call of spy.mock.calls) {
+ expect(JSON.stringify(call)).not.toContain(SECRET)
+ }
+ spy.mockRestore()
+ }
+ })
+})
diff --git a/control-ui/lib/__tests__/oauthInstall.test.ts b/control-ui/lib/__tests__/oauthInstall.test.ts
new file mode 100644
index 000000000..95d2dc92e
--- /dev/null
+++ b/control-ui/lib/__tests__/oauthInstall.test.ts
@@ -0,0 +1,201 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { RegistryEntry } from '../api'
+import {
+ buildOAuthRedirectUri,
+ deriveOAuthClientIdPreview,
+ extractOAuthImmutables,
+ formatScopesForInput,
+ getCatalogOAuthBlock,
+ oauthCallbackBaseUrl,
+ parseScopesInput,
+ referenceSecretIssue,
+ scopesAreSatisfied,
+} from '../oauthInstall'
+
+// Minimal RegistryEntry with only the fields getCatalogOAuthBlock reads. The
+// `mcp_server_meta.oauth` shape is the frozen S1-U1 catalog contract (spec §5).
+function entryWithOAuth(oauth: unknown): RegistryEntry {
+ return {
+ name: 'acme',
+ version: '1.0.0',
+ entry_type: 'mcp-server',
+ mcp_server_meta: { oauth } as Record<string, unknown>,
+ } as RegistryEntry
+}
+
+afterEach(() => {
+ vi.unstubAllEnvs()
+})
+
+describe('deriveOAuthClientIdPreview', () => {
+ it('mirrors the control-api derivation (lowercase, hyphen-collapsed, trimmed)', () => {
+ // Matches control-api deriveOAuthClientId (routes/admin/registry.ts).
+ expect(deriveOAuthClientIdPreview('Acme_Connector')).toBe('acme-connector')
+ expect(deriveOAuthClientIdPreview('--a--b--')).toBe('a-b')
+ expect(deriveOAuthClientIdPreview('UPPER')).toBe('upper')
+ })
+
+ it('truncates to 63 characters', () => {
+ expect(deriveOAuthClientIdPreview('a'.repeat(80))).toHaveLength(63)
+ })
+})
+
+describe('buildOAuthRedirectUri', () => {
+ it('joins the base and callback path with the id encoded', () => {
+ expect(buildOAuthRedirectUri('https://oauth.example.com', 'acme')).toBe(
+ 'https://oauth.example.com/api/v1/oauth-callback/acme'
+ )
+ })
+
+ it('strips a trailing slash from the base', () => {
+ expect(buildOAuthRedirectUri('https://oauth.example.com/', 'acme')).toBe(
+ 'https://oauth.example.com/api/v1/oauth-callback/acme'
+ )
+ })
+
+ it('returns null when the base is missing or blank (no broken URI)', () => {
+ expect(buildOAuthRedirectUri('', 'acme')).toBeNull()
+ expect(buildOAuthRedirectUri(' ', 'acme')).toBeNull()
+ expect(buildOAuthRedirectUri(undefined, 'acme')).toBeNull()
+ })
+
+ it('returns null when the id is empty', () => {
+ expect(buildOAuthRedirectUri('https://oauth.example.com', '')).toBeNull()
+ })
+})
+
+describe('oauthCallbackBaseUrl', () => {
+ it('reads the NEXT_PUBLIC env lazily and trims it', () => {
+ vi.stubEnv('NEXT_PUBLIC_CONTROL_API_OAUTH_CALLBACK_BASE_URL', ' https://oauth.example.com ')
+ expect(oauthCallbackBaseUrl()).toBe('https://oauth.example.com')
+ })
+
+ it('is empty when the env is unset', () => {
+ vi.stubEnv('NEXT_PUBLIC_CONTROL_API_OAUTH_CALLBACK_BASE_URL', '')
+ expect(oauthCallbackBaseUrl()).toBe('')
+ })
+})
+
+describe('getCatalogOAuthBlock', () => {
+ it('extracts a valid block and keeps only understood fields', () => {
+ const block = getCatalogOAuthBlock(
+ entryWithOAuth({
+ provider: 'google',
+ grantScope: 'context',
+ scopes: ['a.read', 'b.read'],
+ genericConfig: { endpoints: {} },
+ })
+ )
+ expect(block).toEqual({
+ provider: 'google',
+ grantScope: 'context',
+ scopes: ['a.read', 'b.read'],
+ })
+ // genericConfig is Slice-3-only and must never leak into Slice-1 state.
+ expect(block).not.toHaveProperty('genericConfig')
+ })
+
+ it('returns null when there is no oauth block', () => {
+ expect(getCatalogOAuthBlock(entryWithOAuth(undefined))).toBeNull()
+ expect(getCatalogOAuthBlock({ mcp_server_meta: null } as RegistryEntry)).toBeNull()
+ expect(getCatalogOAuthBlock(null)).toBeNull()
+ })
+
+ it('returns null when the provider is missing', () => {
+ expect(getCatalogOAuthBlock(entryWithOAuth({ scopes: ['x'] }))).toBeNull()
+ })
+
+ it('drops an invalid grantScope rather than trusting it', () => {
+ const block = getCatalogOAuthBlock(entryWithOAuth({ provider: 'slack', grantScope: 'admin' }))
+ expect(block).toEqual({ provider: 'slack' })
+ })
+})
+
+describe('parseScopesInput / formatScopesForInput', () => {
+ it('splits on whitespace, newlines and commas and de-duplicates', () => {
+ expect(parseScopesInput('a.read b.read\nc.read, a.read')).toEqual([
+ 'a.read',
+ 'b.read',
+ 'c.read',
+ ])
+ })
+
+ it('is empty for whitespace-only input', () => {
+ expect(parseScopesInput(' \n ')).toEqual([])
+ })
+
+ it('round-trips a list to one-per-line text', () => {
+ expect(formatScopesForInput(['a', 'b'])).toBe('a\nb')
+ })
+})
+
+describe('scopesAreSatisfied', () => {
+ it('requires at least one scope (GAP-6)', () => {
+ expect(scopesAreSatisfied([])).toBe(false)
+ expect(scopesAreSatisfied(['a.read'])).toBe(true)
+ })
+})
+
+describe('referenceSecretIssue', () => {
+ const secrets = [{ name: 'gh-oauth', keys: ['client_id', 'client_secret'] }]
+
+ it('accepts an existing Secret with both keys present', () => {
+ expect(
+ referenceSecretIssue(
+ { secretName: 'gh-oauth', clientIdKey: 'client_id', clientSecretKey: 'client_secret' },
+ secrets
+ )
+ ).toBeNull()
+ })
+
+ it('flags a missing Secret', () => {
+ expect(
+ referenceSecretIssue(
+ { secretName: 'absent', clientIdKey: 'client_id', clientSecretKey: 'client_secret' },
+ secrets
+ )
+ ).toMatch(/not found/)
+ })
+
+ it('flags a missing key on an existing Secret', () => {
+ expect(
+ referenceSecretIssue(
+ { secretName: 'gh-oauth', clientIdKey: 'client_id', clientSecretKey: 'nope' },
+ secrets
+ )
+ ).toMatch(/missing key\(s\): nope/)
+ })
+
+ it('requires a chosen Secret and named keys', () => {
+ expect(
+ referenceSecretIssue({ secretName: '', clientIdKey: 'a', clientSecretKey: 'b' }, secrets)
+ ).toMatch(/Choose an existing Secret/)
+ expect(
+ referenceSecretIssue(
+ { secretName: 'gh-oauth', clientIdKey: '', clientSecretKey: '' },
+ secrets
+ )
+ ).toMatch(/Name the Client ID key/)
+ })
+})
+
+describe('extractOAuthImmutables', () => {
+ it('reads id, provider, and grantScope off spec.oauth', () => {
+ expect(
+ extractOAuthImmutables({
+ oauth: { id: 'acme', provider: 'google', grantScope: 'user', scopes: ['x'] },
+ })
+ ).toEqual({ id: 'acme', provider: 'google', grantScope: 'user' })
+ })
+
+ it('returns null when there is no oauth block', () => {
+ expect(extractOAuthImmutables({})).toBeNull()
+ expect(extractOAuthImmutables(undefined)).toBeNull()
+ })
+
+ it('blanks an invalid grantScope', () => {
+ expect(
+ extractOAuthImmutables({ oauth: { id: 'a', provider: 'slack', grantScope: 'x' } })
+ ).toEqual({ id: 'a', provider: 'slack', grantScope: '' })
+ })
+})
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index 66ed6a69f..57c856150 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -1,5 +1,10 @@
'use client'
+import type {
+ McpSecretSummary,
+ OAuthCredentialManifest,
+ OAuthInstallSubmit,
+} from './oauthInstall.types'
import {
DEFAULT_MCP_SERVER_SECRET_NAMESPACE,
DEFAULT_SANDBOX_SECRET_NAMESPACE,
@@ -3183,6 +3188,28 @@ export async function getRegistryCredentialSchema(
) as Promise<CredentialSchema>
}
+/**
+ * The credential-form manifest for a baked OAuth provider (S1-U4, D-B1). control-ui
+ * renders the install form from `fields`; `secret: true` fields are masked and never
+ * echoed back. control-api 404s for a non-baked provider id.
+ */
+export async function getOAuthCredentialManifest(
+ provider: string
+): Promise<OAuthCredentialManifest> {
+ return apiGet(
+ `/api/v1/admin/oauth/providers/${encodeURIComponent(provider)}/credential-manifest`
+ ) as Promise<OAuthCredentialManifest>
+}
+
+/**
+ * Lists MCP Server Secrets as names + keys only — never values (E-16.1). The OAuth
+ * install wizard's reference mode uses this to verify that a chosen Secret and its
+ * id/secret keys exist before the operator submits (D-B3 / Fam. B(1)).
+ */
+export async function listMcpSecrets(): Promise<{ items: McpSecretSummary[] }> {
+ return apiGet('/api/v1/admin/mcp-secrets') as Promise<{ items: McpSecretSummary[] }>
+}
+
export type InstallFromRegistryRequest = {
serverName?: string
namespace?: string
@@ -3191,6 +3218,10 @@ export type InstallFromRegistryRequest = {
registryEntryVersion: string
credentials?: Record<string, string>
egressBindings?: EgressBinding[]
+ // Present only when the catalog entry declares OAuth (S1-U4). `oauth.id` is
+ // never sent — control-api derives and validates it (D-B5). The client_secret
+ // in `oauth.secret` (managed mode) lives only in this request body.
+ oauth?: OAuthInstallSubmit
}
export type InstallFromRegistryResponse = {
diff --git a/control-ui/lib/oauthInstall.ts b/control-ui/lib/oauthInstall.ts
new file mode 100644
index 000000000..5a01a73e3
--- /dev/null
+++ b/control-ui/lib/oauthInstall.ts
@@ -0,0 +1,192 @@
+import type { RegistryEntry } from './api'
+import type {
+ CatalogOAuthBlock,
+ McpSecretSummary,
+ OAuthGrantScope,
+ OAuthInstallSubmit,
+ OAuthReferenceSecretInput,
+} from './oauthInstall.types'
+
+// Public callback base URL for the exact redirect URI (D-B4). It is a control-api
+// server env (CONTROL_API_OAUTH_CALLBACK_BASE_URL) and is NOT reachable from the
+// browser, so control-ui reads a mirror. When it is unset the wizard refuses to
+// invent a URI from window.location (a control-ui origin behind the funnel would
+// guide the operator to register a broken redirect at the provider); it shows a
+// "not configured" state instead, and control-api independently rejects the
+// install with the same reason. Read lazily (not a module-load const) so the
+// value reflects the deployment env at call time — Next still inlines the
+// NEXT_PUBLIC_* reference at build for the browser bundle.
+export function oauthCallbackBaseUrl(): string {
+ return process.env.NEXT_PUBLIC_CONTROL_API_OAUTH_CALLBACK_BASE_URL?.trim() ?? ''
+}
+
+const GRANT_SCOPES: ReadonlySet<string> = new Set<OAuthGrantScope>(['user', 'context'])
+
+/**
+ * Preview mirror of control-api's `deriveOAuthClientId` (routes/admin/registry.ts).
+ * The operator NEVER types `oauth.id`; control-api derives and validates it at
+ * install (D-B5). This mirror only renders the read-only preview so the operator
+ * can see the callback coordinate before submitting — control-api stays the
+ * single authority, so a drift here is a cosmetic preview bug, not a wrong write.
+ */
+export function deriveOAuthClientIdPreview(serverName: string): string {
+ return serverName
+ .toLowerCase()
+ .replace(/[^a-z0-9-]/g, '-')
+ .replace(/-+/g, '-')
+ .replace(/^-+/, '')
+ .slice(0, 63)
+ .replace(/-+$/, '')
+}
+
+/**
+ * The exact redirect URI the operator registers at the provider (D-B4):
+ * `{base}/api/v1/oauth-callback/{oauth.id}`. Returns null when the base URL is
+ * not configured or the id is empty — the caller shows a "not configured" notice
+ * rather than a broken URI.
+ */
+export function buildOAuthRedirectUri(base: string | undefined, oauthId: string): string | null {
+ const trimmedBase = (base ?? '').trim().replace(/\/+$/, '')
+ if (!trimmedBase || !oauthId) return null
+ return `${trimmedBase}/api/v1/oauth-callback/${encodeURIComponent(oauthId)}`
+}
+
+/**
+ * Extracts and shallow-validates the frozen `mcp_server_meta.oauth` block. Returns
+ * null when the entry declares no OAuth (the caller then uses the ordinary
+ * connector install). Only fields the wizard understands survive; `genericConfig`
+ * is dropped (Slice 1, S-4).
+ */
+export function getCatalogOAuthBlock(
+ entry: RegistryEntry | null | undefined
+): CatalogOAuthBlock | null {
+ const raw = entry?.mcp_server_meta?.oauth
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
+ const block = raw as Record<string, unknown>
+ if (typeof block.provider !== 'string' || block.provider.trim().length === 0) return null
+
+ const result: CatalogOAuthBlock = { provider: block.provider }
+ if (typeof block.grantScope === 'string' && GRANT_SCOPES.has(block.grantScope)) {
+ result.grantScope = block.grantScope as OAuthGrantScope
+ }
+ if (Array.isArray(block.scopes)) {
+ result.scopes = block.scopes.filter((s): s is string => typeof s === 'string')
+ }
+ return result
+}
+
+/**
+ * Parses the free-text scopes field into a clean, de-duplicated list. Operators
+ * paste scopes separated by whitespace, newlines, or commas; all are normalised.
+ */
+export function parseScopesInput(text: string): string[] {
+ const seen = new Set<string>()
+ const out: string[] = []
+ for (const token of text.split(/[\s,]+/)) {
+ const scope = token.trim()
+ if (scope && !seen.has(scope)) {
+ seen.add(scope)
+ out.push(scope)
+ }
+ }
+ return out
+}
+
+/** Renders a scope list back into the editable textarea (one per line). */
+export function formatScopesForInput(scopes: readonly string[]): string {
+ return scopes.join('\n')
+}
+
+/**
+ * GAP-6 UI gate: a baked OAuth server must never be submitted with an empty scope
+ * list. The wizard blocks submit until the operator has at least one scope,
+ * mirroring the server's reject (control-api computes an effective scope list and
+ * rejects `[]`).
+ */
+export function scopesAreSatisfied(scopes: readonly string[]): boolean {
+ return scopes.length > 0
+}
+
+// The OAuth fields that are CEL-immutable on the mcpserver CRD (D-B7): a change
+// means delete + recreate, so the edit form shows them read-only. `scopes` is
+// deliberately absent — it is editable (D-B6).
+export type OAuthImmutableFields = {
+ id: string
+ provider: string
+ grantScope: OAuthGrantScope | ''
+}
+
+/**
+ * Reads the immutable OAuth fields off an installed McpServer's `spec.oauth` for a
+ * read-only display in the edit form (D-B7). Returns null when the server carries
+ * no OAuth block.
+ */
+export function extractOAuthImmutables(
+ spec: Record<string, unknown> | null | undefined
+): OAuthImmutableFields | null {
+ const raw = spec?.oauth
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
+ const oauth = raw as Record<string, unknown>
+ const provider = typeof oauth.provider === 'string' ? oauth.provider : ''
+ if (!provider) return null
+ const grantScope =
+ oauth.grantScope === 'user' || oauth.grantScope === 'context' ? oauth.grantScope : ''
+ return {
+ id: typeof oauth.id === 'string' ? oauth.id : '',
+ provider,
+ grantScope,
+ }
+}
+
+/**
+ * The name of the Secret that holds this OAuth connector's client credential
+ * (D-B7 edit view). It is `spec.oauth.clientSecretRef.name` (falling back to
+ * `clientIdRef.name` when the pair shares one Secret) — for a managed install
+ * this is `${serverName}-oauth-client`, for a referenced install it is whatever
+ * the operator named. Returns null when no ref is present.
+ */
+export function oauthClientSecretRefName(
+ spec: Record<string, unknown> | null | undefined
+): string | null {
+ const raw = spec?.oauth
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
+ const oauth = raw as Record<string, unknown>
+ for (const key of ['clientSecretRef', 'clientIdRef']) {
+ const ref = oauth[key]
+ if (
+ ref &&
+ typeof ref === 'object' &&
+ typeof (ref as Record<string, unknown>).name === 'string'
+ ) {
+ return (ref as { name: string }).name
+ }
+ }
+ return null
+}
+
+/**
+ * Reference-mode pre-check (Fam. B(1)): the Secret must exist and carry both named
+ * keys BEFORE submit, so the wizard never writes a CR whose refs dangle. Returns a
+ * human message when something is missing, else null. `GET /admin/mcp-secrets`
+ * returns names + keys only (never values), so this is safe to run client-side.
+ */
+export function referenceSecretIssue(
+ ref: Pick<OAuthReferenceSecretInput, 'secretName' | 'clientIdKey' | 'clientSecretKey'>,
+ secrets: readonly McpSecretSummary[]
+): string | null {
+ const secretName = ref.secretName.trim()
+ const clientIdKey = ref.clientIdKey.trim()
+ const clientSecretKey = ref.clientSecretKey.trim()
+ if (!secretName) return 'Choose an existing Secret.'
+ if (!clientIdKey || !clientSecretKey) return 'Name the Client ID key and the Client Secret key.'
+
+ const match = secrets.find(secret => secret.name === secretName)
+ if (!match) return `Secret "${secretName}" was not found in the MCP servers namespace.`
+
+ const keySet = new Set(match.keys)
+ const missing = [clientIdKey, clientSecretKey].filter(key => !keySet.has(key))
+ if (missing.length > 0) {
+ return `Secret "${secretName}" is missing key(s): ${missing.join(', ')}.`
+ }
+ return null
+}
diff --git a/control-ui/lib/oauthInstall.types.ts b/control-ui/lib/oauthInstall.types.ts
new file mode 100644
index 000000000..04f87dad4
--- /dev/null
+++ b/control-ui/lib/oauthInstall.types.ts
@@ -0,0 +1,63 @@
+// Wire + form types for the OAuth install-from-UI wizard (Slice 1, S1-U4).
+// The submit shape mirrors the frozen control-api contract
+// (routes/admin/registry.ts InstallOAuthInputSchema): `oauth.id` is NEVER sent —
+// control-api derives and validates it (D-B5).
+
+export type OAuthGrantScope = 'user' | 'context'
+
+// The frozen catalog block carried under `mcp_server_meta.oauth` (S1-U1 contract).
+// `genericConfig` is Slice-3-only and deliberately not modelled here: Slice 1
+// serves only the 8 baked providers and never reads generic config (S-4).
+export type CatalogOAuthBlock = {
+ provider: string
+ grantScope?: OAuthGrantScope
+ scopes?: string[]
+}
+
+export type OAuthSecretMode = 'managed' | 'reference'
+
+// Managed mode: the operator types client_id/client_secret and control-api
+// creates the Secret with canonical keys.
+export type OAuthManagedSecretInput = {
+ mode: 'managed'
+ clientId: string
+ clientSecret: string
+}
+
+// Reference mode: the operator points at an existing Secret and names the keys
+// that hold the id and the secret.
+export type OAuthReferenceSecretInput = {
+ mode: 'reference'
+ secretName: string
+ clientIdKey: string
+ clientSecretKey: string
+}
+
+export type OAuthSecretInput = OAuthManagedSecretInput | OAuthReferenceSecretInput
+
+// The `oauth` sub-object attached to POST /admin/registry/install.
+export type OAuthInstallSubmit = {
+ scopes?: string[]
+ grantScope?: OAuthGrantScope
+ secret: OAuthSecretInput
+}
+
+// GET /admin/oauth/providers/:id/credential-manifest response.
+export type OAuthCredentialField = {
+ name: string
+ label: string
+ secret: boolean
+ required: boolean
+ help?: string
+}
+
+export type OAuthCredentialManifest = {
+ provider: string
+ fields: OAuthCredentialField[]
+}
+
+// GET /admin/mcp-secrets item — names + keys only, never values (E-16.1).
+export type McpSecretSummary = {
+ name: string
+ keys: string[]
+}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 55057f0bb..5238431b6 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.604",
+ "version": "0.1.605",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.604",
+ "version": "0.1.605",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index e5c50bedf..e49332bf3 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.604",
+ "version": "0.1.605",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",