Skip to content

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

TypeScript

feat(control-ui): attach credentials to keyless connectors

Mfd9b29393644
diff --git a/control-ui/app/constants/connectorCredentials.ts b/control-ui/app/constants/connectorCredentials.ts
new file mode 100644
index 000000000..f399c29f8
--- /dev/null
+++ b/control-ui/app/constants/connectorCredentials.ts
@@ -0,0 +1,58 @@
+// This timeout MUST stay strictly greater than the HCC's own readiness budget
+// (host-context-controller reconciler.ts: pollReadiness, 24 attempts × 5s =
+// 120s), plus room for the SecretInformer round-trip and one poll interval.
+//
+// The two budgets are not interchangeable, and the slack between them is
+// load-bearing in BOTH directions:
+//
+// - When a rollout fails, the HCC writes the diagnosis — DeploymentReady=False
+// reason=RolloutIncomplete with the rollout numbers — at the END of its
+// budget. If this timeout expired first, the operator would see a bare
+// "timed out" instead of the diagnosis that was about to arrive.
+// - When a rollout is merely SLOW (a loaded cluster, a long image pull), the
+// HCC exhausts its 120s budget and writes RolloutIncomplete before the pod
+// goes Ready — and then its post-terminal re-poll (reconciler.ts,
+// performReconcile) arms one more window and CORRECTS the condition to
+// True/ReplicasAvailable once the Deployment converges. The ~60s this
+// timeout outlives the HCC budget is precisely the observation slack in
+// which that correction lands. Latching failure the moment RolloutIncomplete
+// appears would throw that slack away and report a deterministic false
+// negative for any rotation converging between 120s and 180s (issue #223).
+//
+// Exported so the tests drive fake timers off THESE values instead of keeping
+// their own copy: a duplicated budget silently stops testing the real one the
+// first time either side changes.
+export const POLL_INTERVAL_MS = 3_000
+export const POLL_TIMEOUT_MS = 180_000
+
+// The `reason` the HCC stamps on DeploymentReady=False when ITS readiness poll
+// has exhausted its budget. Terminal for that poll window — but NOT
+// irreversible: the HCC's post-terminal re-poll keeps observing and rewrites
+// the condition to True/ReplicasAvailable if the Deployment converges later.
+// For this UI it therefore means "keep the diagnostic, keep polling until OUR
+// budget expires", never "stop and declare failure". Every other False
+// (notably `WaitingForReplicas`) is a transitory rollout state with no
+// diagnostic value. Must match host-context-controller/src/reconciler.ts.
+export const ROLLOUT_INCOMPLETE_REASON = 'RolloutIncomplete'
+
+// Slack subtracted from the client-side cutoff to absorb clock skew between the
+// browser and the Kubernetes API server (which stamps lastTransitionTime). Must
+// stay well under a real rollout's duration so a stale condition is still
+// excluded. 5s comfortably covers ordinary NTP drift.
+export const CLOCK_SKEW_TOLERANCE_MS = 5_000
+
+// Matches the existing MCP Secret endpoint naming contract.
+export const MCP_SECRET_NAME_PATTERN = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/
+
+// Match the names already forbidden by the existing plain-env API validator.
+export const CREDENTIAL_FORBIDDEN_ENV = new Set([
+ 'LD_PRELOAD',
+ 'LD_LIBRARY_PATH',
+ 'PATH',
+ 'NODE_OPTIONS',
+ 'PYTHONPATH',
+ 'JAVA_TOOL_OPTIONS',
+ 'KUBECONFIG',
+ 'KUBERNETES_SERVICE_HOST',
+ 'KUBERNETES_SERVICE_PORT',
+])
diff --git a/control-ui/app/mcp-servers/[name]/edit/page.tsx b/control-ui/app/mcp-servers/[name]/edit/page.tsx
index ff65e59db..f88a79638 100644
--- a/control-ui/app/mcp-servers/[name]/edit/page.tsx
+++ b/control-ui/app/mcp-servers/[name]/edit/page.tsx
@@ -2,6 +2,7 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
+import { AttachConnectorCredentials } from '@components/AttachConnectorCredentials'
import { AuthGate } from '@components/AuthGate'
import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'
import { CreateFlowPanel } from '@components/CreateFlowPanel'
@@ -22,6 +23,7 @@ import {
isRecipeOwned,
resolveCredentialSurface,
} from '@components/UpdateConnectorCredentials/resolveCredentialSurface'
+import { Button, FormSection } from '@components/ui'
import {
CONNECTOR_EDIT_DEFAULT_TAB,
CONNECTOR_EDIT_TABS,
@@ -44,6 +46,8 @@ import {
mergeAccessSummaries,
sortAccessPrincipals,
} from '@lib/connectorAccess'
+import { credentialAttachUnavailable, sameCredentialSpec } from '@lib/connectorCredentials'
+import { buildMcpEgressStatus, deriveEgressEditorInputs } from '@lib/egressModel'
import type { EgressEditorStatus } from '@lib/egressModel'
import { extractOAuthImmutables, oauthClientSecretRefName } from '@lib/oauthInstall'
@@ -78,6 +82,10 @@ export default function EditMcpServerPage() {
const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState('')
const [saving, setSaving] = useState(false)
+ const [reloadTick, setReloadTick] = useState(0)
+ const [attachActive, setAttachActive] = useState(false)
+ const [attachBusy, setAttachBusy] = useState(false)
+ const [egressDirty, setEgressDirty] = useState(false)
const [saveError, setSaveError] = useState('')
const [egressBindings, setEgressBindings] = useState<EgressBinding[] | undefined>(undefined)
const [egressStatus, setEgressStatus] = useState<EgressEditorStatus | null>(null)
@@ -90,10 +98,12 @@ export default function EditMcpServerPage() {
const [loadingContextAccess, setLoadingContextAccess] = useState(false)
function backToList() {
+ if (attachBusy) return
router.push(CONTROL_ROUTES.connectors.root)
}
function selectTab(next: ConnectorEditTab) {
+ if (attachBusy) return
if (next === CONNECTOR_EDIT_DEFAULT_TAB) {
router.replace(CONTROL_ROUTES.connectors.edit(name))
} else {
@@ -101,12 +111,21 @@ export default function EditMcpServerPage() {
}
}
+ const baselineEgress = useMemo(() => {
+ const inputs = deriveEgressEditorInputs(
+ server?.spec?.egressBindings as EgressBinding[] | undefined,
+ { allowCidr: true }
+ )
+ return buildMcpEgressStatus(inputs.mode, inputs.domainInput, inputs.portInput)
+ }, [server?.spec?.egressBindings])
+
const handleEgressChange = useCallback(
(nextBindings: EgressBinding[] | undefined, nextStatus: EgressEditorStatus) => {
setEgressBindings(nextBindings)
setEgressStatus(nextStatus)
+ setEgressDirty(!sameCredentialSpec(nextStatus, baselineEgress))
},
- []
+ [baselineEgress]
)
useEffect(() => {
@@ -118,9 +137,11 @@ export default function EditMcpServerPage() {
const result = await getMcpServer(name)
if (cancelled) return
setServer(result)
+ setEgressDirty(false)
setEgressBindings((result.spec?.egressBindings as EgressBinding[] | undefined) ?? undefined)
} catch (error) {
if (!cancelled) {
+ setServer(null)
setLoadError(error instanceof Error ? error.message : 'Failed to load connector')
}
} finally {
@@ -131,7 +152,7 @@ export default function EditMcpServerPage() {
return () => {
cancelled = true
}
- }, [name])
+ }, [name, reloadTick])
useEffect(() => {
let cancelled = false
@@ -241,7 +262,7 @@ export default function EditMcpServerPage() {
async function handleSave(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
- if (!server?.spec || saving || egressStatus?.errors.length) return
+ if (!server?.spec || saving || attachBusy || egressStatus?.errors.length) return
setSaving(true)
setSaveError('')
try {
@@ -275,6 +296,17 @@ export default function EditMcpServerPage() {
[server?.metadata]
)
+ const attachUnavailable = server ? credentialAttachUnavailable(server) : undefined
+ const onSpecSaved = useCallback((updated: McpServerResource) => {
+ setAttachActive(true)
+ setServer(updated)
+ }, [])
+ const onAttachFinished = useCallback(() => {
+ setAttachActive(false)
+ setAttachBusy(false)
+ setReloadTick(tick => tick + 1)
+ }, [])
+
return (
<AuthGate>
<DashboardLayout isDetailPage>
@@ -296,6 +328,7 @@ export default function EditMcpServerPage() {
onChange={selectTab}
options={CONNECTOR_EDIT_TABS.map(tab => ({
value: tab,
+ disabled: attachBusy,
label: CONNECTOR_EDIT_TAB_LABELS[tab],
href:
tab === CONNECTOR_EDIT_DEFAULT_TAB
@@ -304,7 +337,11 @@ export default function EditMcpServerPage() {
}))}
/>
- {loadError ? <div className="cu-banner cu-banner--error">{loadError}</div> : null}
+ {loadError ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ {loadError}
+ </div>
+ ) : null}
{loading ? (
activeTab === 'credentials' ? (
@@ -335,7 +372,39 @@ export default function EditMcpServerPage() {
) : server ? (
activeTab === 'credentials' ? (
<div className="cu-connector-edit-form">
- {nonCanonicalSecretName !== undefined ? (
+ {attachActive || !attachUnavailable ? (
+ <>
+ <AttachConnectorCredentials
+ key={name}
+ serverName={name}
+ server={server}
+ registryCredentialSource={registryCredentialSource}
+ blockedReason={
+ egressDirty
+ ? 'Save or discard your egress changes before attaching credentials.'
+ : saving
+ ? 'Wait for the egress save to finish.'
+ : undefined
+ }
+ onBusyChange={setAttachBusy}
+ onSpecSaved={onSpecSaved}
+ onFinished={onAttachFinished}
+ />
+ {egressDirty && !attachBusy ? (
+ <Button
+ onClick={() => {
+ setEgressBindings(
+ server.spec?.egressBindings as EgressBinding[] | undefined
+ )
+ setEgressStatus(null)
+ setEgressDirty(false)
+ }}
+ >
+ Discard egress changes
+ </Button>
+ ) : null}
+ </>
+ ) : nonCanonicalSecretName !== undefined ? (
<div className="cu-banner cu-banner--error" role="alert">
This connector stores a non-canonical Secret name:{' '}
<code>{JSON.stringify(nonCanonicalSecretName)}</code>. Correct the connector
@@ -349,7 +418,7 @@ export default function EditMcpServerPage() {
server.spec as Record<string, unknown>
)}
/>
- ) : (
+ ) : envSecret ? (
<UpdateConnectorCredentials
serverName={name}
envSecret={envSecret}
@@ -361,6 +430,10 @@ export default function EditMcpServerPage() {
// Ownership is a spec fact, independent of observed status.
recipeOwned={isRecipeOwned(server.spec as { managed?: boolean } | undefined)}
/>
+ ) : (
+ <FormSection title="Connector credentials">
+ <p className="cu-muted">{attachUnavailable}</p>
+ </FormSection>
)}
</div>
) : activeTab === 'access' ? (
@@ -462,7 +535,7 @@ export default function EditMcpServerPage() {
<button
type="button"
className="cu-btn cu-btn--ghost"
- disabled={saving}
+ disabled={saving || attachBusy}
onClick={backToList}
>
Cancel
@@ -470,7 +543,7 @@ export default function EditMcpServerPage() {
<button
type="submit"
className="cu-btn cu-btn--primary"
- disabled={saving || Boolean(egressStatus?.errors.length)}
+ disabled={saving || attachBusy || Boolean(egressStatus?.errors.length)}
>
{saving ? 'Saving...' : 'Save egress'}
</button>
diff --git a/control-ui/app/secrets/new/page.tsx b/control-ui/app/secrets/new/page.tsx
index f528fb83b..cd909bf0a 100644
--- a/control-ui/app/secrets/new/page.tsx
+++ b/control-ui/app/secrets/new/page.tsx
@@ -13,6 +13,7 @@ import { IconKey } from '@components/Sidebar/icons'
import { useToast } from '@components/Toast'
import { IconX } from '@components/icons'
import { Button, Field, FormSection, SelectInput, TextInput } from '@components/ui'
+import { MCP_SECRET_NAME_PATTERN } from '@constants/connectorCredentials'
import { CREATE_FLOW_LOADING } from '@constants/createFlowLoading'
import { CONTROL_ROUTES } from '@constants/routes'
import {
@@ -35,7 +36,6 @@ import type { CredentialDraftRow } from '@lib/registryCredentialDraft.types'
const HOST_SECRET_LABEL_KEY = 'clerum.io/host-secret'
const HOST_SECRET_LABEL_VALUE = 'true'
-const MCP_SECRET_NAME_PATTERN = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/
const LLM_SECRET_NAME_FIELD_ID = 'llm-secret-name'
const LLM_SECRET_NAME_ERROR_ID = `${LLM_SECRET_NAME_FIELD_ID}-error`
const LLM_SECRET_NAME_ERROR =
diff --git a/control-ui/components/AttachConnectorCredentials/index.tsx b/control-ui/components/AttachConnectorCredentials/index.tsx
new file mode 100644
index 000000000..9a2ba8ae7
--- /dev/null
+++ b/control-ui/components/AttachConnectorCredentials/index.tsx
@@ -0,0 +1,498 @@
+'use client'
+
+import React, { useEffect, useId, useRef, useState } from 'react'
+import { useConfirmDialog } from '@components/ConfirmDialog'
+import { useToast } from '@components/Toast'
+import { useRolloutWait } from '@components/UpdateConnectorCredentials/useRolloutWait'
+import { Button, Field, FormSection, SelectInput, TextInput } from '@components/ui'
+import { getMcpServers, getRegistryCredentialSchema, listMcpSecrets } from '@lib/api'
+import {
+ CredentialAttachError,
+ attachConnectorCredentials,
+ suggestedCredentialEnvVar,
+ validateCredentialAttach,
+} from '@lib/connectorCredentials'
+import type {
+ AttachCredentialRow,
+ AttachMode,
+ AttachValidation,
+ AttachedCredentials,
+} from '@lib/connectorCredentials.types'
+import type { McpSecretSummary } from '@lib/oauthInstall.types'
+import type { AttachConnectorCredentialsProps } from './types'
+
+export function AttachConnectorCredentials({
+ serverName,
+ server,
+ registryCredentialSource,
+ blockedReason,
+ onBusyChange,
+ onSpecSaved,
+ onFinished,
+}: AttachConnectorCredentialsProps) {
+ const { confirm, confirmDialog } = useConfirmDialog()
+ const { showToast } = useToast()
+ const prefix = useId()
+ const nextRow = useRef(0)
+ function newRow(secretKey = ''): AttachCredentialRow {
+ return {
+ id: `${prefix}-${nextRow.current++}`,
+ secretKey,
+ envVar: suggestedCredentialEnvVar(secretKey),
+ value: '',
+ }
+ }
+ const [mode, setMode] = useState<AttachMode>('create-new')
+ const [secretName, setSecretName] = useState('')
+ const [rows, setRows] = useState<AttachCredentialRow[]>(() => [newRow()])
+ const [secrets, setSecrets] = useState<McpSecretSummary[]>([])
+ const [listState, setListState] = useState<'loading' | 'ready' | 'error'>('ready')
+ const [listTick, setListTick] = useState(0)
+ const [labels, setLabels] = useState<Record<string, string>>(() => Object.create(null))
+ const [validation, setValidation] = useState<AttachValidation | undefined>()
+ const [submitting, setSubmitting] = useState(false)
+ const [saved, setSaved] = useState<AttachedCredentials | null>(null)
+ const [refreshRequired, setRefreshRequired] = useState(false)
+ const [collision, setCollision] = useState(false)
+ const submitLock = useRef(false)
+ const touched = useRef(false)
+ const mounted = useRef(true)
+ const completed = useRef(false)
+ const callbacks = useRef({ onBusyChange, onSpecSaved, onFinished })
+ callbacks.current = { onBusyChange, onSpecSaved, onFinished }
+ const { phase, phaseMessage, setPhase, setPhaseMessage } = useRolloutWait({
+ serverName,
+ cutoff: saved?.cutoff ?? null,
+ expectedUid: saved?.server.metadata?.uid,
+ expectedGeneration: saved?.server.metadata?.generation,
+ })
+ const selectedSecret = secrets.find(item => item.name === secretName)
+ const busy = submitting || phase === 'rotating'
+ const locked = busy || Boolean(saved) || refreshRequired
+ const errorId = `${prefix}-error`
+
+ useEffect(() => {
+ mounted.current = true
+ return () => {
+ mounted.current = false
+ }
+ }, [])
+
+ useEffect(() => {
+ callbacks.current.onBusyChange?.(busy || Boolean(saved) || refreshRequired)
+ return () => {
+ callbacks.current.onBusyChange?.(false)
+ }
+ }, [busy, saved, refreshRequired])
+
+ useEffect(() => {
+ if (mode !== 'use-existing') return
+ let cancelled = false
+ setListState('loading')
+ void listMcpSecrets()
+ .then(({ items }) => {
+ if (cancelled) return
+ setSecrets(items)
+ setListState('ready')
+ })
+ .catch(() => {
+ if (!cancelled) setListState('error')
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [mode, listTick])
+
+ useEffect(() => {
+ if (!registryCredentialSource) return
+ let cancelled = false
+ void getRegistryCredentialSchema(
+ registryCredentialSource.name,
+ registryCredentialSource.version
+ )
+ .then(schema => {
+ if (cancelled) return
+ const names = Object.create(null) as Record<string, string>
+ for (const key of schema.keys) names[key.name] = key.label || key.name
+ setLabels(names)
+ if (!touched.current && schema.keys.length)
+ setRows(schema.keys.map(key => newRow(key.name)))
+ })
+ .catch(() => {
+ /* Optional labels never prevent manual entry. */
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [registryCredentialSource?.name, registryCredentialSource?.version])
+
+ useEffect(() => {
+ if (phase !== 'success' || completed.current) return
+ completed.current = true
+ showToast(`Credentials attached. ${serverName} is ready.`, { tone: 'success' })
+ callbacks.current.onFinished()
+ }, [phase, serverName, showToast])
+
+ function changeMode(next: AttachMode) {
+ touched.current = true
+ setMode(next)
+ setSecretName('')
+ setRows(next === 'create-new' ? [newRow()] : [])
+ setValidation(undefined)
+ setCollision(false)
+ setPhase('idle')
+ setPhaseMessage('')
+ }
+
+ function updateRow(id: string, field: 'secretKey' | 'envVar' | 'value', value: string) {
+ touched.current = true
+ setRows(previous => previous.map(row => (row.id === id ? { ...row, [field]: value } : row)))
+ setValidation(undefined)
+ }
+
+ function clearValues() {
+ if (mounted.current) setRows(previous => previous.map(row => ({ ...row, value: '' })))
+ }
+
+ async function submit(event: React.FormEvent<HTMLFormElement>) {
+ event.preventDefault()
+ if (
+ submitLock.current ||
+ locked ||
+ blockedReason ||
+ (mode === 'use-existing' && listState !== 'ready')
+ )
+ return
+ const invalid = validateCredentialAttach(mode, secretName, rows, server, selectedSecret)
+ setValidation(invalid)
+ if (invalid) {
+ document.getElementById(`${prefix}-${invalid.field ?? 'add'}`)?.focus()
+ return
+ }
+ submitLock.current = true
+ setSubmitting(true)
+ setCollision(false)
+ setPhase('idle')
+ setPhaseMessage('')
+ try {
+ let warning = ''
+ if (mode === 'use-existing' && rows.some(row => row.value !== '')) {
+ warning =
+ ' Entered values update the shared Secret and may restart any connector that references it.'
+ try {
+ const { items } = await getMcpServers()
+ const affected = (items ?? [])
+ .filter(item => (item.spec?.envSecret as { name?: string })?.name === secretName)
+ .map(item => item.metadata?.name)
+ .filter(Boolean)
+ .sort()
+ if (affected.length) warning += ` Current references: ${affected.join(', ')}.`
+ } catch {
+ /* Keep the generic warning if the preview is unavailable. */
+ }
+ }
+ if (!mounted.current) return
+ const confirmed = await confirm({
+ title: 'Attach credentials',
+ confirmLabel: 'Attach and restart',
+ message:
+ mode === 'create-new'
+ ? `Create Secret "${secretName.trim()}" and restart ${serverName} with these credentials?`
+ : `Connect ${serverName} to Secret "${secretName}" and restart it?${warning}`,
+ })
+ if (!confirmed || !mounted.current) return
+ setPhase('saving')
+ const result = await attachConnectorCredentials({
+ serverName,
+ expectedUid: server.metadata?.uid,
+ mode,
+ secretName,
+ rows,
+ selectedSecret,
+ onSecretWritten: clearValues,
+ })
+ if (!mounted.current) return
+ clearValues()
+ setSaved(result)
+ callbacks.current.onSpecSaved(result.server)
+ const metadata = result.server.metadata
+ if (!metadata?.uid || !Number.isInteger(metadata.generation)) {
+ setPhase('timeout')
+ setPhaseMessage(
+ 'Credentials were attached, but rollout identity could not be verified. Refresh to check status.'
+ )
+ } else {
+ setPhase('rotating')
+ }
+ } catch (error) {
+ if (!mounted.current) return
+ const known = error instanceof CredentialAttachError
+ setPhase('failed')
+ setPhaseMessage(
+ known
+ ? error.message
+ : 'The connector settings could not be checked. Refresh before trying again.'
+ )
+ setRefreshRequired(!known || error.refreshRequired)
+ setCollision(known && error.collision)
+ if (!known || error.refreshRequired) clearValues()
+ } finally {
+ submitLock.current = false
+ if (mounted.current) setSubmitting(false)
+ }
+ }
+
+ function fieldFeedback(field: string) {
+ const invalid = validation?.field === field
+ return {
+ invalid,
+ 'aria-invalid': invalid || undefined,
+ 'aria-describedby': invalid ? errorId : undefined,
+ }
+ }
+
+ return (
+ <FormSection
+ title="Attach credentials"
+ description="Choose a Secret and map its keys to the connector's environment variables. Stored values are never shown."
+ >
+ {confirmDialog}
+ <form
+ className="cu-connector-credentials-form cu-form-stack--wide"
+ onSubmit={submit}
+ noValidate
+ >
+ {server.spec?.remote ? (
+ <p className="cu-muted">
+ Remote connectors use credentials only through existing authentication header
+ placeholders. Map keys to those variable names; attaching does not add headers.
+ </p>
+ ) : null}
+ {blockedReason ? (
+ <p className="cu-banner cu-banner--warn" role="status">
+ {blockedReason}
+ </p>
+ ) : null}
+ <fieldset className="cu-form-section__group" disabled={locked}>
+ <legend className="cu-form-section__subheading">Credential source</legend>
+ <div className="cu-agent-radio-group">
+ <label className="cu-agent-radio cu-agent-radio--card">
+ <input
+ type="radio"
+ name={`${prefix}-mode`}
+ checked={mode === 'create-new'}
+ onChange={() => changeMode('create-new')}
+ />
+ <span className="cu-agent-radio__title">Create a new Secret</span>
+ </label>
+ <label className="cu-agent-radio cu-agent-radio--card">
+ <input
+ type="radio"
+ name={`${prefix}-mode`}
+ checked={mode === 'use-existing'}
+ onChange={() => changeMode('use-existing')}
+ />
+ <span className="cu-agent-radio__title">Use an existing Secret</span>
+ </label>
+ </div>
+ <Field
+ label={mode === 'create-new' ? 'Secret name' : 'Existing Secret'}
+ htmlFor={`${prefix}-secret`}
+ required
+ >
+ {mode === 'create-new' ? (
+ <TextInput
+ id={`${prefix}-secret`}
+ required
+ monospace
+ maxLength={253}
+ value={secretName}
+ onChange={event => {
+ touched.current = true
+ setSecretName(event.target.value)
+ setValidation(undefined)
+ }}
+ {...fieldFeedback('secret')}
+ />
+ ) : (
+ <SelectInput
+ id={`${prefix}-secret`}
+ required
+ value={secretName}
+ disabled={listState !== 'ready'}
+ onChange={event => {
+ touched.current = true
+ setSecretName(event.target.value)
+ setRows(
+ (secrets.find(item => item.name === event.target.value)?.keys ?? []).map(key =>
+ newRow(key)
+ )
+ )
+ setValidation(undefined)
+ }}
+ {...fieldFeedback('secret')}
+ >
+ <option value="">Choose a Secret</option>
+ {secrets.map(item => (
+ <option key={item.name} value={item.name}>
+ {item.name}
+ </option>
+ ))}
+ </SelectInput>
+ )}
+ </Field>
+ {mode === 'use-existing' && listState === 'loading' ? (
+ <p role="status">Loading Secrets…</p>
+ ) : null}
+ {mode === 'use-existing' && listState === 'error' ? (
+ <div role="alert">
+ Could not load Secrets.{' '}
+ <Button onClick={() => setListTick(tick => tick + 1)}>Retry loading Secrets</Button>
+ </div>
+ ) : null}
+ {mode === 'use-existing' ? (
+ <p className="cu-muted">
+ Leave a value blank to keep its stored value. New keys require a value. Entered values
+ may restart other connectors sharing this Secret.
+ </p>
+ ) : null}
+ {rows.map((row, index) => (
+ <fieldset className="cu-form-section__group" key={row.id}>
+ <legend className="cu-form-section__subheading">Key mapping {index + 1}</legend>
+ <div className="cu-form-grid cu-form-grid--2">
+ <Field
+ label={`Secret key ${index + 1}`}
+ htmlFor={`${prefix}-${row.id}-key`}
+ required
+ >
+ <TextInput
+ id={`${prefix}-${row.id}-key`}
+ required
+ monospace
+ value={row.secretKey}
+ onChange={event => updateRow(row.id, 'secretKey', event.target.value)}
+ {...fieldFeedback(`${row.id}-key`)}
+ />
+ </Field>
+ <Field
+ label={`Environment variable ${index + 1}`}
+ htmlFor={`${prefix}-${row.id}-env`}
+ required
+ >
+ <TextInput
+ id={`${prefix}-${row.id}-env`}
+ required
+ monospace
+ value={row.envVar}
+ onChange={event => updateRow(row.id, 'envVar', event.target.value)}
+ {...fieldFeedback(`${row.id}-env`)}
+ />
+ </Field>
+ </div>
+ <Field
+ label={
+ Object.hasOwn(labels, row.secretKey)
+ ? `Value for ${labels[row.secretKey]}`
+ : `Credential value ${index + 1}`
+ }
+ htmlFor={`${prefix}-${row.id}-value`}
+ required={
+ mode === 'create-new' || !selectedSecret?.keys.includes(row.secretKey.trim())
+ }
+ >
+ <TextInput
+ id={`${prefix}-${row.id}-value`}
+ type="password"
+ required={
+ mode === 'create-new' || !selectedSecret?.keys.includes(row.secretKey.trim())
+ }
+ autoComplete="new-password"
+ value={row.value}
+ placeholder={
+ mode === 'create-new' ? 'Required' : 'Leave blank to keep current value'
+ }
+ onChange={event => updateRow(row.id, 'value', event.target.value)}
+ {...fieldFeedback(`${row.id}-value`)}
+ />
+ </Field>
+ <Button
+ variant="ghost-danger"
+ onClick={() => {
+ touched.current = true
+ setRows(previous => previous.filter(item => item.id !== row.id))
+ setValidation(undefined)
+ }}
+ aria-label={`Remove mapping ${index + 1}`}
+ >
+ Remove mapping
+ </Button>
+ </fieldset>
+ ))}
+ <Button
+ id={`${prefix}-add`}
+ onClick={() => {
+ touched.current = true
+ setRows(previous => [...previous, newRow()])
+ setValidation(undefined)
+ }}
+ >
+ Add key mapping
+ </Button>
+ </fieldset>
+ {validation ? (
+ <div id={errorId} role="alert" className="cu-banner cu-banner--error">
+ {validation.message}
+ </div>
+ ) : null}
+ {phase === 'rotating' ? (
+ <div role="status" className="cu-banner cu-banner--info">
+ Credentials attached. Waiting for {serverName} to become ready… {phaseMessage}
+ </div>
+ ) : null}
+ {phase === 'failed' ? (
+ <div role="alert" className="cu-banner cu-banner--error">
+ {saved ? 'Credentials were attached, but readiness could not be verified: ' : ''}
+ {phaseMessage}
+ </div>
+ ) : null}
+ {phase === 'timeout' ? (
+ <div role="alert" className="cu-banner cu-banner--warning">
+ Credentials were attached, but readiness could not be verified within the observation
+ window. Refresh to check status or update credentials. {phaseMessage}
+ </div>
+ ) : null}
+ {saved?.affectedConnectors.filter(name => name !== serverName).length ? (
+ <p className="cu-muted">
+ Other connectors sharing this Secret roll out separately:{' '}
+ {saved.affectedConnectors.filter(name => name !== serverName).join(', ')}.
+ </p>
+ ) : null}
+ <div className="cu-create-actions">
+ {saved || refreshRequired ? (
+ <Button onClick={onFinished}>
+ {phase === 'rotating' ? 'Check credentials later' : 'Refresh credentials'}
+ </Button>
+ ) : (
+ <>
+ {collision ? (
+ <Button onClick={() => changeMode('use-existing')}>Choose existing Secret</Button>
+ ) : null}
+ <Button
+ type="submit"
+ variant="primary"
+ disabled={
+ busy ||
+ Boolean(blockedReason) ||
+ (mode === 'use-existing' && listState !== 'ready')
+ }
+ loading={submitting}
+ >
+ {submitting ? 'Attaching…' : 'Attach and restart'}
+ </Button>
+ </>
+ )}
+ </div>
+ </form>
+ </FormSection>
+ )
+}
diff --git a/control-ui/components/AttachConnectorCredentials/types.ts b/control-ui/components/AttachConnectorCredentials/types.ts
new file mode 100644
index 000000000..a27d9075c
--- /dev/null
+++ b/control-ui/components/AttachConnectorCredentials/types.ts
@@ -0,0 +1,12 @@
+import type { RegistryCredentialSource } from '@components/UpdateConnectorCredentials/types'
+import type { McpServerResource } from '@lib/api'
+
+export type AttachConnectorCredentialsProps = {
+ serverName: string
+ server: McpServerResource
+ registryCredentialSource?: RegistryCredentialSource
+ blockedReason?: string
+ onBusyChange?: (busy: boolean) => void
+ onSpecSaved: (server: McpServerResource) => void
+ onFinished: () => void
+}
diff --git a/control-ui/components/UpdateConnectorCredentials/index.tsx b/control-ui/components/UpdateConnectorCredentials/index.tsx
index ae2977efc..e52909d70 100644
--- a/control-ui/components/UpdateConnectorCredentials/index.tsx
+++ b/control-ui/components/UpdateConnectorCredentials/index.tsx
@@ -1,62 +1,26 @@
'use client'
-import React, { useEffect, useRef, useState } from 'react'
+import React, { useEffect, useState } from 'react'
import { DataTable, TableViewport } from '@clerum/frontend-components'
import { useConfirmDialog } from '@components/ConfirmDialog'
import { useToast } from '@components/Toast'
import { Button, Field, FormSection, TextInput } from '@components/ui'
+import { CLOCK_SKEW_TOLERANCE_MS } from '@constants/connectorCredentials'
import {
createMcpSecret,
- getMcpServer,
getMcpServers,
getRegistryCredentialSchema,
updateMcpSecret,
} from '@lib/api'
-import type { McpServerCondition } from '@lib/api'
-import type { RotationPhase, UpdateConnectorCredentialsProps } from './types'
-
-// This timeout MUST stay strictly greater than the HCC's own readiness budget
-// (host-context-controller reconciler.ts: pollReadiness, 24 attempts × 5s =
-// 120s), plus room for the SecretInformer round-trip and one poll interval.
-//
-// The two budgets are not interchangeable, and the slack between them is
-// load-bearing in BOTH directions:
-//
-// - When a rollout fails, the HCC writes the diagnosis — DeploymentReady=False
-// reason=RolloutIncomplete with the rollout numbers — at the END of its
-// budget. If this timeout expired first, the operator would see a bare
-// "timed out" instead of the diagnosis that was about to arrive.
-// - When a rollout is merely SLOW (a loaded cluster, a long image pull), the
-// HCC exhausts its 120s budget and writes RolloutIncomplete before the pod
-// goes Ready — and then its post-terminal re-poll (reconciler.ts,
-// performReconcile) arms one more window and CORRECTS the condition to
-// True/ReplicasAvailable once the Deployment converges. The ~60s this
-// timeout outlives the HCC budget is precisely the observation slack in
-// which that correction lands. Latching failure the moment RolloutIncomplete
-// appears would throw that slack away and report a deterministic false
-// negative for any rotation converging between 120s and 180s (issue #223).
-//
-// Exported so the tests drive fake timers off THESE values instead of keeping
-// their own copy: a duplicated budget silently stops testing the real one the
-// first time either side changes.
-export const POLL_INTERVAL_MS = 3_000
-export const POLL_TIMEOUT_MS = 180_000
-
-// The `reason` the HCC stamps on DeploymentReady=False when ITS readiness poll
-// has exhausted its budget. Terminal for that poll window — but NOT
-// irreversible: the HCC's post-terminal re-poll keeps observing and rewrites
-// the condition to True/ReplicasAvailable if the Deployment converges later.
-// For this UI it therefore means "keep the diagnostic, keep polling until OUR
-// budget expires", never "stop and declare failure". Every other False
-// (notably `WaitingForReplicas`) is a transitory rollout state with no
-// diagnostic value. Must match host-context-controller/src/reconciler.ts.
-export const ROLLOUT_INCOMPLETE_REASON = 'RolloutIncomplete'
-
-// Slack subtracted from the client-side cutoff to absorb clock skew between the
-// browser and the Kubernetes API server (which stamps lastTransitionTime). Must
-// stay well under a real rollout's duration so a stale condition is still
-// excluded. 5s comfortably covers ordinary NTP drift.
-export const CLOCK_SKEW_TOLERANCE_MS = 5_000
+import type { UpdateConnectorCredentialsProps } from './types'
+import { useRolloutWait } from './useRolloutWait'
+
+export {
+ POLL_INTERVAL_MS,
+ POLL_TIMEOUT_MS,
+ ROLLOUT_INCOMPLETE_REASON,
+ CLOCK_SKEW_TOLERANCE_MS,
+} from '@constants/connectorCredentials'
// The aggregate validation alert's id. Rejected inputs point at it through
// `aria-describedby`, so a screen reader announces WHY a field is invalid from
@@ -107,24 +71,6 @@ function buildConfirmMessage(secretName: string, affected: string[] | null): str
return `This rotates the credential value(s) you entered in Secret "${secretName}" and restarts: ${affected.join(', ')}.`
}
-/**
- * Returns the McpServer's DeploymentReady condition ONLY if it transitioned
- * strictly after `cutoffIso` — the instant captured client-side right before
- * the rotation PUT was sent. A condition timestamped at or before the PUT is
- * the rollout's PREVIOUS state (e.g. the old pod staying Ready while the HCC
- * has not reconciled the new Secret yet); treating a stale True as success
- * would report a rotation that never happened (issue #223 plan, Fase 3 §6).
- */
-function findFreshDeploymentReady(
- conditions: McpServerCondition[] | undefined,
- cutoffIso: string
-): McpServerCondition | undefined {
- const condition = conditions?.find(c => c.type === 'DeploymentReady')
- if (!condition) return undefined
- const isFresh = new Date(condition.lastTransitionTime).getTime() > new Date(cutoffIso).getTime()
- return isFresh ? condition : undefined
-}
-
export function UpdateConnectorCredentials({
serverName,
envSecret,
@@ -149,9 +95,11 @@ export function UpdateConnectorCredentials({
// list so the operator sees the same answer before committing.
const [previewAffected, setPreviewAffected] = useState<string[] | null>(null)
- const [phase, setPhase] = useState<RotationPhase>('idle')
- const [phaseMessage, setPhaseMessage] = useState('')
const [rotationCutoff, setRotationCutoff] = useState<string | null>(null)
+ const { phase, phaseMessage, setPhase, setPhaseMessage } = useRolloutWait({
+ serverName,
+ cutoff: rotationCutoff,
+ })
const [rotationAffected, setRotationAffected] = useState<string[]>([])
// Labels use the same Kubernetes-valid key namespace as drafts. Keep this
// map prototype-safe as well, because Marketplace schemas may contain keys
@@ -165,15 +113,6 @@ export function UpdateConnectorCredentials({
// Which operation is actually in flight / just completed. Captured at submit
// time and used for the in-flight and success banners.
const [submittedMode, setSubmittedMode] = useState<'set' | 'rotate'>('rotate')
- // The HCC's most recent RolloutIncomplete diagnostic, kept across polls (a
- // ref, not state: it only matters at the timeout boundary, so it must not
- // re-render or re-fire the poll effect). Seeing RolloutIncomplete never
- // latches failure — the HCC re-polls post-terminal and can still correct the
- // condition to True for a slow pod — but the diagnostic is preserved so that
- // if OUR budget expires without a True, the operator gets the HCC's rollout
- // numbers instead of a bare "timed out".
- const rolloutIncompleteMessage = useRef<string | null>(null)
-
useEffect(() => {
if (!envSecret) return
let cancelled = false
@@ -227,100 +166,6 @@ export function UpdateConnectorCredentials({
}
}, [registryCredentialSource])
- // Poll THIS connector's own McpServer CRD until DeploymentReady resolves,
- // fails, or the bounded timeout expires. Success is NEVER declared from the
- // PUT's 200 alone (Fase 3 §4 corolario vinculante).
- useEffect(() => {
- if (phase !== 'rotating' || !rotationCutoff) return
- let cancelled = false
- const startedAt = Date.now()
- // Each rotation gets a clean slate: a diagnostic left over from a previous
- // attempt must never be reported as THIS rotation's failure.
- rolloutIncompleteMessage.current = null
-
- async function poll() {
- let latest: Awaited<ReturnType<typeof getMcpServer>>
- try {
- latest = await getMcpServer(serverName)
- } catch (e) {
- if (cancelled) return
- // A transient read failure resolves nothing either way — surface it
- // but keep polling until the bounded cap below fires.
- setPhaseMessage(
- `Could not check rollout status (${e instanceof Error ? e.message : 'request failed'}). Retrying…`
- )
- return
- }
- if (cancelled) return
- const fresh = findFreshDeploymentReady(latest.status?.conditions, rotationCutoff!)
- if (!fresh) return
- if (fresh.status === 'True') {
- setPhase('success')
- return
- }
- // NO `False` DeploymentReady is a failure verdict for this UI — not even
- // `RolloutIncomplete`:
- //
- // - `WaitingForReplicas` is the normal transitory state of EVERY rollout,
- // written synchronously right after the PUT. Treating it as failure
- // would abort almost every successful rotation on the first poll.
- // - `RolloutIncomplete` means the HCC exhausted ITS 120s readiness budget
- // (host-context-controller reconciler.ts, pollReadiness 24×5s) — but the
- // HCC keeps observing past that verdict (post-terminal re-poll) and
- // corrects the condition to True when a slow pod converges. Latching
- // failure here would discard the ~60s of budget this poll still holds
- // and report a deterministic false negative for any rollout converging
- // between 120s and 180s — the exact bug of issue #223.
- //
- // So the ONLY outcomes are: a fresh True (success, above), or this poll's
- // own bounded timeout — which reports `failed` with the preserved HCC
- // diagnostic if RolloutIncomplete was seen, `timeout` otherwise.
- if (fresh.status === 'False' && fresh.reason === ROLLOUT_INCOMPLETE_REASON) {
- rolloutIncompleteMessage.current =
- fresh.message || 'The connector rollout did not complete.'
- // Keep the operator informed instead of silently spinning: the rollout
- // has outlived the controller's own budget but is still being observed.
- setPhaseMessage(
- "The rollout is taking longer than the controller's readiness budget — still verifying…"
- )
- }
- }
-
- const id = setInterval(() => {
- if (Date.now() - startedAt >= POLL_TIMEOUT_MS) {
- clearInterval(id)
- if (!cancelled) {
- if (rolloutIncompleteMessage.current !== null) {
- // The HCC diagnosed the rollout (RolloutIncomplete) and never
- // corrected it to True within our budget: a real failure, reported
- // with the controller's own rollout numbers — never degraded to a
- // bare "timed out".
- setPhase('failed')
- setPhaseMessage(rolloutIncompleteMessage.current)
- } else {
- // No verdict either way inside the budget — an inconclusive
- // timeout, distinct from a diagnosed failure.
- setPhase('timeout')
- // Diagnostic only. The "what to try next" sentence is mode-specific
- // and is appended by the timeout banner from `submittedMode`.
- setPhaseMessage(
- `The rollout did not finish within ${Math.round(POLL_TIMEOUT_MS / 1000)}s. Run ` +
- `"kubectl get mcpserver ${serverName} -o yaml" to see the current DeploymentReady ` +
- 'condition.'
- )
- }
- }
- return
- }
- void poll()
- }, POLL_INTERVAL_MS)
-
- return () => {
- cancelled = true
- clearInterval(id)
- }
- }, [phase, rotationCutoff, serverName])
-
// "The Secret is missing and this screen would have to create it." Two
// sources feed it, and `secretCreated` gates BOTH — not just the `surface`
// prop. That latch flips the moment a create succeeds, and the Secret it
@@ -488,7 +333,6 @@ export function UpdateConnectorCredentials({
setPhaseMessage('')
setRotationCutoff(null)
setRotationAffected([])
- rolloutIncompleteMessage.current = null
}
const busy = phase === 'saving' || phase === 'rotating'
diff --git a/control-ui/components/UpdateConnectorCredentials/types.ts b/control-ui/components/UpdateConnectorCredentials/types.ts
index e5a2f9933..e118cd316 100644
--- a/control-ui/components/UpdateConnectorCredentials/types.ts
+++ b/control-ui/components/UpdateConnectorCredentials/types.ts
@@ -59,9 +59,17 @@ export type UpdateConnectorCredentialsProps = {
* DeploymentReady condition (the connector restarting after a
* rotation, or starting for the first time after a create).
* - success: a fresh DeploymentReady=True was observed after the write.
- * - failed: the write itself failed, OR a fresh DeploymentReady=False was
- * observed after it.
+ * - failed: the write failed, or the UI budget expired after an unresolved
+ * RolloutIncomplete diagnostic (a fresh False alone is not final).
* - timeout: the bounded poll window elapsed without a fresh terminal
* condition. Never reported as success.
*/
export type RotationPhase = 'idle' | 'saving' | 'rotating' | 'success' | 'failed' | 'timeout'
+
+export type RolloutWaitOptions = {
+ serverName: string
+ cutoff: string | null
+ /** Attach mutates spec; rotation callers retain timestamp-only correlation. */
+ expectedUid?: string
+ expectedGeneration?: number
+}
diff --git a/control-ui/components/UpdateConnectorCredentials/useRolloutWait.ts b/control-ui/components/UpdateConnectorCredentials/useRolloutWait.ts
new file mode 100644
index 000000000..9e2320278
--- /dev/null
+++ b/control-ui/components/UpdateConnectorCredentials/useRolloutWait.ts
@@ -0,0 +1,158 @@
+'use client'
+
+import { useEffect, useRef, useState } from 'react'
+import {
+ POLL_INTERVAL_MS,
+ POLL_TIMEOUT_MS,
+ ROLLOUT_INCOMPLETE_REASON,
+} from '@constants/connectorCredentials'
+import { getMcpServer } from '@lib/api'
+import type { McpServerCondition } from '@lib/api'
+import type { RolloutWaitOptions, RotationPhase } from './types'
+
+/**
+ * Returns the McpServer's DeploymentReady condition ONLY if it transitioned
+ * strictly after `cutoffIso` — the instant captured client-side right before
+ * the rotation PUT was sent. A condition timestamped at or before the PUT is
+ * the rollout's PREVIOUS state (e.g. the old pod staying Ready while the HCC
+ * has not reconciled the new Secret yet); treating a stale True as success
+ * would report a rotation that never happened (issue #223 plan, Fase 3 §6).
+ */
+function findFreshDeploymentReady(
+ conditions: McpServerCondition[] | undefined,
+ cutoffIso: string
+): McpServerCondition | undefined {
+ const condition = conditions?.find(c => c.type === 'DeploymentReady')
+ if (!condition) return undefined
+ const isFresh = new Date(condition.lastTransitionTime).getTime() > new Date(cutoffIso).getTime()
+ return isFresh ? condition : undefined
+}
+
+export function useRolloutWait({
+ serverName,
+ cutoff,
+ expectedUid,
+ expectedGeneration,
+}: RolloutWaitOptions) {
+ const [phase, setPhase] = useState<RotationPhase>('idle')
+ const [phaseMessage, setPhaseMessage] = useState('')
+ const rolloutIncompleteMessage = useRef<string | null>(null)
+
+ // Poll THIS connector's own McpServer CRD until DeploymentReady resolves,
+ // fails, or the bounded timeout expires. Success is NEVER declared from the
+ // PUT's 200 alone (Fase 3 §4 corolario vinculante).
+ useEffect(() => {
+ if (phase !== 'rotating' || !cutoff) return
+ let cancelled = false
+ const startedAt = Date.now()
+ // Each rotation gets a clean slate: a diagnostic left over from a previous
+ // attempt must never be reported as THIS rotation's failure.
+ rolloutIncompleteMessage.current = null
+
+ async function poll() {
+ let latest: Awaited<ReturnType<typeof getMcpServer>>
+ try {
+ latest = await getMcpServer(serverName)
+ } catch (e) {
+ if (cancelled) return
+ // A transient read failure resolves nothing either way — surface it
+ // but keep polling until the bounded cap below fires.
+ setPhaseMessage(
+ `Could not check rollout status (${e instanceof Error ? e.message : 'request failed'}). Retrying…`
+ )
+ return
+ }
+ if (cancelled) return
+ if (expectedUid !== undefined) {
+ if (
+ latest.metadata?.uid !== expectedUid ||
+ (expectedGeneration !== undefined &&
+ latest.metadata?.generation !== undefined &&
+ latest.metadata.generation !== expectedGeneration)
+ ) {
+ cancelled = true
+ clearInterval(id)
+ setPhase('failed')
+ setPhaseMessage(
+ 'The connector changed during verification. Refresh to check its current state.'
+ )
+ return
+ }
+ if (latest.metadata?.generation !== expectedGeneration) return
+ }
+ const fresh = findFreshDeploymentReady(latest.status?.conditions, cutoff!)
+ if (expectedGeneration !== undefined && fresh?.observedGeneration !== expectedGeneration)
+ return
+ if (!fresh) return
+ if (fresh.status === 'True') {
+ cancelled = true
+ clearInterval(id)
+ setPhase('success')
+ return
+ }
+ // NO `False` DeploymentReady is a failure verdict for this UI — not even
+ // `RolloutIncomplete`:
+ //
+ // - `WaitingForReplicas` is the normal transitory state of EVERY rollout,
+ // written synchronously right after the PUT. Treating it as failure
+ // would abort almost every successful rotation on the first poll.
+ // - `RolloutIncomplete` means the HCC exhausted ITS 120s readiness budget
+ // (host-context-controller reconciler.ts, pollReadiness 24×5s) — but the
+ // HCC keeps observing past that verdict (post-terminal re-poll) and
+ // corrects the condition to True when a slow pod converges. Latching
+ // failure here would discard the ~60s of budget this poll still holds
+ // and report a deterministic false negative for any rollout converging
+ // between 120s and 180s — the exact bug of issue #223.
+ //
+ // So the ONLY outcomes are: a fresh True (success, above), or this poll's
+ // own bounded timeout — which reports `failed` with the preserved HCC
+ // diagnostic if RolloutIncomplete was seen, `timeout` otherwise.
+ if (fresh.status === 'False' && fresh.reason === ROLLOUT_INCOMPLETE_REASON) {
+ rolloutIncompleteMessage.current =
+ fresh.message || 'The connector rollout did not complete.'
+ // Keep the operator informed instead of silently spinning: the rollout
+ // has outlived the controller's own budget but is still being observed.
+ setPhaseMessage(
+ "The rollout is taking longer than the controller's readiness budget — still verifying…"
+ )
+ }
+ }
+
+ const id = setInterval(() => {
+ if (Date.now() - startedAt >= POLL_TIMEOUT_MS) {
+ clearInterval(id)
+ if (!cancelled) {
+ cancelled = true
+ if (rolloutIncompleteMessage.current !== null) {
+ // The HCC diagnosed the rollout (RolloutIncomplete) and never
+ // corrected it to True within our budget: a real failure, reported
+ // with the controller's own rollout numbers — never degraded to a
+ // bare "timed out".
+ setPhase('failed')
+ setPhaseMessage(rolloutIncompleteMessage.current)
+ } else {
+ // No verdict either way inside the budget — an inconclusive
+ // timeout, distinct from a diagnosed failure.
+ setPhase('timeout')
+ // Diagnostic only. The "what to try next" sentence is mode-specific
+ // and is appended by the timeout banner from `submittedMode`.
+ setPhaseMessage(
+ `The rollout did not finish within ${Math.round(POLL_TIMEOUT_MS / 1000)}s. Run ` +
+ `"kubectl get mcpserver ${serverName} -o yaml" to see the current DeploymentReady ` +
+ 'condition.'
+ )
+ }
+ }
+ return
+ }
+ void poll()
+ }, POLL_INTERVAL_MS)
+
+ return () => {
+ cancelled = true
+ clearInterval(id)
+ }
+ }, [phase, cutoff, serverName, expectedUid, expectedGeneration])
+
+ return { phase, phaseMessage, setPhase, setPhaseMessage }
+}
diff --git a/control-ui/components/__tests__/AttachConnectorCredentials.test.tsx b/control-ui/components/__tests__/AttachConnectorCredentials.test.tsx
new file mode 100644
index 000000000..399d7fc71
--- /dev/null
+++ b/control-ui/components/__tests__/AttachConnectorCredentials.test.tsx
@@ -0,0 +1,357 @@
+import React from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
+import { AttachConnectorCredentials } from '@components/AttachConnectorCredentials'
+import { ToastProvider } from '@components/Toast'
+import { POLL_INTERVAL_MS, POLL_TIMEOUT_MS } from '@constants/connectorCredentials'
+import * as api from '@lib/api'
+import type { McpServerResource } from '@lib/api'
+
+vi.mock('@lib/api', async importOriginal => ({
+ ...(await importOriginal<typeof import('@lib/api')>()),
+ getMcpServer: vi.fn(),
+ getMcpServers: vi.fn(),
+ listMcpSecrets: vi.fn(),
+ getRegistryCredentialSchema: vi.fn(),
+ createMcpSecret: vi.fn(),
+ updateMcpSecret: vi.fn(),
+ updateMcpServer: vi.fn(),
+ deleteMcpSecret: vi.fn(),
+}))
+const source: McpServerResource = {
+ metadata: { name: 'search', uid: 'server-uid', resourceVersion: '12', generation: 2 },
+ spec: { image: 'example/search:v1', egressBindings: [] },
+}
+const reference = { name: 'secret', keys: [{ secretKey: 'api-key', envVar: 'API_KEY' }] }
+let saved: McpServerResource
+const onSpecSaved = vi.fn(),
+ onFinished = vi.fn(),
+ onBusyChange = vi.fn()
+async function flush(count = 20) {
+ for (let i = 0; i < count; i++)
+ await act(async () => {
+ await Promise.resolve()
+ })
+}
+function panel(overrides = {}) {
+ return render(
+ <ToastProvider>
+ <AttachConnectorCredentials
+ serverName="search"
+ server={source}
+ onSpecSaved={onSpecSaved}
+ onFinished={onFinished}
+ onBusyChange={onBusyChange}
+ {...overrides}
+ />
+ </ToastProvider>
+ )
+}
+function fill() {
+ fireEvent.change(screen.getByLabelText(/^Secret name/), { target: { value: 'secret' } })
+ fireEvent.change(screen.getByLabelText(/^Secret key 1/), { target: { value: 'api-key' } })
+ fireEvent.change(screen.getByLabelText(/^Environment variable 1/), {
+ target: { value: 'API_KEY' },
+ })
+ fireEvent.change(screen.getByLabelText(/^Credential value 1/), {
+ target: { value: 'private-value' },
+ })
+}
+async function confirm() {
+ fireEvent.click(screen.getByRole('button', { name: 'Attach and restart' }))
+ await flush()
+ const dialog = screen.getByRole('alertdialog')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Attach and restart' }))
+ await flush()
+}
+async function existing() {
+ fireEvent.click(screen.getByRole('radio', { name: 'Use an existing Secret' }))
+ await flush()
+ fireEvent.change(screen.getByLabelText(/^Existing Secret/), { target: { value: 'secret' } })
+}
+async function tick(ms = POLL_INTERVAL_MS) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms)
+ })
+}
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime('2026-10-23T12:00:00Z')
+ vi.resetAllMocks()
+ saved = {
+ ...source,
+ metadata: { ...source.metadata, generation: 3 },
+ spec: { ...source.spec, envSecret: reference },
+ }
+ vi.mocked(api.getMcpServer).mockResolvedValue(source)
+ vi.mocked(api.getMcpServers).mockResolvedValue({ items: [] })
+ vi.mocked(api.listMcpSecrets).mockResolvedValue({
+ items: [{ name: 'secret', uid: 'secret-uid', keys: ['api-key'] }],
+ })
+ vi.mocked(api.createMcpSecret).mockResolvedValue({
+ name: 'secret',
+ namespace: 'mcp-server',
+ uid: 'created',
+ resourceVersion: '1',
+ })
+ vi.mocked(api.updateMcpServer).mockImplementation(async () => saved)
+ vi.mocked(api.updateMcpSecret).mockResolvedValue({
+ name: 'secret',
+ namespace: 'mcp-server',
+ keys: ['api-key'],
+ affectedConnectors: ['other'],
+ })
+})
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+})
+
+describe('attach form', () => {
+ it('validates before requests and associates/focuses the rejected control', async () => {
+ panel()
+ fireEvent.click(screen.getByRole('button', { name: 'Attach and restart' }))
+ const input = screen.getByLabelText(/^Secret name/)
+ expect(input).toHaveFocus()
+ expect(input).toHaveAttribute('aria-invalid', 'true')
+ expect(document.getElementById(input.getAttribute('aria-describedby'))).toHaveTextContent(
+ 'Enter a Secret name'
+ )
+ expect(api.getMcpServer).not.toHaveBeenCalled()
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ })
+ it('names missing values and makes no writes', () => {
+ panel()
+ fill()
+ fireEvent.change(screen.getByLabelText(/^Credential value 1/), { target: { value: '' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Attach and restart' }))
+ expect(screen.getByRole('alert')).toHaveTextContent('api-key')
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ })
+ it('blocks attach while the page has unsaved egress edits', () => {
+ panel({ blockedReason: 'Save or discard egress edits.' })
+ fill()
+ expect(screen.getByRole('button', { name: 'Attach and restart' })).toBeDisabled()
+ })
+ it('creates, saves a reference, clears values, and waits for correlated readiness', async () => {
+ panel()
+ fill()
+ await confirm()
+ expect(onSpecSaved).toHaveBeenCalledWith(saved)
+ expect(onBusyChange).toHaveBeenLastCalledWith(true)
+ expect(screen.getByLabelText(/^Credential value 1/)).toHaveValue('')
+ expect(screen.getByText(/Waiting for search to become ready/)).toBeInTheDocument()
+ expect(onFinished).not.toHaveBeenCalled()
+ vi.mocked(api.getMcpServer).mockResolvedValue({
+ ...saved,
+ status: {
+ conditions: [
+ {
+ type: 'DeploymentReady',
+ status: 'True',
+ reason: 'ReplicasAvailable',
+ message: '',
+ lastTransitionTime: new Date().toISOString(),
+ observedGeneration: 2,
+ },
+ ],
+ },
+ })
+ await tick()
+ expect(onFinished).not.toHaveBeenCalled()
+ vi.mocked(api.getMcpServer).mockResolvedValue({
+ ...saved,
+ status: {
+ conditions: [
+ {
+ type: 'DeploymentReady',
+ status: 'True',
+ reason: 'ReplicasAvailable',
+ message: '',
+ lastTransitionTime: new Date().toISOString(),
+ observedGeneration: 3,
+ },
+ ],
+ },
+ })
+ await tick()
+ expect(onFinished).toHaveBeenCalledOnce()
+ expect(screen.getByText('Credentials attached. search is ready.')).toBeInTheDocument()
+ await tick()
+ expect(onFinished).toHaveBeenCalledOnce()
+ })
+ it('loads existing keys, edits mappings, and skips Secret writes for blank values', async () => {
+ panel()
+ await existing()
+ expect(screen.getByLabelText(/^Secret key 1/)).toHaveValue('api-key')
+ expect(screen.getByLabelText(/^Environment variable 1/)).toHaveValue('API_KEY')
+ await confirm()
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpServer).toHaveBeenCalledOnce()
+ })
+ it('warns about other consumers and records the affected list when values are entered', async () => {
+ vi.mocked(api.getMcpServers).mockResolvedValue({
+ items: [{ metadata: { name: 'other' }, spec: { envSecret: reference } }],
+ })
+ panel()
+ await existing()
+ fireEvent.change(screen.getByLabelText(/^Credential value 1/), {
+ target: { value: 'replacement' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Attach and restart' }))
+ await flush()
+ expect(screen.getByRole('alertdialog')).toHaveTextContent('Current references: other')
+ fireEvent.click(
+ within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Attach and restart' })
+ )
+ await flush()
+ expect(api.updateMcpSecret).toHaveBeenCalledWith('secret', { 'api-key': 'replacement' })
+ expect(
+ screen.getByText(/Other connectors sharing this Secret roll out separately: other/)
+ ).toBeInTheDocument()
+ })
+ it('keeps a generic shared-Secret warning if the consumer preview fails', async () => {
+ vi.mocked(api.getMcpServers).mockRejectedValue(new Error('unavailable'))
+ panel()
+ await existing()
+ fireEvent.change(screen.getByLabelText(/^Credential value 1/), {
+ target: { value: 'replacement' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Attach and restart' }))
+ await flush()
+ expect(screen.getByRole('alertdialog')).toHaveTextContent('may restart any connector')
+ })
+ it('retries list failure and clears drafts on mode and Secret switches', async () => {
+ vi.mocked(api.listMcpSecrets).mockRejectedValueOnce(new Error('unavailable'))
+ panel()
+ fill()
+ fireEvent.click(screen.getByRole('radio', { name: 'Use an existing Secret' }))
+ await flush()
+ expect(screen.getByRole('button', { name: 'Attach and restart' })).toBeDisabled()
+ fireEvent.click(screen.getByRole('button', { name: 'Retry loading Secrets' }))
+ await flush()
+ fireEvent.change(screen.getByLabelText(/^Existing Secret/), { target: { value: 'secret' } })
+ expect(screen.getByLabelText(/^Credential value 1/)).toHaveValue('')
+ fireEvent.change(screen.getByLabelText(/^Credential value 1/), {
+ target: { value: 'new-draft' },
+ })
+ fireEvent.click(screen.getByRole('radio', { name: 'Create a new Secret' }))
+ expect(screen.getByLabelText(/^Credential value 1/)).toHaveValue('')
+ })
+ it('offers explicit existing mode on collision without overwriting', async () => {
+ vi.mocked(api.createMcpSecret).mockRejectedValue(
+ Object.assign(new Error('collision'), { status: 409 })
+ )
+ panel()
+ fill()
+ await confirm()
+ expect(screen.getByRole('alert')).toHaveTextContent('already exists')
+ expect(api.updateMcpSecret).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Choose existing Secret' }))
+ await flush()
+ fireEvent.change(screen.getByLabelText(/^Existing Secret/), { target: { value: 'secret' } })
+ expect(screen.getByLabelText(/^Credential value 1/)).toHaveValue('')
+ })
+ it('requires refresh after an unknown create outcome, never retries the POST', async () => {
+ vi.mocked(api.createMcpSecret).mockRejectedValue(new TypeError('network'))
+ panel()
+ fill()
+ await confirm()
+ expect(screen.getByRole('alert')).toHaveTextContent('could not be confirmed')
+ expect(onBusyChange).toHaveBeenLastCalledWith(true)
+ expect(screen.queryByRole('button', { name: 'Attach and restart' })).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh credentials' }))
+ expect(onFinished).toHaveBeenCalledOnce()
+ expect(api.createMcpSecret).toHaveBeenCalledOnce()
+ })
+ it('times out a saved attachment and hands off without deleting or creating again', async () => {
+ panel()
+ fill()
+ await confirm()
+ vi.mocked(api.getMcpServer).mockResolvedValue(saved)
+ await tick(POLL_TIMEOUT_MS)
+ expect(screen.getByRole('alert')).toHaveTextContent('Credentials were attached')
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh credentials' }))
+ expect(onFinished).toHaveBeenCalledOnce()
+ expect(api.createMcpSecret).toHaveBeenCalledOnce()
+ })
+ it('allows leaving verification after a saved attachment', async () => {
+ panel()
+ fill()
+ await confirm()
+ fireEvent.click(screen.getByRole('button', { name: 'Check credentials later' }))
+ expect(onFinished).toHaveBeenCalledOnce()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('does not misreport a saved attachment without generation as successful', async () => {
+ delete saved.metadata.generation
+ panel()
+ fill()
+ await confirm()
+ expect(screen.getByRole('alert')).toHaveTextContent('rollout identity could not be verified')
+ expect(onSpecSaved).toHaveBeenCalledOnce()
+ expect(onFinished).not.toHaveBeenCalled()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('keeps manual rows when optional schema arrives after editing', async () => {
+ let resolve: (value: api.CredentialSchema) => void
+ vi.mocked(api.getRegistryCredentialSchema).mockImplementation(
+ () =>
+ new Promise(done => {
+ resolve = done
+ })
+ )
+ panel({ registryCredentialSource: { name: 'catalog', version: '1' } })
+ fill()
+ await act(async () => {
+ resolve({
+ required: false,
+ authType: 'none',
+ keys: [{ name: 'OTHER', label: 'Other', kind: 'text' }],
+ })
+ })
+ expect(screen.getByLabelText(/^Secret key 1/)).toHaveValue('api-key')
+ })
+ it.each(['empty', 'error'])(
+ 'keeps manual entry usable with optional schema %s',
+ async outcome => {
+ if (outcome === 'error')
+ vi.mocked(api.getRegistryCredentialSchema).mockRejectedValue(new Error('unavailable'))
+ else
+ vi.mocked(api.getRegistryCredentialSchema).mockResolvedValue({
+ required: false,
+ authType: 'none',
+ keys: [],
+ })
+ panel({ registryCredentialSource: { name: 'catalog', version: '1' } })
+ await flush()
+ fill()
+ await confirm()
+ expect(api.updateMcpServer).toHaveBeenCalledOnce()
+ }
+ )
+ it('uses stable row identities when removing earlier rows', () => {
+ panel()
+ fill()
+ fireEvent.click(screen.getByRole('button', { name: 'Add key mapping' }))
+ fireEvent.change(screen.getByLabelText(/^Credential value 2/), { target: { value: 'second' } })
+ const remaining = screen.getByLabelText(/^Credential value 2/)
+ fireEvent.click(screen.getByRole('button', { name: 'Remove mapping 1' }))
+ expect(screen.getByLabelText(/^Credential value 1/)).toBe(remaining)
+ expect(remaining).toHaveValue('second')
+ })
+ it('does not submit twice while confirmation is open', async () => {
+ panel()
+ fill()
+ fireEvent.click(screen.getByRole('button', { name: 'Attach and restart' }))
+ await flush()
+ fireEvent.submit(screen.getByLabelText(/^Secret name/).closest('form'))
+ fireEvent.click(
+ within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Attach and restart' })
+ )
+ await flush()
+ expect(api.createMcpSecret).toHaveBeenCalledOnce()
+ })
+})
diff --git a/control-ui/components/__tests__/ConnectorEditContext.test.tsx b/control-ui/components/__tests__/ConnectorEditContext.test.tsx
index f4421e9d3..952b11989 100644
--- a/control-ui/components/__tests__/ConnectorEditContext.test.tsx
+++ b/control-ui/components/__tests__/ConnectorEditContext.test.tsx
@@ -173,7 +173,7 @@ describe('connector edit agent access', () => {
activeTab = 'credentials'
rerender(<EditMcpServerPage />)
- expect(screen.getByRole('button', { name: 'Rotate credential' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'Attach and restart' })).toBeEnabled()
activeTab = 'egress'
rerender(<EditMcpServerPage />)
diff --git a/control-ui/components/__tests__/EditMcpServerPageAttach.test.tsx b/control-ui/components/__tests__/EditMcpServerPageAttach.test.tsx
new file mode 100644
index 000000000..a605c9d1d
--- /dev/null
+++ b/control-ui/components/__tests__/EditMcpServerPageAttach.test.tsx
@@ -0,0 +1,202 @@
+import React from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
+import { ToastProvider } from '@components/Toast'
+import { POLL_INTERVAL_MS, POLL_TIMEOUT_MS } from '@constants/connectorCredentials'
+import * as api from '@lib/api'
+import type { McpServerResource } from '@lib/api'
+import EditMcpServerPage from '../../app/mcp-servers/[name]/edit/page'
+
+const navigation = vi.hoisted(() => ({ tab: 'credentials', push: vi.fn(), replace: vi.fn() }))
+vi.mock('next/navigation', () => ({
+ useParams: () => ({ name: 'search', tab: navigation.tab }),
+ useRouter: () => navigation,
+}))
+vi.mock('@components/AuthGate', () => ({ AuthGate: ({ children }) => children }))
+vi.mock('@components/DashboardLayout', () => ({ DashboardLayout: ({ children }) => children }))
+vi.mock('@lib/api', async importOriginal => ({
+ ...(await importOriginal<typeof import('@lib/api')>()),
+ getMcpServer: vi.fn(),
+ getMcpServers: vi.fn(),
+ getHosts: vi.fn(),
+ getContexts: vi.fn(),
+ listMcpSecrets: vi.fn(),
+ createMcpSecret: vi.fn(),
+ updateMcpSecret: vi.fn(),
+ updateMcpServer: vi.fn(),
+ deleteMcpSecret: vi.fn(),
+}))
+let current: McpServerResource
+async function flush() {
+ for (let i = 0; i < 30; i++)
+ await act(async () => {
+ await Promise.resolve()
+ })
+}
+function page() {
+ return (
+ <ToastProvider>
+ <EditMcpServerPage />
+ </ToastProvider>
+ )
+}
+async function open() {
+ const result = render(page())
+ await flush()
+ return result
+}
+async function submit() {
+ fireEvent.change(screen.getByLabelText(/^Secret name/), { target: { value: 'secret' } })
+ fireEvent.change(screen.getByLabelText(/^Secret key 1/), { target: { value: 'api-key' } })
+ fireEvent.change(screen.getByLabelText(/^Environment variable 1/), {
+ target: { value: 'API_KEY' },
+ })
+ fireEvent.change(screen.getByLabelText(/^Credential value 1/), { target: { value: 'value' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Attach and restart' }))
+ await flush()
+ fireEvent.click(
+ within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Attach and restart' })
+ )
+ await flush()
+}
+async function tick(ms = POLL_INTERVAL_MS) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms)
+ })
+ await flush()
+}
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime('2026-10-23T12:00:00Z')
+ vi.resetAllMocks()
+ navigation.tab = 'credentials'
+ current = {
+ metadata: { name: 'search', uid: 'uid', resourceVersion: '12', generation: 2 },
+ spec: { image: 'example/search:v1' },
+ }
+ vi.mocked(api.getMcpServer).mockImplementation(async () => structuredClone(current))
+ vi.mocked(api.getMcpServers).mockResolvedValue({ items: [] })
+ vi.mocked(api.getHosts).mockResolvedValue({ items: [] })
+ vi.mocked(api.getContexts).mockResolvedValue({ items: [] })
+ vi.mocked(api.createMcpSecret).mockResolvedValue({
+ name: 'secret',
+ namespace: 'mcp-server',
+ uid: 'secret-uid',
+ resourceVersion: '1',
+ })
+ vi.mocked(api.updateMcpServer).mockImplementation(async (_name, payload) => {
+ current = {
+ ...current,
+ metadata: { ...current.metadata, generation: 3, resourceVersion: '13' },
+ spec: payload.spec,
+ }
+ return structuredClone(current)
+ })
+})
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+})
+
+describe('keyless edit credentials journey', () => {
+ it('keeps egress blocked after an unknown save and hides stale settings if refresh fails', async () => {
+ vi.mocked(api.updateMcpServer).mockRejectedValue(new TypeError('network'))
+ await open()
+ await submit()
+ expect(screen.getByRole('tab', { name: 'External Egress' })).toBeDisabled()
+ vi.mocked(api.getMcpServer).mockRejectedValue(new Error('Connector read unavailable'))
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh credentials' }))
+ await flush()
+ expect(screen.queryByRole('button', { name: 'Attach and restart' })).not.toBeInTheDocument()
+ expect(screen.getByRole('alert')).toHaveTextContent('Connector read unavailable')
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+
+ it('renders attach in the existing centered edit card', async () => {
+ await open()
+ expect(screen.getByRole('heading', { name: 'Attach credentials' })).toBeInTheDocument()
+ expect(screen.getByRole('heading', { name: 'Edit Connector: search' })).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'Attach and restart' }).closest('.cu-connector-edit-form')
+ ).not.toBeNull()
+ })
+ it.each([
+ { managed: false },
+ { enabled: false },
+ { envSecret: null },
+ { envSecret: { name: 'broken' } },
+ { oauth: {} },
+ { oauth: null },
+ { oauth: { id: 'x', provider: 'slack' } },
+ { oauth: { id: 'x', source: 'generic' } },
+ { oauth: { id: 'x', source: 'remote' } },
+ ])('does not offer attach for excluded state %j', async spec => {
+ current.spec = { ...current.spec, ...spec }
+ await open()
+ expect(screen.queryByRole('button', { name: 'Attach and restart' })).not.toBeInTheDocument()
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ })
+ it('retains the running panel after spec save, then refreshes into rotation on correlated success', async () => {
+ await open()
+ await submit()
+ expect(screen.getByText(/Waiting for search to become ready/)).toBeInTheDocument()
+ expect(screen.getByRole('tab', { name: 'External Egress' })).toBeDisabled()
+ expect(screen.queryByRole('button', { name: 'Rotate credentials' })).not.toBeInTheDocument()
+ current.status = {
+ conditions: [
+ {
+ type: 'DeploymentReady',
+ status: 'True',
+ reason: 'ReplicasAvailable',
+ message: '',
+ observedGeneration: 2,
+ lastTransitionTime: new Date().toISOString(),
+ },
+ ],
+ }
+ await tick()
+ expect(screen.getByRole('heading', { name: 'Attach credentials' })).toBeInTheDocument()
+ current.status.conditions[0].observedGeneration = 3
+ await tick()
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()
+ expect(screen.queryByRole('heading', { name: 'Attach credentials' })).not.toBeInTheDocument()
+ expect(api.createMcpSecret).toHaveBeenCalledOnce()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('refreshes a saved timed-out attachment into rotation without another create', async () => {
+ await open()
+ await submit()
+ await tick(POLL_TIMEOUT_MS)
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh credentials' }))
+ await flush()
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()
+ expect(api.createMcpSecret).toHaveBeenCalledOnce()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('blocks attach until unsaved egress changes are explicitly discarded', async () => {
+ navigation.tab = 'egress'
+ const view = await open()
+ fireEvent.change(screen.getByLabelText('Egress mode'), { target: { value: 'public-web' } })
+ await flush()
+ navigation.tab = 'credentials'
+ view.rerender(page())
+ await flush()
+ expect(screen.getByRole('button', { name: 'Attach and restart' })).toBeDisabled()
+ expect(screen.getByText(/Save or discard your egress changes/)).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Discard egress changes' }))
+ expect(screen.getByRole('button', { name: 'Attach and restart' })).toBeEnabled()
+ })
+ it('supports the existing static remote header-placeholder path with an explicit limitation', async () => {
+ current.spec.remote = {
+ baseUrl: 'https://api.example.com',
+ authHeaders: [{ name: 'X-API-Key', valueTemplate: '${API_KEY}' }],
+ }
+ await open()
+ expect(screen.getByText(/attaching does not add headers/)).toBeInTheDocument()
+ await submit()
+ expect(api.updateMcpServer).toHaveBeenCalledWith(
+ 'search',
+ expect.objectContaining({ spec: expect.objectContaining({ remote: current.spec.remote }) })
+ )
+ })
+})
diff --git a/control-ui/components/__tests__/useRolloutWait.test.tsx b/control-ui/components/__tests__/useRolloutWait.test.tsx
new file mode 100644
index 000000000..e7cad7acb
--- /dev/null
+++ b/control-ui/components/__tests__/useRolloutWait.test.tsx
@@ -0,0 +1,183 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, renderHook } from '@testing-library/react'
+import type { RolloutWaitOptions } from '@components/UpdateConnectorCredentials/types'
+import { useRolloutWait } from '@components/UpdateConnectorCredentials/useRolloutWait'
+import { POLL_INTERVAL_MS, POLL_TIMEOUT_MS } from '@constants/connectorCredentials'
+import { getMcpServer } from '@lib/api'
+import type { McpServerResource } from '@lib/api'
+
+vi.mock('@lib/api', () => ({ getMcpServer: vi.fn() }))
+const cutoff = '2026-10-23T12:00:00.000Z'
+const target: RolloutWaitOptions = {
+ serverName: 'connector',
+ cutoff,
+ expectedUid: 'uid',
+ expectedGeneration: 3,
+}
+function response(
+ status: 'True' | 'False' = 'True',
+ options: {
+ generation?: number
+ observedGeneration?: number
+ timestamp?: string
+ reason?: string
+ uid?: string
+ } = {}
+): McpServerResource {
+ return {
+ metadata: { uid: options.uid ?? 'uid', generation: options.generation ?? 3 },
+ status: {
+ conditions: [
+ {
+ type: 'DeploymentReady',
+ status,
+ reason: options.reason ?? (status === 'True' ? 'ReplicasAvailable' : 'RolloutIncomplete'),
+ message: 'updated 0/1',
+ lastTransitionTime: options.timestamp ?? '2026-10-23T12:00:01.000Z',
+ observedGeneration: options.observedGeneration ?? 3,
+ },
+ ],
+ },
+ }
+}
+function start(options: RolloutWaitOptions = target) {
+ const hook = renderHook(props => useRolloutWait(props), { initialProps: options })
+ act(() => hook.result.current.setPhase('rotating'))
+ return hook
+}
+async function tick(ms = POLL_INTERVAL_MS) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms)
+ })
+}
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(cutoff)
+ vi.resetAllMocks()
+ vi.mocked(getMcpServer).mockResolvedValue({
+ metadata: { uid: 'uid', generation: 3 },
+ status: { conditions: [] },
+ })
+})
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+})
+
+describe('shared rollout observation', () => {
+ it('succeeds only with a fresh True for the exact attach generation and UID', async () => {
+ vi.mocked(getMcpServer)
+ .mockResolvedValueOnce(response('True', { observedGeneration: 2 }))
+ .mockResolvedValueOnce(response('True', { timestamp: cutoff }))
+ .mockResolvedValueOnce(response())
+ const hook = start()
+ await tick()
+ expect(hook.result.current.phase).toBe('rotating')
+ await tick()
+ expect(hook.result.current.phase).toBe('rotating')
+ await tick()
+ expect(hook.result.current.phase).toBe('success')
+ })
+ it('does not accept missing generation metadata', async () => {
+ const missing = response()
+ delete missing.metadata.generation
+ vi.mocked(getMcpServer).mockResolvedValue(missing)
+ const hook = start()
+ await tick(POLL_TIMEOUT_MS)
+ expect(hook.result.current.phase).toBe('timeout')
+ })
+ it('does not accept a missing condition observedGeneration', async () => {
+ const missing = response()
+ delete missing.status.conditions[0].observedGeneration
+ vi.mocked(getMcpServer).mockResolvedValue(missing)
+ const hook = start()
+ await tick()
+ expect(hook.result.current.phase).toBe('rotating')
+ })
+ it.each([{ uid: 'replacement' }, { generation: 4 }])(
+ 'requires refresh when identity/spec changes %j',
+ async changed => {
+ vi.mocked(getMcpServer).mockResolvedValue(response('True', changed))
+ const hook = start()
+ await tick()
+ expect(hook.result.current.phase).toBe('failed')
+ expect(hook.result.current.phaseMessage).toContain('Refresh')
+ }
+ )
+ it('preserves timestamp-only rotation behavior', async () => {
+ const oldProducer = response()
+ delete oldProducer.metadata
+ delete oldProducer.status.conditions[0].observedGeneration
+ vi.mocked(getMcpServer).mockResolvedValue(oldProducer)
+ const hook = start({ serverName: 'connector', cutoff })
+ await tick()
+ expect(hook.result.current.phase).toBe('success')
+ })
+ it('keeps polling through transient False and RolloutIncomplete, then accepts recovery', async () => {
+ vi.mocked(getMcpServer)
+ .mockResolvedValueOnce(response('False', { reason: 'WaitingForReplicas' }))
+ .mockResolvedValueOnce(response('False'))
+ .mockResolvedValue(response())
+ const hook = start()
+ await tick()
+ expect(hook.result.current.phase).toBe('rotating')
+ await tick()
+ expect(hook.result.current.phase).toBe('rotating')
+ await tick()
+ expect(hook.result.current.phase).toBe('success')
+ })
+ it('keeps the HCC diagnostic until its own timeout, including read failures', async () => {
+ vi.mocked(getMcpServer)
+ .mockResolvedValueOnce(response('False'))
+ .mockRejectedValue(new Error('unavailable'))
+ const hook = start()
+ await tick()
+ expect(hook.result.current.phase).toBe('rotating')
+ await tick(POLL_TIMEOUT_MS - POLL_INTERVAL_MS)
+ expect(hook.result.current.phase).toBe('failed')
+ expect(hook.result.current.phaseMessage).toBe('updated 0/1')
+ })
+ it('distinguishes an inconclusive timeout from a diagnosed failure', async () => {
+ const hook = start()
+ await tick(POLL_TIMEOUT_MS)
+ expect(hook.result.current.phase).toBe('timeout')
+ })
+ it('ignores a read completing after the timeout', async () => {
+ let resolve: (value: McpServerResource) => void
+ vi.mocked(getMcpServer).mockImplementation(
+ () =>
+ new Promise(done => {
+ resolve = done
+ })
+ )
+ const hook = start()
+ await tick(POLL_TIMEOUT_MS)
+ await act(async () => {
+ resolve(response())
+ })
+ expect(hook.result.current.phase).toBe('timeout')
+ })
+ it('cancels pending reads/timers on reset, new attempt, and unmount', async () => {
+ let resolve: (value: McpServerResource) => void
+ vi.mocked(getMcpServer).mockImplementation(
+ () =>
+ new Promise(done => {
+ resolve = done
+ })
+ )
+ const hook = start()
+ await tick()
+ act(() => hook.result.current.setPhase('idle'))
+ await act(async () => {
+ resolve(response())
+ })
+ expect(hook.result.current.phase).toBe('idle')
+ vi.mocked(getMcpServer).mockResolvedValue(response())
+ hook.rerender({ ...target, cutoff: '2026-10-23T12:01:00.000Z' })
+ act(() => hook.result.current.setPhase('rotating'))
+ await tick()
+ expect(hook.result.current.phase).toBe('rotating')
+ hook.unmount()
+ expect(vi.getTimerCount()).toBe(0)
+ })
+})
diff --git a/control-ui/lib/__tests__/connectorCredentials.test.ts b/control-ui/lib/__tests__/connectorCredentials.test.ts
new file mode 100644
index 000000000..22e39422a
--- /dev/null
+++ b/control-ui/lib/__tests__/connectorCredentials.test.ts
@@ -0,0 +1,384 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import * as api from '@lib/api'
+import type { McpServerResource } from '@lib/api'
+import {
+ attachConnectorCredentials,
+ buildAttachPayload,
+ credentialAttachUnavailable,
+ validateCredentialAttach,
+} from '@lib/connectorCredentials'
+import type { AttachCredentialRow, AttachCredentialsRequest } from '@lib/connectorCredentials.types'
+
+vi.mock('@lib/api', async importOriginal => ({
+ ...(await importOriginal<typeof import('@lib/api')>()),
+ getMcpServer: vi.fn(),
+ listMcpSecrets: vi.fn(),
+ createMcpSecret: vi.fn(),
+ updateMcpSecret: vi.fn(),
+ deleteMcpSecret: vi.fn(),
+ updateMcpServer: vi.fn(),
+}))
+
+const reference = { name: 'new-secret', keys: [{ secretKey: 'api-key', envVar: 'API_KEY' }] }
+const row: AttachCredentialRow = {
+ id: 'row',
+ secretKey: 'api-key',
+ envVar: 'API_KEY',
+ value: ' private bytes ',
+}
+function server(): McpServerResource {
+ return {
+ metadata: { name: 'connector', uid: 'server-uid', resourceVersion: '10', generation: 2 },
+ spec: {
+ image: 'example/image:v1',
+ managed: true,
+ egressBindings: [{ dns: 'api.example.com', port: 443 }],
+ },
+ }
+}
+function error(status: number, body?: object) {
+ return Object.assign(new Error('request failed'), { status, body })
+}
+function request(overrides: Partial<AttachCredentialsRequest> = {}): AttachCredentialsRequest {
+ return {
+ serverName: 'connector',
+ secretName: 'new-secret',
+ mode: 'create-new',
+ rows: [{ ...row }],
+ onSecretWritten: vi.fn(),
+ ...overrides,
+ }
+}
+const existing = { name: 'new-secret', uid: 'secret-uid', keys: ['api-key'] }
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ vi.mocked(api.getMcpServer).mockResolvedValue(server())
+ vi.mocked(api.listMcpSecrets).mockResolvedValue({ items: [existing] })
+ vi.mocked(api.createMcpSecret).mockResolvedValue({
+ name: 'new-secret',
+ namespace: 'mcp-server',
+ uid: 'created-uid',
+ resourceVersion: 'secret-rv',
+ })
+ vi.mocked(api.updateMcpSecret).mockResolvedValue({
+ name: 'new-secret',
+ namespace: 'mcp-server',
+ keys: ['api-key'],
+ affectedConnectors: ['other'],
+ })
+ vi.mocked(api.updateMcpServer).mockImplementation(async (_name, payload) => ({
+ ...server(),
+ metadata: { ...server().metadata, generation: 3 },
+ spec: payload.spec,
+ }))
+ vi.mocked(api.deleteMcpSecret).mockResolvedValue({ name: 'new-secret', namespace: 'mcp-server' })
+})
+
+describe('attach validation', () => {
+ it.each(['-abc', 'UPPER', 'a'.repeat(254), ''])('rejects invalid Secret name %s', name => {
+ expect(validateCredentialAttach('create-new', name, [row], server())?.field).toBe('secret')
+ })
+ it.each(['.', '..data', '', 'a/b', 'a'.repeat(254)])('rejects invalid key %s', secretKey => {
+ expect(
+ validateCredentialAttach('create-new', 'secret', [{ ...row, secretKey }], server())?.field
+ ).toBe('row-key')
+ })
+ it.each(['', '1INVALID', 'KEY-VAR', 'NODE_OPTIONS', 'path'])(
+ 'rejects invalid or dangerous env %s',
+ envVar => {
+ expect(
+ validateCredentialAttach('create-new', 'secret', [{ ...row, envVar }], server())?.field
+ ).toBe('row-env')
+ }
+ )
+ it('requires rows, every new value, and a selected existing Secret', () => {
+ expect(validateCredentialAttach('create-new', 'secret', [], server())?.message).toContain(
+ 'at least one'
+ )
+ expect(
+ validateCredentialAttach('create-new', 'secret', [{ ...row, value: '' }], server())?.field
+ ).toBe('row-value')
+ expect(validateCredentialAttach('use-existing', 'secret', [row], server())?.field).toBe(
+ 'secret'
+ )
+ })
+ it('rejects duplicate destinations, env collisions, and conflicting duplicate-key values', () => {
+ const target = server()
+ target.spec.env = [{ name: 'API_KEY', value: 'plain' }]
+ expect(validateCredentialAttach('create-new', 'secret', [row], target)?.message).toContain(
+ 'already mapped'
+ )
+ target.spec.env = []
+ target.spec.envMapping = { token: 'API_KEY' }
+ expect(validateCredentialAttach('create-new', 'secret', [row], target)?.message).toContain(
+ 'already mapped'
+ )
+ expect(
+ validateCredentialAttach('create-new', 'secret', [row, { ...row, id: 'two' }], server())
+ ?.message
+ ).toContain('already mapped')
+ expect(
+ validateCredentialAttach(
+ 'create-new',
+ 'secret',
+ [row, { ...row, id: 'two', envVar: 'OTHER_KEY', value: 'different' }],
+ server()
+ )?.message
+ ).toContain('same value')
+ })
+ it('preserves credential bytes and safely serializes prototype-overlapping keys', () => {
+ const rows = ['__proto__', 'constructor', 'toString'].map((secretKey, index) => ({
+ ...row,
+ id: String(index),
+ secretKey,
+ envVar: `KEY_${index}`,
+ }))
+ const payload = buildAttachPayload(' secret ', rows)
+ expect(Object.getPrototypeOf(payload.data)).toBeNull()
+ expect(JSON.parse(JSON.stringify(payload.data))['__proto__']).toBe(row.value)
+ expect(payload.reference.name).toBe('secret')
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined()
+ })
+ it.each([
+ { envSecret: null },
+ { envSecret: { name: 'broken' } },
+ { oauth: null },
+ { oauth: {} },
+ { managed: false },
+ { enabled: false },
+ ])('blocks structural ineligibility %j', spec => {
+ expect(
+ credentialAttachUnavailable({ ...server(), spec: { ...server().spec, ...spec } })
+ ).toBeTruthy()
+ })
+})
+
+describe('ordered attach writes and recovery', () => {
+ it('refuses a same-name replacement since the page loaded before touching any Secret', async () => {
+ await expect(
+ attachConnectorCredentials(request({ expectedUid: 'old-page-uid' }))
+ ).rejects.toThrow('replaced')
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpSecret).not.toHaveBeenCalled()
+ })
+
+ it('preserves fresh spec, fences by UID/RV, and keeps values out of spec', async () => {
+ const fresh = server()
+ fresh.metadata.resourceVersion = '12'
+ vi.mocked(api.getMcpServer).mockResolvedValueOnce(server()).mockResolvedValueOnce(fresh)
+ const input = request()
+ const result = await attachConnectorCredentials(input)
+ expect(api.createMcpSecret).toHaveBeenCalledWith('new-secret', { 'api-key': row.value })
+ expect(api.updateMcpServer).toHaveBeenCalledWith('connector', {
+ metadata: { uid: 'server-uid', resourceVersion: '12' },
+ spec: { ...fresh.spec, envSecret: reference },
+ })
+ expect(api.getMcpServer.mock.invocationCallOrder[0]).toBeLessThan(
+ api.createMcpSecret.mock.invocationCallOrder[0]
+ )
+ expect(api.createMcpSecret.mock.invocationCallOrder[0]).toBeLessThan(
+ api.getMcpServer.mock.invocationCallOrder[1]
+ )
+ expect(api.getMcpServer.mock.invocationCallOrder[1]).toBeLessThan(
+ api.updateMcpServer.mock.invocationCallOrder[0]
+ )
+ expect(JSON.stringify(api.updateMcpServer.mock.calls)).not.toContain(row.value)
+ expect(result.server.metadata.generation).toBe(3)
+ expect(input.onSecretWritten).toHaveBeenCalledOnce()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it.each([409, 500, 503])('never overwrites after rejected create %s', async status => {
+ vi.mocked(api.createMcpSecret).mockRejectedValue(error(status))
+ await expect(attachConnectorCredentials(request())).rejects.toMatchObject({
+ collision: status === 409,
+ refreshRequired: status !== 409,
+ })
+ expect(api.updateMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('does not blindly overwrite or delete after lost create response', async () => {
+ vi.mocked(api.createMcpSecret).mockRejectedValue(new TypeError('network'))
+ await expect(attachConnectorCredentials(request())).rejects.toMatchObject({
+ refreshRequired: true,
+ })
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpSecret).not.toHaveBeenCalled()
+ })
+ it.each([true, false])(
+ 'handles a partial create with complete repair identity=%s',
+ async complete => {
+ vi.mocked(api.createMcpSecret).mockRejectedValue(
+ error(503, {
+ error: 'mcp_secret_rollback_permit_unavailable',
+ outcome: 'repair_required',
+ created: {
+ name: 'new-secret',
+ namespace: 'mcp-server',
+ uid: 'repair-uid',
+ ...(complete ? { resourceVersion: 'repair-rv' } : {}),
+ },
+ })
+ )
+ await expect(attachConnectorCredentials(request())).rejects.toThrow()
+ if (complete)
+ expect(api.deleteMcpSecret).toHaveBeenCalledWith('new-secret', {
+ uid: 'repair-uid',
+ resourceVersion: 'repair-rv',
+ })
+ else expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ }
+ )
+ it('refuses a successful create without identity', async () => {
+ vi.mocked(api.createMcpSecret).mockResolvedValue({
+ name: 'new-secret',
+ namespace: 'mcp-server',
+ })
+ await expect(attachConnectorCredentials(request())).rejects.toMatchObject({
+ refreshRequired: true,
+ })
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ })
+ it.each([409, 422])(
+ 'cleans only the exact created Secret after definite spec rejection %s',
+ async status => {
+ vi.mocked(api.updateMcpServer).mockRejectedValue(error(status))
+ await expect(attachConnectorCredentials(request())).rejects.toThrow('could not be attached')
+ expect(api.deleteMcpSecret).toHaveBeenCalledWith('new-secret', {
+ uid: 'created-uid',
+ resourceVersion: 'secret-rv',
+ })
+ }
+ )
+ it.each([409, 503])('reports both failures when cleanup is refused %s', async status => {
+ vi.mocked(api.updateMcpServer).mockRejectedValue(error(422))
+ vi.mocked(api.deleteMcpSecret).mockRejectedValue(error(status))
+ await expect(attachConnectorCredentials(request())).rejects.toThrow(
+ /could not be attached.*Cleanup.*new-secret/
+ )
+ expect(api.deleteMcpSecret).toHaveBeenCalledOnce()
+ })
+ it('treats an already absent cleanup target as cleaned', async () => {
+ vi.mocked(api.updateMcpServer).mockRejectedValue(error(422))
+ vi.mocked(api.deleteMcpSecret).mockRejectedValue(error(404))
+ await expect(attachConnectorCredentials(request())).rejects.not.toThrow('Cleanup')
+ })
+ it('continues verification after a lost PUT response and matching readback', async () => {
+ vi.mocked(api.updateMcpServer).mockRejectedValue(new TypeError('network'))
+ const saved = {
+ ...server(),
+ metadata: { ...server().metadata, generation: 3 },
+ spec: { ...server().spec, envSecret: reference },
+ }
+ vi.mocked(api.getMcpServer)
+ .mockResolvedValueOnce(server())
+ .mockResolvedValueOnce(server())
+ .mockResolvedValueOnce(saved)
+ expect((await attachConnectorCredentials(request())).server).toEqual(saved)
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it.each(['old', 'replaced', 'unreadable'])(
+ 'retains Secret when PUT outcome is uncertain (%s)',
+ async outcome => {
+ vi.mocked(api.updateMcpServer).mockRejectedValue(error(500))
+ const read = vi
+ .mocked(api.getMcpServer)
+ .mockResolvedValueOnce(server())
+ .mockResolvedValueOnce(server())
+ if (outcome === 'unreadable') read.mockRejectedValueOnce(error(503))
+ else
+ read.mockResolvedValueOnce({
+ ...server(),
+ metadata: {
+ ...server().metadata,
+ uid: outcome === 'replaced' ? 'replacement' : 'server-uid',
+ },
+ })
+ await expect(attachConnectorCredentials(request())).rejects.toThrow('Secret was retained')
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ }
+ )
+ it.each(['uid', 'spec', 'ownership', 'rv'])(
+ 'rechecks identity and eligibility after Secret creation (%s)',
+ async change => {
+ const latest = server()
+ if (change === 'uid') latest.metadata.uid = 'replacement'
+ if (change === 'spec') latest.spec.egressBindings = []
+ if (change === 'ownership') latest.spec.managed = false
+ if (change === 'rv') delete latest.metadata.resourceVersion
+ vi.mocked(api.getMcpServer).mockResolvedValueOnce(server()).mockResolvedValueOnce(latest)
+ await expect(attachConnectorCredentials(request())).rejects.toThrow(
+ 'current settings could not be verified'
+ )
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ expect(api.deleteMcpSecret).toHaveBeenCalledOnce()
+ }
+ )
+ it('rejects ineligible or unidentified initial reads before any writes', async () => {
+ vi.mocked(api.getMcpServer).mockResolvedValue({ ...server(), metadata: {} })
+ await expect(attachConnectorCredentials(request())).rejects.toThrow('identity')
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ })
+ it('skips all Secret writes when existing values are blank', async () => {
+ await attachConnectorCredentials(
+ request({ mode: 'use-existing', selectedSecret: existing, rows: [{ ...row, value: '' }] })
+ )
+ expect(api.listMcpSecrets).toHaveBeenCalledOnce()
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpServer).toHaveBeenCalledOnce()
+ })
+ it('merges only filled keys before saving spec and returns other affected consumers', async () => {
+ const result = await attachConnectorCredentials(
+ request({ mode: 'use-existing', selectedSecret: existing })
+ )
+ expect(api.updateMcpSecret).toHaveBeenCalledWith('new-secret', { 'api-key': row.value })
+ expect(api.updateMcpSecret.mock.invocationCallOrder[0]).toBeLessThan(
+ api.updateMcpServer.mock.invocationCallOrder[0]
+ )
+ expect(result.affectedConnectors).toEqual(['other'])
+ })
+ it.each(['gone', 'key-gone', 'replaced'])(
+ 'stops before writes if selected Secret changed: %s',
+ async change => {
+ vi.mocked(api.listMcpSecrets).mockResolvedValue({
+ items:
+ change === 'gone'
+ ? []
+ : [
+ {
+ ...existing,
+ keys: change === 'key-gone' ? [] : existing.keys,
+ uid: change === 'replaced' ? 'replacement' : existing.uid,
+ },
+ ],
+ })
+ await expect(
+ attachConnectorCredentials(
+ request({ mode: 'use-existing', selectedSecret: existing, rows: [{ ...row, value: '' }] })
+ )
+ ).rejects.toThrow()
+ expect(api.updateMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ }
+ )
+ it('never creates on an existing Secret update 404', async () => {
+ vi.mocked(api.updateMcpSecret).mockRejectedValue(error(404))
+ await expect(
+ attachConnectorCredentials(request({ mode: 'use-existing', selectedSecret: existing }))
+ ).rejects.toThrow('no longer exists')
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ })
+ it('does not undo existing values when spec save fails', async () => {
+ vi.mocked(api.updateMcpServer).mockRejectedValue(error(409))
+ await expect(
+ attachConnectorCredentials(request({ mode: 'use-existing', selectedSecret: existing }))
+ ).rejects.toThrow('Secret values were updated')
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpSecret).toHaveBeenCalledOnce()
+ })
+})
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index f8ba5ee93..25f30e259 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -133,6 +133,7 @@ export type Metadata = {
* optimistic-concurrency precondition (docs/architecture/stateless-invariants.md).
*/
resourceVersion?: string
+ generation?: number
/** K8s-standard creation timestamp (RFC3339). Not in the type for older
* endpoints but carried by the new admin payloads. */
creationTimestamp?: string
@@ -669,13 +670,18 @@ export type GfsOperatorSubjectInput = { type: 'operator' }
export type GfsContextSubjectInput = { type: 'context'; id: string }
export type GfsBulkGrantSubjectInput =
- GfsUserSubjectInput | GfsTeamSubjectInput | GfsHostSubjectInput
+ | GfsUserSubjectInput
+ | GfsTeamSubjectInput
+ | GfsHostSubjectInput
export type GfsBulkShareSubjectInput = GfsUserSubjectInput | GfsTeamSubjectInput
export type GfsSubjectInput =
- GfsBulkGrantSubjectInput | GfsOperatorSubjectInput | GfsContextSubjectInput
+ | GfsBulkGrantSubjectInput
+ | GfsOperatorSubjectInput
+ | GfsContextSubjectInput
type GfsSubjectMutationInput<TBulkSubject extends GfsSubjectInput> =
- { subject: GfsSubjectInput; subjects?: never } | { subject?: never; subjects: TBulkSubject[] }
+ | { subject: GfsSubjectInput; subjects?: never }
+ | { subject?: never; subjects: TBulkSubject[] }
type GfsMutationRequestBody = {
drive?: string
@@ -1278,6 +1284,7 @@ export type HostResource = {
* Fase 3 requisito 6).
*/
export type McpServerCondition = {
+ observedGeneration?: number
type: string
status: 'True' | 'False' | 'Unknown'
reason: string
@@ -1827,7 +1834,11 @@ export async function createMcpServer(payload: {
/** Cleanup stages control-api reports as `pending` when an mcp-server uninstall stops. */
export type McpServerUninstallStage =
- 'contexts' | 'dynamic_client' | 'oauth_grants' | 'secrets' | 'mcp_server'
+ | 'contexts'
+ | 'dynamic_client'
+ | 'oauth_grants'
+ | 'secrets'
+ | 'mcp_server'
const MCP_SERVER_UNINSTALL_STAGE_LABELS: Record<McpServerUninstallStage, string> = {
contexts: 'agent access',
@@ -1915,7 +1926,10 @@ export async function getMcpServer(name: string) {
) as Promise<McpServerResource>
}
-export async function updateMcpServer(name: string, payload: { spec: Record<string, unknown> }) {
+export async function updateMcpServer(
+ name: string,
+ payload: { spec: Record<string, unknown>; metadata?: { uid?: string; resourceVersion?: string } }
+) {
return apiSend(
'PUT',
`/api/v1/admin/mcp-servers/${encodeURIComponent(name)}`,
@@ -1997,7 +2011,9 @@ export async function updateMcpSecret(name: string, data: Record<string, string>
}
export type RecipeSecretOwnership =
- { kind: 'shared' } | { kind: 'owner-recipe'; recipeName: string } | { kind: 'unlabeled' }
+ | { kind: 'shared' }
+ | { kind: 'owner-recipe'; recipeName: string }
+ | { kind: 'unlabeled' }
export type RecipeSecretItem = {
name: string
@@ -3004,7 +3020,13 @@ export type WorkflowRecipePhase =
| 'rollback-failed'
export type WorkflowExecutionPhase =
- 'pending' | 'initializing' | 'running' | 'completed' | 'failed' | 'cancelled' | 'recovering'
+ | 'pending'
+ | 'initializing'
+ | 'running'
+ | 'completed'
+ | 'failed'
+ | 'cancelled'
+ | 'recovering'
export type WorkflowRecipeStatus = {
phase?: WorkflowRecipePhase
@@ -3822,7 +3844,10 @@ export async function installRecipeFromRegistry(
// capability ceiling, and the may_deny ⇒ fail-closed rule; error bodies arrive as
// { error, reason? } (surfaced via the thrown Error's `.body`/`.code`).
export type HookCapability =
- 'may_deny' | 'may_rewrite' | 'may_substitute_result' | 'may_add_context'
+ | 'may_deny'
+ | 'may_rewrite'
+ | 'may_substitute_result'
+ | 'may_add_context'
export type InstallHookFromRegistryRequest = {
hostRef: string
@@ -4021,7 +4046,8 @@ export async function listOrgGrants(pluginName?: string): Promise<{ grants: OrgG
export async function createOrgGrant(input: CreateOrgGrantInput): Promise<OrgGrant> {
const raw = (await registryCodedRequest('POST', '/api/v1/admin/registry/grants', input)) as
- RawOrgGrant | undefined
+ | RawOrgGrant
+ | undefined
return normalizeOrgGrant(raw ?? {})
}
@@ -4339,7 +4365,12 @@ export type PluginWorkloadSdkQuotaCounter = {
}
export type PluginWorkloadSdkInvocationStatus =
- 'in_progress' | 'complete' | 'failed' | 'provider_unavailable' | 'accepted' | 'delivered'
+ | 'in_progress'
+ | 'complete'
+ | 'failed'
+ | 'provider_unavailable'
+ | 'accepted'
+ | 'delivered'
export type PluginWorkloadSdkInvocation = {
id: string
@@ -4560,7 +4591,12 @@ export async function listOrgImages(): Promise<{ org: string; images: OrgImage[]
// registry_signing_material_unavailable.
export type RegistryConnectionState =
- 'disconnected' | 'pending' | 'connecting' | 'approved' | 'rejected' | 'connected'
+ | 'disconnected'
+ | 'pending'
+ | 'connecting'
+ | 'approved'
+ | 'rejected'
+ | 'connected'
export type RegistryRecoveryError =
| 'already_claimed'
diff --git a/control-ui/lib/connectorCredentials.ts b/control-ui/lib/connectorCredentials.ts
new file mode 100644
index 000000000..5a7f86112
--- /dev/null
+++ b/control-ui/lib/connectorCredentials.ts
@@ -0,0 +1,317 @@
+import {
+ CLOCK_SKEW_TOLERANCE_MS,
+ CREDENTIAL_FORBIDDEN_ENV,
+ MCP_SECRET_NAME_PATTERN,
+} from '@constants/connectorCredentials'
+import {
+ createMcpSecret,
+ deleteMcpSecret,
+ getMcpSecretRollbackRepairIdentity,
+ getMcpServer,
+ listMcpSecrets,
+ updateMcpSecret,
+ updateMcpServer,
+} from '@lib/api'
+import type { McpServerResource, SecretIdentity } from '@lib/api'
+import type { McpSecretSummary } from '@lib/oauthInstall.types'
+import type {
+ AttachCredentialRow,
+ AttachCredentialsRequest,
+ AttachMode,
+ AttachPayload,
+ AttachValidation,
+ AttachedCredentials,
+} from './connectorCredentials.types'
+
+/** Structural eligibility, independent of potentially stale status conditions. */
+export function credentialAttachUnavailable(server: McpServerResource): string | undefined {
+ const spec = server.spec
+ if (!spec) return 'Connector settings are unavailable. Refresh before attaching credentials.'
+ if (Object.hasOwn(spec, 'envSecret'))
+ return 'This connector already has a Secret reference. Refresh to edit its credentials.'
+ if (Object.hasOwn(spec, 'oauth'))
+ return 'OAuth credentials must be managed through the OAuth configuration.'
+ if (spec.managed === false)
+ return "This connector's credentials are managed by its WorkflowRecipe. Add the Secret through the recipe's secrets."
+ if (spec.enabled === false)
+ return 'Enable this connector before attaching credentials and restarting it.'
+ return undefined
+}
+
+export function suggestedCredentialEnvVar(key: string): string {
+ const name = key.replace(/[^A-Za-z0-9_]/g, '_').toUpperCase()
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ? name : ''
+}
+
+export function validateCredentialAttach(
+ mode: AttachMode,
+ secretName: string,
+ rows: AttachCredentialRow[],
+ server: McpServerResource,
+ selected?: McpSecretSummary
+): AttachValidation | undefined {
+ if (!MCP_SECRET_NAME_PATTERN.test(secretName.trim()) || secretName.trim().length > 253) {
+ return {
+ message:
+ 'Enter a Secret name with lowercase letters, numbers, or hyphens, up to 253 characters.',
+ field: 'secret',
+ }
+ }
+ if (mode === 'use-existing' && (!selected || selected.name !== secretName.trim())) {
+ return { message: 'Select an existing Secret.', field: 'secret' }
+ }
+ if (!rows.length) return { message: 'Add at least one key mapping.' }
+ const destinations = new Set<string>()
+ const values = new Map<string, string>()
+ const plainEnv = Array.isArray(server.spec?.env) ? server.spec.env : []
+ const mapping = server.spec?.envMapping
+ const reserved = new Set([
+ ...plainEnv.map(item => (item as { name?: string })?.name),
+ ...(mapping && typeof mapping === 'object' ? Object.values(mapping) : []),
+ ])
+ for (const row of rows) {
+ const key = row.secretKey.trim()
+ const env = row.envVar.trim()
+ if (!/^[-._a-zA-Z0-9]+$/.test(key) || key.length > 253 || key === '.' || key.startsWith('..')) {
+ return {
+ message:
+ 'Enter a valid Secret key (letters, numbers, -, _, or .; not . or a .. prefix; up to 253 characters).',
+ field: `${row.id}-key`,
+ }
+ }
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(env) || CREDENTIAL_FORBIDDEN_ENV.has(env.toUpperCase())) {
+ return {
+ message:
+ 'Enter a valid environment variable name that does not control the container runtime.',
+ field: `${row.id}-env`,
+ }
+ }
+ if (destinations.has(env) || reserved.has(env)) {
+ return {
+ message: `Environment variable "${env}" is already mapped. Choose another name.`,
+ field: `${row.id}-env`,
+ }
+ }
+ destinations.add(env)
+ if ((mode === 'create-new' || !selected?.keys.includes(key)) && !row.value.trim()) {
+ return { message: `Enter a credential value for "${key}".`, field: `${row.id}-value` }
+ }
+ if (row.value !== '') {
+ if (values.has(key) && values.get(key) !== row.value) {
+ return {
+ message: `Enter the same value for each mapping of "${key}".`,
+ field: `${row.id}-value`,
+ }
+ }
+ values.set(key, row.value)
+ }
+ }
+}
+
+export function buildAttachPayload(secretName: string, rows: AttachCredentialRow[]): AttachPayload {
+ const data = Object.create(null) as Record<string, string>
+ for (const row of rows) if (row.value !== '') data[row.secretKey.trim()] = row.value
+ return {
+ data,
+ reference: {
+ name: secretName.trim(),
+ keys: rows.map(row => ({ secretKey: row.secretKey.trim(), envVar: row.envVar.trim() })),
+ },
+ }
+}
+
+/** Order-independent comparison for API JSON snapshots, including prototype-like keys. */
+export function sameCredentialSpec(left: unknown, right: unknown): boolean {
+ if (left === right) return true
+ if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object')
+ return false
+ if (Array.isArray(left) !== Array.isArray(right)) return false
+ const a = Object.keys(left)
+ const b = Object.keys(right)
+ return (
+ a.length === b.length &&
+ a.every(key => Object.hasOwn(right, key) && sameCredentialSpec(left[key], right[key]))
+ )
+}
+
+export class CredentialAttachError extends Error {
+ constructor(
+ message: string,
+ readonly refreshRequired = false,
+ readonly collision = false
+ ) {
+ super(message)
+ }
+}
+
+function httpStatus(error: unknown): number | undefined {
+ return error instanceof Error ? (error as Error & { status?: number }).status : undefined
+}
+
+function definiteRejection(error: unknown): boolean {
+ const status = httpStatus(error)
+ return status >= 400 && status < 500 && status !== 408
+}
+
+async function cleanupCreatedSecret(name: string, identity: SecretIdentity): Promise<string> {
+ try {
+ await deleteMcpSecret(name, { uid: identity.uid, resourceVersion: identity.resourceVersion })
+ return ''
+ } catch (error) {
+ if (httpStatus(error) === 404) return ''
+ return ` Cleanup of the created Secret "${name}" could not be confirmed. Refresh and review its references before taking further action.`
+ }
+}
+
+/** Values are never included in returned results or errors. No create→overwrite fallback. */
+export async function attachConnectorCredentials(
+ request: AttachCredentialsRequest
+): Promise<AttachedCredentials> {
+ const { serverName, mode, rows, selectedSecret, onSecretWritten } = request
+ const secretName = request.secretName.trim()
+ const initial = await getMcpServer(serverName)
+ if (request.expectedUid && initial.metadata?.uid !== request.expectedUid) {
+ throw new CredentialAttachError(
+ 'The connector was replaced. Refresh before attaching credentials.',
+ true
+ )
+ }
+ const unavailable = credentialAttachUnavailable(initial)
+ if (unavailable) throw new CredentialAttachError(unavailable, true)
+ if (!initial.metadata?.uid || !initial.metadata?.resourceVersion) {
+ throw new CredentialAttachError(
+ 'Connector identity is unavailable. Refresh before attaching.',
+ true
+ )
+ }
+ let selected = selectedSecret
+ if (mode === 'use-existing') {
+ const { items } = await listMcpSecrets()
+ selected = items.find(item => item.name === secretName)
+ if (!selected || (selectedSecret?.uid && selected.uid !== selectedSecret.uid)) {
+ throw new CredentialAttachError(
+ 'This Secret no longer exists or was replaced. Refresh and select it again.',
+ true
+ )
+ }
+ }
+ const invalid = validateCredentialAttach(mode, secretName, rows, initial, selected)
+ if (invalid) throw new CredentialAttachError(invalid.message)
+ const { reference, data } = buildAttachPayload(secretName, rows)
+ let createdIdentity: SecretIdentity | undefined
+ let patched = false
+ let affectedConnectors: string[] = []
+
+ if (mode === 'create-new') {
+ try {
+ const created = await createMcpSecret(secretName, data)
+ onSecretWritten()
+ if (!created.uid || !created.resourceVersion) {
+ throw new CredentialAttachError(
+ `Secret "${secretName}" was created without a complete identity. Refresh and review it before retrying.`,
+ true
+ )
+ }
+ createdIdentity = { uid: created.uid, resourceVersion: created.resourceVersion }
+ } catch (error) {
+ if (error instanceof CredentialAttachError) throw error
+ const repair = getMcpSecretRollbackRepairIdentity(error, secretName)
+ if (repair) {
+ onSecretWritten()
+ const cleanup = await cleanupCreatedSecret(secretName, repair)
+ throw new CredentialAttachError(
+ `Secret "${secretName}" was created but its creation could not be completed.${cleanup || ' The unused Secret was removed.'}`,
+ Boolean(cleanup)
+ )
+ }
+ if (httpStatus(error) === 409) {
+ throw new CredentialAttachError(
+ `Secret "${secretName}" already exists. Choose "Use an existing Secret" to attach it without overwriting credentials.`,
+ false,
+ true
+ )
+ }
+ throw new CredentialAttachError(
+ definiteRejection(error)
+ ? 'The Secret could not be created. Review its name and keys before retrying.'
+ : `Creation of Secret "${secretName}" could not be confirmed. Refresh and review it before retrying; no overwrite or unfenced cleanup was attempted.`,
+ !definiteRejection(error)
+ )
+ }
+ } else if (Object.keys(data).length) {
+ try {
+ const result = await updateMcpSecret(secretName, data)
+ patched = true
+ affectedConnectors = result.affectedConnectors
+ onSecretWritten()
+ } catch (error) {
+ throw new CredentialAttachError(
+ httpStatus(error) === 404
+ ? 'This Secret no longer exists. Refresh and select it again.'
+ : 'The Secret update could not be confirmed. Refresh and review it before retrying.',
+ true
+ )
+ }
+ }
+
+ // Until PUT is attempted, no connector reference can have been written by us.
+ let latest: McpServerResource
+ try {
+ latest = await getMcpServer(serverName)
+ if (
+ latest.metadata?.uid !== initial.metadata.uid ||
+ credentialAttachUnavailable(latest) ||
+ !sameCredentialSpec(initial.spec, latest.spec)
+ ) {
+ throw new CredentialAttachError(
+ 'The connector changed while credentials were being prepared. Refresh before continuing.',
+ true
+ )
+ }
+ if (!latest.metadata?.resourceVersion)
+ throw new CredentialAttachError(
+ 'Connector identity is unavailable. Refresh before continuing.',
+ true
+ )
+ } catch {
+ const cleanup = createdIdentity ? await cleanupCreatedSecret(secretName, createdIdentity) : ''
+ throw new CredentialAttachError(
+ `${patched ? 'Secret values were updated, but ' : ''}the connector could not be attached because its current settings could not be verified. Refresh before continuing.${cleanup}`,
+ true
+ )
+ }
+ const nextSpec = { ...latest.spec, envSecret: reference }
+ const cutoff = new Date(Date.now() - CLOCK_SKEW_TOLERANCE_MS).toISOString()
+ let saved: McpServerResource
+ try {
+ saved = await updateMcpServer(serverName, {
+ metadata: { uid: latest.metadata.uid, resourceVersion: latest.metadata.resourceVersion },
+ spec: nextSpec,
+ })
+ } catch (error) {
+ if (definiteRejection(error)) {
+ const cleanup = createdIdentity ? await cleanupCreatedSecret(secretName, createdIdentity) : ''
+ throw new CredentialAttachError(
+ `${patched ? 'Secret values were updated, but the connector could not be attached.' : 'The connector could not be attached.'} ${httpStatus(error) === 409 ? 'Its settings changed; refresh before continuing.' : 'The spec save was rejected; refresh and review its settings.'}${cleanup}`,
+ true
+ )
+ }
+ // A failed response is not proof the PUT failed. Keep the Secret unless the
+ // write was definitely rejected, even if a read currently sees the old spec.
+ try {
+ saved = await getMcpServer(serverName)
+ } catch {
+ throw new CredentialAttachError(
+ 'The attachment outcome could not be confirmed. Refresh to check the connector. The Secret was retained.',
+ true
+ )
+ }
+ if (saved.metadata?.uid !== initial.metadata.uid || !sameCredentialSpec(saved.spec, nextSpec)) {
+ throw new CredentialAttachError(
+ 'The attachment outcome could not be confirmed. Refresh to check the connector. The Secret was retained.',
+ true
+ )
+ }
+ }
+ return { server: saved, cutoff, affectedConnectors }
+}
diff --git a/control-ui/lib/connectorCredentials.types.ts b/control-ui/lib/connectorCredentials.types.ts
new file mode 100644
index 000000000..ab9aaf67a
--- /dev/null
+++ b/control-ui/lib/connectorCredentials.types.ts
@@ -0,0 +1,37 @@
+import type { EnvSecret, McpServerResource } from '@lib/api'
+import type { McpSecretSummary } from '@lib/oauthInstall.types'
+
+export type AttachMode = 'create-new' | 'use-existing'
+
+export type AttachCredentialRow = {
+ id: string
+ secretKey: string
+ envVar: string
+ value: string
+}
+
+export type AttachValidation = {
+ message: string
+ field?: string
+}
+
+export type AttachCredentialsRequest = {
+ serverName: string
+ expectedUid?: string
+ mode: AttachMode
+ secretName: string
+ rows: AttachCredentialRow[]
+ selectedSecret?: McpSecretSummary
+ onSecretWritten: () => void
+}
+
+export type AttachedCredentials = {
+ server: McpServerResource
+ cutoff: string
+ affectedConnectors: string[]
+}
+
+export type AttachPayload = {
+ reference: EnvSecret
+ data: Record<string, string>
+}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index d03913f1a..e641cf936 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.748",
+ "version": "0.1.749",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.748",
+ "version": "0.1.749",
"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 f482cdb9b..ddf3215e6 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.748",
+ "version": "0.1.749",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/control-ui/tsconfig.json b/control-ui/tsconfig.json
index 714dc7463..09d7849b3 100644
--- a/control-ui/tsconfig.json
+++ b/control-ui/tsconfig.json
@@ -11,6 +11,7 @@
"module": "esnext",
"esModuleInterop": true,
"moduleResolution": "bundler",
+ "preserveSymlinks": true,
"paths": {
"@/*": ["./*"],
"@components/*": ["./components/*"],