Skip to content

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

TypeScript

feat(control-ui): reuse an existing Secret during connector creation

Mbb03b1e0a514
diff --git a/control-ui/components/CreateMcpServerForm/index.tsx b/control-ui/components/CreateMcpServerForm/index.tsx
index 419ce0dc1..ad05c3a8d 100644
--- a/control-ui/components/CreateMcpServerForm/index.tsx
+++ b/control-ui/components/CreateMcpServerForm/index.tsx
@@ -1,6 +1,13 @@
'use client'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { ExistingConnectorSecretFields } from '@components/ExistingConnectorSecretFields'
+import {
+ buildAttachPayload,
+ validateCredentialAttach,
+ verifyExistingCredentialSelection,
+} from '@lib/connectorCredentials'
+import type { ExistingCredentialSelection } from '@lib/connectorCredentials.types'
import { CreateFlowPanel } from '@/components/CreateFlowPanel'
import { CreateStepFlow } from '@/components/CreateStepFlow'
import { SelectionDropdown } from '@/components/SelectionDropdown'
@@ -224,7 +231,11 @@ export function CreateMcpServerForm({
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState('')
const [envVars, setEnvVars] = useState<EnvVar[]>([])
- const [credentialMode, setCredentialMode] = useState<'secret' | 'none' | null>(null)
+ const [credentialMode, setCredentialMode] = useState<'secret' | 'existing' | 'none' | null>(null)
+ const [existingSelection, setExistingSelection] = useState<ExistingCredentialSelection>({
+ rows: [],
+ ready: false,
+ })
const [envSecretName, setEnvSecretName] = useState('')
const [envSecretKeys, setEnvSecretKeys] = useState<EnvSecretKeyMapping[]>([])
const [secretValues, setSecretValues] = useState<string[]>([])
@@ -243,8 +254,21 @@ export function CreateMcpServerForm({
const values = [row.secretKey.trim(), row.envVar.trim(), (secretValues[index] ?? '').trim()]
return values.some(Boolean) && !values.every(Boolean)
})
+ const existingServer = useMemo(() => ({ spec: { env: envVars } }), [envVars])
+ const existingValid =
+ existingSelection.ready &&
+ Boolean(existingSelection.secret) &&
+ !validateCredentialAttach(
+ 'use-existing',
+ existingSelection.secret?.name ?? '',
+ existingSelection.rows,
+ existingServer,
+ existingSelection.secret,
+ { storedKeysOnly: true }
+ )
const credentialsConfigured =
credentialMode === 'none' ||
+ (credentialMode === 'existing' && existingValid) ||
(credentialMode === 'secret' &&
Boolean(envSecretName.trim()) &&
hasCompleteSecretMapping &&
@@ -464,13 +488,7 @@ export function CreateMcpServerForm({
}
if (!canSubmit) return
- // ── Client-side envSecret validation (PR-A / A2) ─────────────────────────
- // If the operator chose a Secret, they must provide
- // at least one key-value pair so we actually create the Secret in-band.
- // Referencing a pre-existing Secret from this form is not supported here:
- // it's the exact "Secret missing → HCC silent hang" class we're closing.
- // Operators who need to reference an existing Secret should manage it via
- // kubectl or the API directly.
+ // New Secrets require values; existing references use metadata-only validation.
if (useEnvSecret && envSecretName.trim()) {
const builtSecretData: Record<string, string> = {}
envSecretKeys.forEach((row, index) => {
@@ -494,6 +512,24 @@ export function CreateMcpServerForm({
setSubmitting(true)
setError('')
+ if (credentialMode === 'existing') {
+ try {
+ await verifyExistingCredentialSelection(
+ existingSelection.secret?.name ?? '',
+ existingSelection.rows,
+ existingSelection.secret,
+ existingServer
+ )
+ } catch {
+ setError(
+ 'The selected Secret or its keys could not be verified. Refresh Secrets and review the selection before creating the connector.'
+ )
+ setExistingSelection(current => ({ ...current, ready: false }))
+ setSubmitting(false)
+ return
+ }
+ }
+
// Resolve the write targets: the distinct private scopes of the selected
// agents. With no selection the connector gets its own private scope (an
// implementation detail, same as Marketplace installs) so the resource
@@ -552,6 +588,13 @@ export function CreateMcpServerForm({
}
}
+ if (credentialMode === 'existing') {
+ spec.envSecret = buildAttachPayload(
+ existingSelection.secret!.name,
+ existingSelection.rows
+ ).reference
+ }
+
const parsedCommand = parseCommaSeparated(command)
if (parsedCommand.length > 0) {
spec.command = parsedCommand
@@ -686,7 +729,7 @@ export function CreateMcpServerForm({
let cleanupError: unknown
let cleanupSecretName = createdSecretName
let cleanupSecretIdentity = createdSecretIdentity
- if (!cleanupSecretName) {
+ if (!cleanupSecretName && willCreateSecret) {
const repairIdentity = getMcpSecretRollbackRepairIdentity(submitError, envSecretName.trim())
if (repairIdentity) {
cleanupSecretName = repairIdentity.name
@@ -1068,6 +1111,21 @@ export function CreateMcpServerForm({
</span>
</span>
</label>
+ <label className="cu-agent-radio cu-agent-radio--card">
+ <input
+ name="credential-mode"
+ type="radio"
+ checked={credentialMode === 'existing'}
+ disabled={submitting}
+ onChange={() => setCredentialMode('existing')}
+ />
+ <span className="cu-agent-radio__copy">
+ <span className="cu-agent-radio__title">Use an existing Secret</span>
+ <span className="cu-agent-radio__description">
+ Reuse stored credentials from Secrets → Connectors and map their keys.
+ </span>
+ </span>
+ </label>
<label className="cu-agent-radio cu-agent-radio--card">
<input
name="credential-mode"
@@ -1092,19 +1150,29 @@ export function CreateMcpServerForm({
</p>
) : null}
+ {credentialMode === 'existing' ? (
+ <ExistingConnectorSecretFields
+ server={existingServer}
+ disabled={submitting}
+ onChange={setExistingSelection}
+ />
+ ) : null}
+
{useEnvSecret ? (
<>
<Field
description={
<>
- Name for the new Secret in the <code>mcp-server</code> namespace that will
- contain these credentials.
+ Name for the new Secret. Choose “Use an existing Secret” to reuse stored
+ credentials.
</>
}
label="Kubernetes Secret Name"
+ htmlFor="connector-new-secret-name"
>
<TextInput
monospace
+ id="connector-new-secret-name"
onChange={event => setEnvSecretName(event.target.value)}
placeholder="brave-search-credentials"
disabled={submitting}
@@ -1159,10 +1227,9 @@ export function CreateMcpServerForm({
</Button>
<p className="cu-form-section__description">
- Enter each secret value here to create a Kubernetes Opaque Secret in the{' '}
- <code>mcp-server</code> namespace. All values are required — the form creates
- the Secret in-band before the connector resource to avoid a missing-Secret
- reconcile hang.
+ Enter each value to create a reusable Secret before the connector. To use
+ credentials already stored in Secrets → Connectors, choose “Use an existing
+ Secret”.
</p>
</>
) : null}
@@ -1170,7 +1237,11 @@ export function CreateMcpServerForm({
</div>
) : null}
- {error ? <div className="cu-banner cu-banner--error">{error}</div> : null}
+ {error ? (
+ <div role="alert" className="cu-banner cu-banner--error">
+ {error}
+ </div>
+ ) : null}
<div className={mode === 'page' ? 'cu-create-actions' : 'cu-modal-panel__foot'}>
<Button
diff --git a/control-ui/components/ExistingConnectorSecretFields/index.tsx b/control-ui/components/ExistingConnectorSecretFields/index.tsx
new file mode 100644
index 000000000..80cf9ccb5
--- /dev/null
+++ b/control-ui/components/ExistingConnectorSecretFields/index.tsx
@@ -0,0 +1,195 @@
+'use client'
+
+import { useEffect, useId, useRef, useState } from 'react'
+import Link from 'next/link'
+import { Button, Field, SelectInput, TextInput } from '@components/ui'
+import { CONTROL_ROUTES } from '@constants/routes'
+import { listMcpSecrets } from '@lib/api'
+import { suggestedCredentialEnvVar, validateCredentialAttach } from '@lib/connectorCredentials'
+import type { AttachCredentialRow } from '@lib/connectorCredentials.types'
+import type { McpSecretSummary } from '@lib/oauthInstall.types'
+import type { ExistingConnectorSecretFieldsProps } from './types'
+
+export function ExistingConnectorSecretFields({
+ server,
+ initialReference,
+ disabled = false,
+ onChange,
+}: ExistingConnectorSecretFieldsProps) {
+ const prefix = useId()
+ const counter = useRef(0)
+ const [secrets, setSecrets] = useState<McpSecretSummary[]>([])
+ const [name, setName] = useState('')
+ const [rows, setRows] = useState<AttachCredentialRow[]>([])
+ const [state, setState] = useState<'loading' | 'error' | 'ready'>('loading')
+ const [refresh, setRefresh] = useState(0)
+ const callback = useRef(onChange)
+ callback.current = onChange
+ const selected = secrets.find(secret => secret.name === name)
+ const invalid = name
+ ? validateCredentialAttach('use-existing', name, rows, server, selected, {
+ storedKeysOnly: true,
+ })
+ : undefined
+ const errorId = `${prefix}-validation`
+
+ useEffect(() => {
+ let cancelled = false
+ setState('loading')
+ void listMcpSecrets()
+ .then(({ items }) => {
+ if (cancelled) return
+ setSecrets([...items].sort((a, b) => a.name.localeCompare(b.name)))
+ setState('ready')
+ })
+ .catch(() => {
+ if (!cancelled) setState('error')
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [refresh])
+
+ useEffect(() => {
+ callback.current({ secret: selected, rows, ready: state === 'ready' })
+ }, [selected, rows, state])
+
+ function newRow(
+ secretKey: string,
+ envVar = suggestedCredentialEnvVar(secretKey)
+ ): AttachCredentialRow {
+ return { id: `${prefix}-${counter.current++}`, secretKey, envVar, value: '' }
+ }
+
+ function selectSecret(nextName: string) {
+ setName(nextName)
+ const keys = secrets.find(secret => secret.name === nextName)?.keys ?? []
+ // Existing destinations are the connector's contract. A missing source key
+ // needs an explicit choice; never silently replace or drop its destination.
+ setRows(
+ initialReference?.keys.length
+ ? initialReference.keys.map(mapping =>
+ newRow(keys.includes(mapping.secretKey) ? mapping.secretKey : '', mapping.envVar)
+ )
+ : keys.map(key => newRow(key))
+ )
+ }
+
+ function feedback(field: string) {
+ const isInvalid = invalid?.field === field
+ return {
+ 'aria-invalid': isInvalid || undefined,
+ 'aria-describedby': isInvalid ? errorId : undefined,
+ }
+ }
+
+ return (
+ <fieldset className="cu-form-section__group" disabled={disabled}>
+ <legend className="cu-form-section__subheading">Existing Secret and key mappings</legend>
+ <p className="cu-muted">
+ Reuse a Secret from Secrets → Connectors. Stored values stay unchanged and are never shown.
+ </p>
+ <Field label="Existing Secret" htmlFor={`${prefix}-secret`} required>
+ <SelectInput
+ id={`${prefix}-secret`}
+ value={name}
+ disabled={state !== 'ready'}
+ onChange={event => selectSecret(event.target.value)}
+ >
+ <option value="">Choose a Secret</option>
+ {secrets.map(secret => (
+ <option key={secret.name} value={secret.name}>
+ {secret.name}
+ </option>
+ ))}
+ </SelectInput>
+ </Field>
+ {state === 'loading' ? <p role="status">Loading Secrets…</p> : null}
+ {state === 'error' ? (
+ <div role="alert">
+ Could not load Secrets.{' '}
+ <Button onClick={() => setRefresh(value => value + 1)}>Retry loading Secrets</Button>
+ </div>
+ ) : null}
+ {state === 'ready' && !secrets.length ? (
+ <p role="status">
+ No connector Secrets are available. Create one in Secrets → Connectors, then refresh this
+ list.
+ </p>
+ ) : null}
+ <div className="cu-create-actions">
+ <Button onClick={() => setRefresh(value => value + 1)} disabled={state === 'loading'}>
+ Refresh Secrets
+ </Button>
+ <Link href={CONTROL_ROUTES.secrets.connector} target="_blank" rel="noopener noreferrer">
+ Manage connector Secrets (opens in a new tab)
+ </Link>
+ </div>
+ {selected && !selected.keys.length ? (
+ <p role="alert">
+ This Secret has no stored keys. Add keys in Secrets → Connectors, then refresh.
+ </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={`${row.id}-key`} required>
+ <SelectInput
+ id={`${row.id}-key`}
+ value={row.secretKey}
+ onChange={event =>
+ setRows(current =>
+ current.map(item =>
+ item.id === row.id ? { ...item, secretKey: event.target.value } : item
+ )
+ )
+ }
+ {...feedback(`${row.id}-key`)}
+ >
+ <option value="">Choose a stored key</option>
+ {selected?.keys.map(key => (
+ <option key={key} value={key}>
+ {key}
+ </option>
+ ))}
+ </SelectInput>
+ </Field>
+ <Field label={`Environment variable ${index + 1}`} htmlFor={`${row.id}-env`} required>
+ <TextInput
+ id={`${row.id}-env`}
+ monospace
+ value={row.envVar}
+ onChange={event =>
+ setRows(current =>
+ current.map(item =>
+ item.id === row.id ? { ...item, envVar: event.target.value } : item
+ )
+ )
+ }
+ {...feedback(`${row.id}-env`)}
+ />
+ </Field>
+ </div>
+ <Button
+ variant="ghost-danger"
+ onClick={() => setRows(current => current.filter(item => item.id !== row.id))}
+ aria-label={`Remove mapping ${index + 1}`}
+ >
+ Remove mapping
+ </Button>
+ </fieldset>
+ ))}
+ {selected?.keys.length ? (
+ <Button onClick={() => setRows(current => [...current, newRow('')])}>
+ Add key mapping
+ </Button>
+ ) : null}
+ {invalid ? (
+ <p id={errorId} className="cu-banner cu-banner--error" role="alert">
+ {invalid.message}
+ </p>
+ ) : null}
+ </fieldset>
+ )
+}
diff --git a/control-ui/components/ExistingConnectorSecretFields/types.ts b/control-ui/components/ExistingConnectorSecretFields/types.ts
new file mode 100644
index 000000000..42d9766ed
--- /dev/null
+++ b/control-ui/components/ExistingConnectorSecretFields/types.ts
@@ -0,0 +1,9 @@
+import type { EnvSecret, McpServerResource } from '@lib/api'
+import type { ExistingCredentialSelection } from '@lib/connectorCredentials.types'
+
+export type ExistingConnectorSecretFieldsProps = {
+ server: McpServerResource
+ initialReference?: EnvSecret
+ disabled?: boolean
+ onChange: (selection: ExistingCredentialSelection) => void
+}
diff --git a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx b/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
index 149df5f73..b9b96eba1 100644
--- a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
+++ b/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
@@ -24,6 +24,9 @@ vi.mock('../../lib/api', async importOriginal => {
...actual,
apiSend: vi.fn().mockResolvedValue({}),
createMcpServer: vi.fn().mockResolvedValue({ metadata: { name: 'test-server' } }),
+ listMcpSecrets: vi.fn().mockResolvedValue({
+ items: [{ name: 'shared-credentials', uid: 'shared-uid', keys: ['api-key'] }],
+ }),
createMcpSecret: vi.fn().mockResolvedValue({
name: 'test-credentials',
namespace: 'mcp-server',
@@ -962,3 +965,65 @@ describe('CreateMcpServerForm — envSecret guardrails', () => {
expect(screen.getByText('Connector created successfully.')).toBeInTheDocument()
})
})
+
+describe('CreateMcpServerForm — reusable Secrets', () => {
+ async function prepareExisting() {
+ render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={vi.fn()} />)
+ await fillIdentity()
+ continueToSecrets()
+ fireEvent.click(screen.getByRole('radio', { name: /Use an existing Secret/ }))
+ await waitFor(() => expect(screen.getByLabelText(/^Existing Secret/)).toBeEnabled())
+ fireEvent.change(screen.getByLabelText(/^Existing Secret/), {
+ target: { value: 'shared-credentials' },
+ })
+ }
+ it('creates a connector referencing stored keys without requesting or writing values', async () => {
+ await prepareExisting()
+ expect(screen.queryByPlaceholderText('sk-...')).not.toBeInTheDocument()
+ expect(screen.getByLabelText(/^Environment variable 1/)).toHaveValue('API_KEY')
+ fireEvent.click(screen.getByRole('button', { name: 'Create connector' }))
+ await waitFor(() => expect(api.createMcpServer).toHaveBeenCalledOnce())
+ expect(api.createMcpServer).toHaveBeenCalledWith(
+ expect.objectContaining({
+ spec: expect.objectContaining({
+ envSecret: {
+ name: 'shared-credentials',
+ keys: [{ secretKey: 'api-key', envVar: 'API_KEY' }],
+ },
+ }),
+ })
+ )
+ expect(api.listMcpSecrets).toHaveBeenCalledTimes(2)
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('keeps a shared Secret when connector creation fails', async () => {
+ vi.mocked(api.createMcpServer).mockRejectedValueOnce(new Error('connector rejected'))
+ await prepareExisting()
+ fireEvent.click(screen.getByRole('button', { name: 'Create connector' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('connector rejected')
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('checks the selected Secret identity before creating an access scope or connector', async () => {
+ await prepareExisting()
+ vi.mocked(api.listMcpSecrets).mockResolvedValueOnce({
+ items: [{ name: 'shared-credentials', uid: 'replaced-uid', keys: ['api-key'] }],
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Create connector' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('could not be verified')
+ expect(api.apiSend).not.toHaveBeenCalled()
+ expect(api.createMcpServer).not.toHaveBeenCalled()
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ expect(screen.getByRole('button', { name: 'Create connector' })).toBeDisabled()
+ })
+ it('blocks invalid and colliding environment destinations', async () => {
+ await prepareExisting()
+ fireEvent.change(screen.getByLabelText(/^Environment variable 1/), {
+ target: { value: 'NODE_OPTIONS' },
+ })
+ expect(screen.getByRole('button', { name: 'Create connector' })).toBeDisabled()
+ expect(screen.getByRole('alert')).toHaveTextContent('runtime')
+ })
+})
diff --git a/control-ui/components/__tests__/ExistingConnectorSecretFields.test.tsx b/control-ui/components/__tests__/ExistingConnectorSecretFields.test.tsx
new file mode 100644
index 000000000..e1653c2a5
--- /dev/null
+++ b/control-ui/components/__tests__/ExistingConnectorSecretFields.test.tsx
@@ -0,0 +1,199 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { ExistingConnectorSecretFields } from '@components/ExistingConnectorSecretFields'
+import { listMcpSecrets } from '@lib/api'
+import type { McpServerResource } from '@lib/api'
+import type { ExistingCredentialSelection } from '@lib/connectorCredentials.types'
+
+vi.mock('@lib/api', () => ({
+ listMcpSecrets: vi.fn(),
+}))
+
+const mockListMcpSecrets = vi.mocked(listMcpSecrets)
+
+const SERVER: McpServerResource = {
+ metadata: { name: 'connector' },
+ spec: { image: 'example/image:v1' },
+}
+
+/** The connector's current reference used by the reassignment flow. */
+const INITIAL_REFERENCE = {
+ name: 'old-secret',
+ keys: [
+ { secretKey: 'api-key', envVar: 'LINEAR_API_KEY' },
+ { secretKey: 'workspace-id', envVar: 'LINEAR_WORKSPACE' },
+ ],
+}
+
+const SECRET_A = { name: 'alpha-credentials', uid: 'uid-a', keys: ['api-key'] }
+const SECRET_B = { name: 'beta-credentials', uid: 'uid-b', keys: ['beta-token'] }
+
+function renderFields(props: Partial<Parameters<typeof ExistingConnectorSecretFields>[0]> = {}) {
+ const onChange = vi.fn()
+ const utils = render(
+ <ExistingConnectorSecretFields server={SERVER} onChange={onChange} {...props} />
+ )
+ return { onChange, ...utils }
+}
+
+/** The latest onChange payload, so tests can assert the reported selection. */
+function lastSelection(onChange: ReturnType<typeof vi.fn>): ExistingCredentialSelection {
+ return onChange.mock.calls.at(-1)?.[0] as ExistingCredentialSelection
+}
+
+beforeEach(() => {
+ mockListMcpSecrets.mockResolvedValue({ items: [SECRET_B, SECRET_A] })
+})
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+
+describe('ExistingConnectorSecretFields — metadata loading', () => {
+ it('reports not-ready while loading, then enables the selector', async () => {
+ let resolveList: ((value: { items: (typeof SECRET_A)[] }) => void) | undefined
+ mockListMcpSecrets.mockReturnValue(
+ new Promise(resolve => {
+ resolveList = resolve
+ })
+ )
+ const { onChange } = renderFields()
+
+ expect(screen.getByRole('status')).toHaveTextContent('Loading Secrets…')
+ expect(screen.getByLabelText(/^Existing Secret/)).toBeDisabled()
+ expect(lastSelection(onChange).ready).toBe(false)
+
+ resolveList?.({ items: [SECRET_A] })
+ await waitFor(() => expect(screen.getByLabelText(/^Existing Secret/)).toBeEnabled())
+ expect(lastSelection(onChange).ready).toBe(true)
+ })
+
+ it('offers retry after a listing failure and recovers without losing the alert', async () => {
+ mockListMcpSecrets.mockRejectedValueOnce(new Error('boom'))
+ renderFields()
+
+ const alert = await screen.findByRole('alert')
+ expect(alert).toHaveTextContent('Could not load Secrets')
+ // No metadata is available, so nothing can be selected yet.
+ expect(screen.getByLabelText(/^Existing Secret/)).toBeDisabled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Retry loading Secrets' }))
+ await waitFor(() => expect(screen.getByLabelText(/^Existing Secret/)).toBeEnabled())
+ expect(mockListMcpSecrets).toHaveBeenCalledTimes(2)
+ })
+
+ it('explains an empty Secret list instead of rendering a bare selector', async () => {
+ mockListMcpSecrets.mockResolvedValue({ items: [] })
+ renderFields()
+
+ expect(await screen.findByText(/No connector Secrets are available/)).toBeInTheDocument()
+ // The list is loaded (not stuck in a loading/error state); it is simply empty.
+ expect(screen.getByLabelText(/^Existing Secret/)).toBeEnabled()
+ })
+
+ it('reloads metadata on demand through the explicit refresh control', async () => {
+ renderFields()
+ await waitFor(() => expect(screen.getByLabelText(/^Existing Secret/)).toBeEnabled())
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh Secrets' }))
+ await waitFor(() => expect(mockListMcpSecrets).toHaveBeenCalledTimes(2))
+ })
+})
+
+describe('ExistingConnectorSecretFields — reference-only key mapping', () => {
+ it('auto-maps stored keys to environment variables and never renders a value input', async () => {
+ const { onChange } = renderFields()
+ fireEvent.change(await screen.findByLabelText(/^Existing Secret/), {
+ target: { value: SECRET_A.name },
+ })
+
+ expect(screen.getByLabelText(/^Environment variable 1/)).toHaveValue('API_KEY')
+ // Write-only contract: no credential value is ever requested or rendered.
+ expect(document.querySelectorAll('input[type="password"]')).toHaveLength(0)
+ expect(screen.queryByText(/Credential value/i)).not.toBeInTheDocument()
+ const selection = lastSelection(onChange)
+ expect(selection.secret).toEqual(SECRET_A)
+ expect(selection.rows).toEqual([
+ expect.objectContaining({ secretKey: 'api-key', envVar: 'API_KEY', value: '' }),
+ ])
+ })
+
+ it('preserves each destination and demands an explicit key when the new Secret lacks it', async () => {
+ const { onChange } = renderFields({ initialReference: INITIAL_REFERENCE })
+ fireEvent.change(await screen.findByLabelText(/^Existing Secret/), {
+ target: { value: SECRET_B.name },
+ })
+
+ // Destination names are the connector's contract: both survive the switch,
+ // and the missing source key is an explicit choice, never a value prompt.
+ expect(screen.getByLabelText(/^Environment variable 1/)).toHaveValue('LINEAR_API_KEY')
+ expect(screen.getByLabelText(/^Environment variable 2/)).toHaveValue('LINEAR_WORKSPACE')
+ expect(screen.getByLabelText(/^Secret key 1/)).toHaveValue('')
+ expect(screen.getByLabelText(/^Secret key 2/)).toHaveValue('')
+ expect(screen.getByRole('alert')).toHaveTextContent('Choose a stored key')
+ expect(screen.getByRole('alert').textContent?.toLowerCase()).not.toContain(
+ 'enter a credential value'
+ )
+ const selection = lastSelection(onChange)
+ expect(selection.rows.map(row => row.envVar)).toEqual(['LINEAR_API_KEY', 'LINEAR_WORKSPACE'])
+ expect(
+ selection.rows.every(row => row.secretKey === '' || SECRET_B.keys.includes(row.secretKey))
+ ).toBe(true)
+ })
+
+ it('clears the key error once an explicit stored key is chosen and keeps the destination', async () => {
+ const singleKeyReference = { name: 'old-secret', keys: [INITIAL_REFERENCE.keys[0]] }
+ renderFields({ initialReference: singleKeyReference })
+ fireEvent.change(await screen.findByLabelText(/^Existing Secret/), {
+ target: { value: SECRET_B.name },
+ })
+ expect(screen.getByRole('alert')).toHaveTextContent('Choose a stored key')
+
+ fireEvent.change(screen.getByLabelText(/^Secret key 1/), {
+ target: { value: 'beta-token' },
+ })
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ expect(screen.getByLabelText(/^Environment variable 1/)).toHaveValue('LINEAR_API_KEY')
+ })
+
+ it('flags a key that vanished from the selected Secret as a key problem after a refresh', async () => {
+ const { onChange } = renderFields()
+ fireEvent.change(await screen.findByLabelText(/^Existing Secret/), {
+ target: { value: SECRET_A.name },
+ })
+ expect(lastSelection(onChange).rows[0]?.secretKey).toBe('api-key')
+
+ // Out-of-band: the stored key disappeared, then the operator refreshes.
+ mockListMcpSecrets.mockResolvedValue({
+ items: [{ ...SECRET_A, keys: ['replacement-key'] }],
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh Secrets' }))
+ await waitFor(() =>
+ expect(screen.getByRole('alert')).toHaveTextContent('not stored in the selected Secret')
+ )
+ // The stale choice is reported where it was made — the key select — and the
+ // message never asks the operator to re-enter a credential value.
+ expect(screen.getByLabelText(/^Secret key 1/)).toHaveAttribute('aria-invalid', 'true')
+ expect(screen.getByRole('alert').textContent?.toLowerCase()).not.toContain(
+ 'enter a credential value'
+ )
+ })
+
+ it('keeps the empty-Secret guidance discoverable when the selected Secret stores no keys', async () => {
+ mockListMcpSecrets.mockResolvedValue({
+ items: [{ name: 'hollow-credentials', uid: 'uid-hollow', keys: [] }],
+ })
+ renderFields()
+ fireEvent.change(await screen.findByLabelText(/^Existing Secret/), {
+ target: { value: 'hollow-credentials' },
+ })
+
+ expect(
+ screen
+ .getAllByRole('alert')
+ .map(alert => alert.textContent)
+ .join(' ')
+ ).toContain('This Secret has no stored keys')
+ expect(screen.queryByRole('button', { name: 'Add key mapping' })).not.toBeInTheDocument()
+ })
+})
diff --git a/control-ui/lib/__tests__/connectorCredentials.test.ts b/control-ui/lib/__tests__/connectorCredentials.test.ts
index 22e39422a..55981a4e3 100644
--- a/control-ui/lib/__tests__/connectorCredentials.test.ts
+++ b/control-ui/lib/__tests__/connectorCredentials.test.ts
@@ -4,6 +4,7 @@ import type { McpServerResource } from '@lib/api'
import {
attachConnectorCredentials,
buildAttachPayload,
+ changeConnectorSecretReference,
credentialAttachUnavailable,
validateCredentialAttach,
} from '@lib/connectorCredentials'
@@ -154,6 +155,78 @@ describe('attach validation', () => {
})
})
+// Reference-only reuse (creation + reassignment) must answer a missing or
+// stale key with a KEY selection error and must never request a credential
+// value — unlike the keyless-attach flow, which may still write new keys.
+describe('reference-only validation with storedKeysOnly', () => {
+ const selected = { name: 'new-secret', uid: 'secret-uid', keys: ['api-key', 'other-key'] }
+ const options = { storedKeysOnly: true } as const
+
+ it('reports an empty key as a key choice, not a format or value error', () => {
+ const invalid = validateCredentialAttach(
+ 'use-existing',
+ 'new-secret',
+ [{ ...row, secretKey: '' }],
+ server(),
+ selected,
+ options
+ )
+ expect(invalid?.field).toBe('row-key')
+ expect(invalid?.message).toContain('Choose a stored key')
+ })
+
+ it('reports a stale key as a key selection error and never asks for a value', () => {
+ const invalid = validateCredentialAttach(
+ 'use-existing',
+ 'new-secret',
+ [{ ...row, secretKey: 'removed-key' }],
+ server(),
+ selected,
+ options
+ )
+ expect(invalid?.field).toBe('row-key')
+ expect(invalid?.message).toContain('not stored')
+ expect(invalid?.message.toLowerCase()).not.toContain('enter a credential value')
+ })
+
+ it('rejects a supplied value even for a stored key', () => {
+ const invalid = validateCredentialAttach(
+ 'use-existing',
+ 'new-secret',
+ [row],
+ server(),
+ selected,
+ options
+ )
+ expect(invalid?.field).toBe('row-value')
+ expect(invalid?.message).toContain('never take a value')
+ })
+
+ it('accepts a stored key mapped without a value and keeps destination checks', () => {
+ const stored: AttachCredentialRow = { ...row, value: '' }
+ expect(
+ validateCredentialAttach('use-existing', 'new-secret', [stored], server(), selected, options)
+ ).toBeUndefined()
+ const colliding = server()
+ colliding.spec.env = [{ name: 'API_KEY', value: 'plain' }]
+ expect(
+ validateCredentialAttach('use-existing', 'new-secret', [stored], colliding, selected, options)
+ ?.field
+ ).toBe('row-env')
+ })
+
+ it('keeps the keyless-attach behavior when the option is absent: a missing stored key requires a value', () => {
+ const invalid = validateCredentialAttach(
+ 'use-existing',
+ 'new-secret',
+ [{ ...row, secretKey: 'new-key', value: '' }],
+ server(),
+ selected
+ )
+ expect(invalid?.field).toBe('row-value')
+ })
+})
+
describe('ordered attach writes and recovery', () => {
it('refuses a same-name replacement since the page loaded before touching any Secret', async () => {
await expect(
@@ -382,3 +455,126 @@ describe('ordered attach writes and recovery', () => {
expect(api.updateMcpSecret).toHaveBeenCalledOnce()
})
})
+
+describe('reference-only Secret reassignment', () => {
+ const oldReference = { name: 'old-secret', keys: [{ secretKey: 'old-token', envVar: 'API_KEY' }] }
+ function assignedServer() {
+ const current = server()
+ current.spec.envSecret = oldReference
+ current.spec.contextRef = 'private-context'
+ current.spec.remote = {
+ authType: 'bearer',
+ authHeaders: [{ name: 'Authorization', valueTemplate: 'Bearer ${API_KEY}' }],
+ }
+ return current
+ }
+ function changeRequest() {
+ return {
+ serverName: 'connector',
+ server: assignedServer(),
+ selection: { ready: true, secret: existing, rows: [{ ...row, value: '' }] },
+ }
+ }
+ beforeEach(() => {
+ vi.mocked(api.getMcpServer).mockResolvedValue(assignedServer())
+ })
+ it('changes only envSecret and preserves the remote auth, access, egress, and identity preconditions', async () => {
+ const result = await changeConnectorSecretReference(changeRequest())
+ expect(api.updateMcpServer).toHaveBeenCalledWith('connector', {
+ metadata: { uid: 'server-uid', resourceVersion: '10' },
+ spec: { ...assignedServer().spec, envSecret: reference },
+ })
+ expect(result.server.spec.envSecret).toEqual(reference)
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpSecret).not.toHaveBeenCalled()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it.each([
+ { managed: false },
+ { enabled: false },
+ { oauth: null },
+ { envSecret: null },
+ { envSecret: { name: 'invalid' } },
+ ])('rejects ineligible reference changes without writes: %j', async changed => {
+ const request = changeRequest()
+ request.server.spec = { ...request.server.spec, ...changed }
+ vi.mocked(api.getMcpServer).mockResolvedValue(request.server)
+ await expect(changeConnectorSecretReference(request)).rejects.toThrow(/connector changed/)
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('rejects an edit since the displayed snapshot before checking or writing Secrets', async () => {
+ const changed = assignedServer()
+ changed.spec.image = 'example/new-image:v2'
+ vi.mocked(api.getMcpServer).mockResolvedValue(changed)
+ await expect(changeConnectorSecretReference(changeRequest())).rejects.toThrow(
+ /connector changed/
+ )
+ expect(api.listMcpSecrets).not.toHaveBeenCalled()
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ })
+ it('rejects changes between verification and the final write', async () => {
+ const changed = assignedServer()
+ changed.spec.enabled = false
+ vi.mocked(api.getMcpServer)
+ .mockResolvedValueOnce(assignedServer())
+ .mockResolvedValueOnce(changed)
+ await expect(changeConnectorSecretReference(changeRequest())).rejects.toThrow(
+ /connector changed/
+ )
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ })
+ // Each case is the full `items` array, wrapped one extra level so `it.each`
+ // passes it as a single argument instead of spreading it.
+ it.each([
+ [[]],
+ [[{ ...existing, uid: 'replacement' }]],
+ [[{ ...existing, keys: ['different-key'] }]],
+ ])('rejects missing/replaced Secrets and missing stored keys: %j', async items => {
+ vi.mocked(api.listMcpSecrets).mockResolvedValue({ items })
+ await expect(changeConnectorSecretReference(changeRequest())).rejects.toThrow(/Secret|key/)
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ expect(api.createMcpSecret).not.toHaveBeenCalled()
+ expect(api.updateMcpSecret).not.toHaveBeenCalled()
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('rejects an unchanged assignment', async () => {
+ const current = assignedServer()
+ current.spec.envSecret = reference
+ vi.mocked(api.getMcpServer).mockResolvedValue(current)
+ await expect(
+ changeConnectorSecretReference({ ...changeRequest(), server: current })
+ ).rejects.toThrow(/different Secret/)
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ })
+ it('never cleans up shared Secrets when the API rejects the reference save', async () => {
+ vi.mocked(api.updateMcpServer).mockRejectedValue(error(409))
+ await expect(changeConnectorSecretReference(changeRequest())).rejects.toThrow(/rejected/)
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('recovers an uncertain successful save through a matching read', async () => {
+ vi.mocked(api.updateMcpServer).mockRejectedValue(error(503))
+ const saved = assignedServer()
+ saved.spec.envSecret = reference
+ vi.mocked(api.getMcpServer)
+ .mockResolvedValueOnce(assignedServer())
+ .mockResolvedValueOnce(assignedServer())
+ .mockResolvedValueOnce(saved)
+ expect((await changeConnectorSecretReference(changeRequest())).server).toEqual(saved)
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('reports an uncertain outcome when the read cannot prove the reference was saved', async () => {
+ vi.mocked(api.updateMcpServer).mockRejectedValue(error(503))
+ await expect(changeConnectorSecretReference(changeRequest())).rejects.toThrow(
+ /could not be confirmed/
+ )
+ expect(api.deleteMcpSecret).not.toHaveBeenCalled()
+ })
+ it('rejects any attempt to supply credential bytes in a reference-only operation', async () => {
+ const request = changeRequest()
+ request.selection.rows[0].value = 'unexpected'
+ await expect(changeConnectorSecretReference(request)).rejects.toThrow(/key/)
+ expect(api.updateMcpServer).not.toHaveBeenCalled()
+ expect(api.updateMcpSecret).not.toHaveBeenCalled()
+ })
+})
diff --git a/control-ui/lib/connectorCredentials.ts b/control-ui/lib/connectorCredentials.ts
index 5a7f86112..60c8688ae 100644
--- a/control-ui/lib/connectorCredentials.ts
+++ b/control-ui/lib/connectorCredentials.ts
@@ -20,7 +20,9 @@ import type {
AttachMode,
AttachPayload,
AttachValidation,
+ AttachValidationOptions,
AttachedCredentials,
+ ChangeCredentialReferenceRequest,
} from './connectorCredentials.types'
/** Structural eligibility, independent of potentially stale status conditions. */
@@ -38,6 +40,124 @@ export function credentialAttachUnavailable(server: McpServerResource): string |
return undefined
}
+/** A reference change is separate from rotating values in a shared Secret. */
+export function credentialReferenceChangeUnavailable(
+ server: McpServerResource
+): string | undefined {
+ const raw = server.spec?.envSecret as { name?: unknown; keys?: unknown } | undefined
+ if (
+ !raw ||
+ typeof raw.name !== 'string' ||
+ raw.name !== raw.name.trim() ||
+ !MCP_SECRET_NAME_PATTERN.test(raw.name) ||
+ !Array.isArray(raw.keys) ||
+ !raw.keys.length ||
+ raw.keys.some(
+ key => !key || typeof key.secretKey !== 'string' || typeof key.envVar !== 'string'
+ )
+ )
+ return 'The connector has no valid Secret reference to change.'
+ const { envSecret: _reference, ...spec } = server.spec!
+ return credentialAttachUnavailable({ ...server, spec })
+}
+
+/** Refresh metadata only. Never read, create, rotate, or delete credential values. */
+export async function verifyExistingCredentialSelection(
+ secretName: string,
+ rows: AttachCredentialRow[],
+ selected: McpSecretSummary | undefined,
+ server: McpServerResource
+): Promise<void> {
+ const { items } = await listMcpSecrets()
+ const current = items.find(item => item.name === secretName)
+ if (!selected || !current || (selected.uid && selected.uid !== current.uid)) {
+ throw new CredentialAttachError(
+ 'This Secret no longer exists or was replaced. Refresh and select it again.',
+ true
+ )
+ }
+ if (rows.some(row => row.value !== '' || !current.keys.includes(row.secretKey.trim()))) {
+ throw new CredentialAttachError(
+ 'A selected key is no longer available. Refresh and select its replacement.',
+ true
+ )
+ }
+ const invalid = validateCredentialAttach('use-existing', secretName, rows, server, current, {
+ storedKeysOnly: true,
+ })
+ if (invalid) throw new CredentialAttachError(invalid.message)
+}
+
+/** Replace only envSecret, with explicit snapshot and API concurrency checks. */
+export async function changeConnectorSecretReference({
+ serverName,
+ server,
+ selection,
+}: ChangeCredentialReferenceRequest): Promise<AttachedCredentials> {
+ const initial = await getMcpServer(serverName)
+ if (
+ !server.metadata?.uid ||
+ initial.metadata?.uid !== server.metadata.uid ||
+ !initial.metadata?.resourceVersion ||
+ credentialReferenceChangeUnavailable(initial) ||
+ !sameCredentialSpec(server.spec, initial.spec)
+ )
+ throw new CredentialAttachError(
+ 'The connector changed. Refresh before changing its assigned Secret.',
+ true
+ )
+ const secretName = selection.secret?.name ?? ''
+ if (!selection.ready)
+ throw new CredentialAttachError('Wait for the Secret list to finish loading.')
+ await verifyExistingCredentialSelection(secretName, selection.rows, selection.secret, initial)
+ const { reference } = buildAttachPayload(secretName, selection.rows)
+ if (sameCredentialSpec(initial.spec?.envSecret, reference)) {
+ throw new CredentialAttachError('Choose a different Secret or change its key mappings.')
+ }
+ const latest = await getMcpServer(serverName)
+ if (
+ latest.metadata?.uid !== initial.metadata.uid ||
+ !latest.metadata?.resourceVersion ||
+ credentialReferenceChangeUnavailable(latest) ||
+ !sameCredentialSpec(initial.spec, latest.spec)
+ )
+ throw new CredentialAttachError(
+ 'The connector changed. Refresh before changing its assigned Secret.',
+ true
+ )
+ const spec = { ...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,
+ })
+ } catch (error) {
+ if (definiteRejection(error)) {
+ throw new CredentialAttachError(
+ 'The assignment was rejected. Refresh and review the connector before retrying.',
+ true
+ )
+ }
+ try {
+ saved = await getMcpServer(serverName)
+ } catch {
+ throw new CredentialAttachError(
+ 'The assignment outcome could not be confirmed. Refresh to check the connector.',
+ true
+ )
+ }
+ if (saved.metadata?.uid !== initial.metadata.uid || !sameCredentialSpec(saved.spec, spec)) {
+ throw new CredentialAttachError(
+ 'The assignment outcome could not be confirmed. Refresh to check the connector.',
+ true
+ )
+ }
+ }
+ return { server: saved, cutoff, affectedConnectors: [] }
+}
+
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 : ''
@@ -48,7 +168,8 @@ export function validateCredentialAttach(
secretName: string,
rows: AttachCredentialRow[],
server: McpServerResource,
- selected?: McpSecretSummary
+ selected?: McpSecretSummary,
+ options?: AttachValidationOptions
): AttachValidation | undefined {
if (!MCP_SECRET_NAME_PATTERN.test(secretName.trim()) || secretName.trim().length > 253) {
return {
@@ -72,6 +193,26 @@ export function validateCredentialAttach(
for (const row of rows) {
const key = row.secretKey.trim()
const env = row.envVar.trim()
+ if (options?.storedKeysOnly) {
+ // Reference-only reuse: keys must already exist in the selected Secret
+ // and values are never accepted. A missing or stale key is a key
+ // selection problem, never a request to re-enter a credential value.
+ if (!key) {
+ return { message: 'Choose a stored key from the selected Secret.', field: `${row.id}-key` }
+ }
+ if (!selected || !selected.keys.includes(key)) {
+ return {
+ message: `"${key}" is not stored in the selected Secret. Refresh the Secret list and choose a stored key.`,
+ field: `${row.id}-key`,
+ }
+ }
+ if (row.value !== '') {
+ return {
+ message: 'Stored keys never take a value here. Values stay unchanged in the Secret.',
+ field: `${row.id}-value`,
+ }
+ }
+ }
if (!/^[-._a-zA-Z0-9]+$/.test(key) || key.length > 253 || key === '.' || key.startsWith('..')) {
return {
message:
diff --git a/control-ui/lib/connectorCredentials.types.ts b/control-ui/lib/connectorCredentials.types.ts
index ab9aaf67a..651539cb1 100644
--- a/control-ui/lib/connectorCredentials.types.ts
+++ b/control-ui/lib/connectorCredentials.types.ts
@@ -35,3 +35,25 @@ export type AttachPayload = {
reference: EnvSecret
data: Record<string, string>
}
+
+/**
+ * Validation switches for credential selection. `storedKeysOnly` marks the
+ * reference-only reuse flows: every key must already be stored in the selected
+ * Secret and credential values are forbidden. The keyless-attach flow omits it
+ * because it may write new keys into a shared Secret.
+ */
+export type AttachValidationOptions = {
+ storedKeysOnly?: boolean
+}
+
+export type ExistingCredentialSelection = {
+ secret?: McpSecretSummary
+ rows: AttachCredentialRow[]
+ ready: boolean
+}
+
+export type ChangeCredentialReferenceRequest = {
+ serverName: string
+ server: McpServerResource
+ selection: ExistingCredentialSelection
+}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 52422f78a..c129ea928 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.751",
+ "version": "0.1.752",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.751",
+ "version": "0.1.752",
"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 8ab25e749..8058daf60 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.751",
+ "version": "0.1.752",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",