Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-ui): gate wizard create on RFC1123 format and existing-host collision (R4-B1, R4-H1)
Diego Zacarias11d5beee0b86
diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsxindex 486aa3a35..75feba234 100644--- a/control-ui/components/HostWizard/index.tsx+++ b/control-ui/components/HostWizard/index.tsx@@ -35,7 +35,7 @@ import {resolveDefaultModel,validateLlmSecretData,} from '@/lib/llm'-import { toKebabCase, toKebabInput } from '@/lib/string'+import { RFC1123_MAX_LENGTH, isValidResourceSlug, toKebabCase, toKebabInput } from '@/lib/string'import {HOST_NAMESPACE,HOST_SECRET_LABEL_KEY,@@ -209,6 +209,17 @@ function WizardSelect({)}+// Human-readable reason a derived slug fails the server RFC1123 constraint, or+// null when it is valid (or empty — the empty case is surfaced by each field's+// own "must contain letters or numbers" message).+function slugConstraintMessage(rawName: string): string | null {+ const slug = toKebabCase(rawName)+ if (slug.length === 0) return null+ if (slug.length > RFC1123_MAX_LENGTH) return 'Identifier must be at most 63 characters.'+ if (!isValidResourceSlug(rawName)) return 'Identifier must be a valid RFC1123 identifier.'+ return null+}+function isStepValid(stepIndex: number,state: {@@ -233,19 +244,29 @@ function isStepValid(selectedUserIds: string[]selectedTeamIds: string[]directoryLoadFailed: boolean+ existingHostNames: string[]}): boolean {- // Gate on the DERIVED slug, not the raw text: a name with no ASCII- // alphanumerics ("!!!", "日本語", "---", whitespace) trims to a non-empty- // string but toKebabCase()s to "", which would send metadata.name: "" — and- // because the secret/context are created BEFORE the host in submit(), a- // failed host create would orphan those siblings.- if (stepIndex === 0) return toKebabCase(state.hostName).length > 0+ // Gate on the DERIVED slug against the FULL server constraint, not just+ // "non-empty": a name with no ASCII alphanumerics ("!!!", "日本語", "---",+ // whitespace) slugs to "", and a 70-char name slugs to a >63 label the server+ // rejects (`invalid_name`, RFC1123 DNS-label). Either way the secret/context+ // are created BEFORE the host in submit(), so a rejected host create orphans+ // those siblings. isValidResourceSlug mirrors the server rule client-side.+ if (stepIndex === 0) {+ if (!isValidResourceSlug(state.hostName)) return false+ // Block a slug that collides with an existing host: create's PUT-first+ // upsert (submitAll → upsertResource('admin/hosts', …)) would otherwise+ // overwrite that agent's entire spec and still report "created". Gating here+ // stops the collision BEFORE any sibling (secret/context/channel) is created.+ if (state.existingHostNames.includes(toKebabCase(state.hostName))) return false+ return true+ }if (stepIndex === 1) {if (state.contextMode === 'existing') return state.selectedExistingContext.trim().length > 0// Same slug-derivation gate: the new context upsert runs before the host- // create, so an empty derived name here has the same orphan risk.- return toKebabCase(state.contextName).length > 0+ // create, so an invalid/over-long derived name here has the same orphan risk.+ return isValidResourceSlug(state.contextName)}if (stepIndex === 2) {// New secret: the PRIMARY provider must be usable (asymmetric gate — a@@ -262,7 +283,7 @@ function isStepValid(const hasValidSecret =state.secretMode === 'existing'? state.existingSecret.trim().length > 0- : toKebabCase(state.newSecretName).length > 0 &&+ : isValidResourceSlug(state.newSecretName) &&primaryCredentialUsable(state.provider, state.llmKeyDraft) &&validateLlmSecretData(projectedDraft).length === 0return hasValidSecret && state.modelName.trim().length > 0@@ -273,7 +294,7 @@ function isStepValid(if (stepIndex === 4) {if (state.channelMode === 'skip') return trueif (state.channelMode === 'existing') return state.selectedExistingChannel.trim().length > 0- if (!toKebabCase(state.channelName)) return false+ if (!isValidResourceSlug(state.channelName)) return falseif (!hasRequiredChannelCredential(state.channelProvider, state.pendingCredentials)) return falseif (state.channelProvider === 'telegram' &&@@ -314,6 +335,10 @@ export function HostWizard({const [hostName, setHostName] = useState('')const hostNamespace = HOST_NAMESPACE+ // Existing host slugs (metadata.name), loaded up front so the step-0 gate can+ // block a colliding name BEFORE any sibling is created. Without this, create's+ // PUT-first upsert would silently overwrite an existing agent's whole spec.+ const [existingHostNames, setExistingHostNames] = useState<string[]>([])const [contextName, setContextName] = useState('')const [contextMode, setContextMode] = useState<'existing' | 'new'>('existing')@@ -484,6 +509,7 @@ export function HostWizard({selectedUserIds,selectedTeamIds,directoryLoadFailed: directoryLoadError.length > 0,+ existingHostNames,})}, [step,@@ -508,6 +534,7 @@ export function HostWizard({selectedUserIds,selectedTeamIds,directoryLoadError,+ existingHostNames,])const loadDirectory = useCallback(async () => {@@ -515,7 +542,7 @@ export function HostWizard({setDirectoryLoadError('')setError('')try {- const [usersData, teamsData, contextsData, channelsData] = await Promise.all([+ const [usersData, teamsData, contextsData, channelsData, hostsData] = await Promise.all([getAdminUsers(''),getAdminTeams(),apiGet('/api/v1/admin/contexts') as Promise<{@@ -530,6 +557,9 @@ export function HostWizard({spec?: Record<string, unknown>}>}>,+ apiGet('/api/v1/admin/hosts') as Promise<{+ items?: Array<{ metadata?: { name?: string } }>+ }>,])if (!mountedRef.current) returnsetUsers(Array.isArray(usersData.items) ? usersData.items : [])@@ -558,6 +588,10 @@ export function HostWizard({.filter(channel => channel.name).sort((a, b) => `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`))setExistingChannels(channelOptions)+ const hostNames = (hostsData.items || [])+ .map(host => String(host.metadata?.name || '').trim())+ .filter(Boolean)+ setExistingHostNames(hostNames)} catch (e) {if (!mountedRef.current) returnconst message =@@ -602,6 +636,7 @@ export function HostWizard({selectedUserIds,selectedTeamIds,directoryLoadFailed: directoryLoadError.length > 0,+ existingHostNames,})) {return false@@ -632,21 +667,29 @@ export function HostWizard({selectedUserIds,selectedTeamIds,directoryLoadError,+ existingHostNames,])const validationMessage = useMemo(() => {if (step === 0 && !toKebabCase(hostName)) return 'Agent name must contain letters or numbers.'+ if (step === 0 && slugConstraintMessage(hostName)) return slugConstraintMessage(hostName)!+ if (step === 0 && existingHostNames.includes(toKebabCase(hostName)))+ return 'Identifier already in use — choose another name.'if (step === 1 && contextMode === 'existing' && !selectedExistingContext.trim())return 'Select an existing context.'if (step === 1 && contextMode === 'new' && !toKebabCase(contextName))return 'Context name must contain letters or numbers.'+ if (step === 1 && contextMode === 'new' && slugConstraintMessage(contextName))+ return slugConstraintMessage(contextName)!if (step === 2 && !modelName.trim()) return 'Model name is required.'if (step === 2 && secretMode === 'existing' && !existingSecret.trim())return 'Select an existing secret.'if (step === 2 && secretMode === 'new' && !toKebabCase(newSecretName)) {return 'For a new secret, set a name.'}+ if (step === 2 && secretMode === 'new' && slugConstraintMessage(newSecretName))+ return slugConstraintMessage(newSecretName)!if (step === 2 && secretMode === 'new' && !primaryCredentialUsable(provider, llmKeyDraft)) {return `Add the ${getProviderLabel(provider)} credential for the primary model.`}@@ -662,6 +705,8 @@ export function HostWizard({return 'Select an existing channel or skip channel setup.'if (step === 4 && channelMode === 'new' && !toKebabCase(channelName))return 'CommunicationChannel name is required, or skip channel setup.'+ if (step === 4 && channelMode === 'new' && slugConstraintMessage(channelName))+ return slugConstraintMessage(channelName)!if (step === 4 &&channelMode === 'new' &&@@ -705,6 +750,7 @@ export function HostWizard({modelName,selectedUserIds,selectedTeamIds,+ existingHostNames,])async function upsertResource(@@ -787,6 +833,12 @@ export function HostWizard({try {const shouldSkipChannels = options.skipChannels || channelMode === 'skip'const normalizedHostName = toKebabCase(hostName)+ // Collision guard, mirrored from the step-0 gate: create's PUT-first+ // upsert would overwrite an existing agent's spec. Throw BEFORE creating+ // any sibling (secret/context/channel) so a collision never orphans them.+ if (existingHostNames.includes(normalizedHostName)) {+ throw new Error('Identifier already in use — choose another name.')+ }const normalizedContextName = toKebabCase(contextName)const resolvedContextName =contextMode === 'existing' ? selectedContextOption?.contextId || '' : normalizedContextName@@ -1015,6 +1067,9 @@ export function HostWizard({Identifier: <code>{toKebabCase(hostName)}</code></span>) : null}+ {slugConstraintMessage(hostName) ? (+ <span className="cu-field__error">{slugConstraintMessage(hostName)}</span>+ ) : null}</Field><div className="cu-agent-namespace">Namespace: {HOST_NAMESPACE}</div>{SHOW_STATELESS_AGENT_SELECTOR ? (diff --git a/control-ui/components/__tests__/HostWizard.slug-gate.test.tsx b/control-ui/components/__tests__/HostWizard.slug-gate.test.tsxindex 64eed689c..44fef50bb 100644--- a/control-ui/components/__tests__/HostWizard.slug-gate.test.tsx+++ b/control-ui/components/__tests__/HostWizard.slug-gate.test.tsx@@ -131,3 +131,68 @@ describe('HostWizard — step 1 new-context gate on the derived slug (R1-B1 siblexpect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled()})})++/**+ * Regression guard for R4-H1: the step-0 gate must mirror the SERVER validation+ * (RFC1123 DNS-label ≤63 chars), not just "derives a non-empty slug". A 64-char+ * name derives a valid-but-too-long slug that passes `toKebabCase(x).length > 0`+ * yet is rejected server-side (`invalid_name`), orphaning the siblings created+ * before the host. FAILS against the pre-fix head where the gate was+ * `toKebabCase(state.hostName).length > 0`.+ */+describe('HostWizard — step 0 gates on the RFC1123 length limit (R4-H1)', () => {+ it('keeps Next DISABLED when the derived slug exceeds 63 characters', async () => {+ await renderWizard()+ await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())++ fireEvent.change(screen.getByPlaceholderText(/agent-name/i), {+ target: { value: 'a'.repeat(64) },+ })++ expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()+ expect(screen.getAllByText(/at most 63 characters/i).length).toBeGreaterThan(0)+ })++ it('enables Next for a 63-character derived slug (boundary)', async () => {+ await renderWizard()+ await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())++ fireEvent.change(screen.getByPlaceholderText(/agent-name/i), {+ target: { value: 'a'.repeat(63) },+ })++ expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled()+ })+})++/**+ * Regression guard for R4-B1: create is a PUT-first upsert, so a slug that+ * collides with an existing host would silently OVERWRITE that agent's spec and+ * report "created". The step-0 gate must block a colliding derived slug BEFORE+ * any sibling (secret/context/channel) is created — no create request escapes.+ * FAILS against the pre-fix head, which never loaded the host directory.+ */+describe('HostWizard — step 0 blocks a slug colliding with an existing host (R4-B1)', () => {+ it('keeps Next DISABLED and fires no create request when the slug matches an existing host', async () => {+ ;(api.apiGet as unknown as ReturnType<typeof vi.fn>).mockImplementation((path: string) => {+ if (path === '/api/v1/admin/hosts') {+ return Promise.resolve({ items: [{ metadata: { name: 'my-agent' } }] })+ }+ return Promise.resolve({ items: [] })+ })++ await renderWizard()+ await waitFor(() => expect(api.apiGet).toHaveBeenCalledWith('/api/v1/admin/hosts'))++ // "My Agent" derives to the slug "my-agent", which already exists.+ fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: 'My Agent' } })++ expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()+ expect(screen.getByText(/Identifier already in use/i)).toBeInTheDocument()+ // No create request (POST/PUT via apiSend) escapes for a colliding slug.+ expect(api.apiSend).not.toHaveBeenCalled()++ // Restore the default apiGet stub so no implementation leaks past this test.+ ;(api.apiGet as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({ items: [] })+ })+})diff --git a/control-ui/lib/k8sValidation.ts b/control-ui/lib/k8sValidation.tsindex cbd7f4563..e43642669 100644--- a/control-ui/lib/k8sValidation.ts+++ b/control-ui/lib/k8sValidation.ts@@ -6,8 +6,11 @@const K8S_NAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/+// RFC1123 DNS-label max length, mirrored by the server (`invalid_name`).+export const RFC1123_MAX_LENGTH = 63+export function isValidK8sName(name: string): boolean {- return K8S_NAME_RE.test(name) && name.length <= 63+ return K8S_NAME_RE.test(name) && name.length <= RFC1123_MAX_LENGTH}/**diff --git a/control-ui/lib/string.ts b/control-ui/lib/string.tsindex c38c97f81..fbf0a6aa1 100644--- a/control-ui/lib/string.ts+++ b/control-ui/lib/string.ts@@ -1,3 +1,19 @@+import { RFC1123_MAX_LENGTH, isValidK8sName } from './k8sValidation'++export { RFC1123_MAX_LENGTH }++/**+ * A derived slug is server-acceptable only when it is a valid RFC1123 DNS label+ * (non-empty, lowercase alphanumerics + interior hyphens, ≤63 chars). Gates that+ * only checked `toKebabCase(x).length > 0` let e.g. a 70-char name through the+ * client; the server then rejects it (`invalid_name`) after siblings created+ * first are already orphaned. This mirrors the server constraint client-side.+ * Reuses the shared K8s validator (`lib/k8sValidation`).+ */+export function isValidResourceSlug(rawName: string): boolean {+ return isValidK8sName(toKebabCase(rawName))+}+export function toKebabCase(input: string): string {return input.toLowerCase()