Skip to content

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

TypeScript

fix(control-ui): gate context create on full RFC1123 slug and display-field rule (R4-H1 sibling)

Diego Zacarias155ee04c18d2
diff --git a/control-ui/app/contexts/__tests__/CreateContextPage.rfc1123-display-gate.test.tsx b/control-ui/app/contexts/__tests__/CreateContextPage.rfc1123-display-gate.test.tsx
new file mode 100644
index 000000000..25b308aa5
--- /dev/null
+++ b/control-ui/app/contexts/__tests__/CreateContextPage.rfc1123-display-gate.test.tsx
@@ -0,0 +1,123 @@
+import React from 'react'
+import type { ReactNode } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
+import { ToastProvider } from '../../../components/Toast'
+import * as api from '../../../lib/api'
+import CreateContextPage from '../new/page'
+
+/**
+ * Regression guard for the context-create page's gate — the sibling of R4-H1 /
+ * R5-H1 in HostWizard (phase 4 of the display-field mini-spec).
+ *
+ * D-A: canSubmit/canContinue/canSelectStep must gate on the FULL RFC1123 rule
+ * (isValidResourceSlug), not just `toKebabCase(name).length > 0`. A name
+ * whose derived slug is >63 chars trims/kebabs non-empty but the server
+ * rejects it (invalid_name).
+ * D-B: the free-text `spec.displayName` (contextName.trim()) must be validated
+ * with the shared @clerum/display-field rule the server applies. A bidi/
+ * control char survives into displayName (toKebabCase strips it from the
+ * slug) or a >120-char display is rejected server-side.
+ *
+ * These tests FAIL against the pre-fix head, where the gates read only
+ * `toKebabCase(contextName).length > 0`: the over-long slug and the bidi/long
+ * display names all enabled Continue and let a doomed create escape.
+ */
+
+const replaceMock = vi.fn()
+const pushMock = vi.fn()
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: pushMock, replace: replaceMock }),
+}))
+
+vi.mock('@components/AuthGate', () => ({
+ AuthGate: ({ children }: { children: ReactNode }) => <>{children}</>,
+}))
+
+vi.mock('../../../components/DashboardLayout', () => ({
+ DashboardLayout: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}))
+
+vi.mock('../../../lib/api', () => ({
+ createContext: vi.fn().mockResolvedValue({}),
+ getMcpServers: vi.fn().mockResolvedValue({ items: [] }),
+}))
+
+function render(children: ReactNode) {
+ return rtlRender(<ToastProvider>{children}</ToastProvider>)
+}
+
+async function typeName(value: string) {
+ render(<CreateContextPage />)
+ await waitFor(() => expect(api.getMcpServers).toHaveBeenCalled())
+ fireEvent.change(screen.getByPlaceholderText('Context 1'), { target: { value } })
+}
+
+afterEach(() => {
+ cleanup()
+})
+
+describe('CreateContextPage — RFC1123 slug + displayName gate (D-A / D-B)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ // INV-1 (D-A): a name whose derived slug exceeds 63 chars must block.
+ it('blocks an over-long (>63) derived slug and never calls createContext', async () => {
+ await typeName('a'.repeat(64)) // toKebabCase() → 64 chars, > RFC1123 limit
+
+ const continueBtn = screen.getByRole('button', { name: 'Continue' })
+ expect(continueBtn).toBeDisabled()
+ expect(screen.getByText(/at most 63 characters/i)).toBeInTheDocument()
+
+ fireEvent.click(continueBtn)
+ expect(api.createContext).not.toHaveBeenCalled()
+ })
+
+ // INV-2 (D-B): the R5-H1 vector — a bidi override char. toKebabCase strips it,
+ // so the slug (`ctxname`) is valid, but it survives into spec.displayName.
+ it('blocks a name with a bidi formatting char (valid slug, invalid display)', async () => {
+ await typeName('ctx‮name') // slug → "ctxname" (valid); display keeps U+202E
+
+ const continueBtn = screen.getByRole('button', { name: 'Continue' })
+ expect(continueBtn).toBeDisabled()
+ expect(screen.getByText(/control or formatting characters/i)).toBeInTheDocument()
+
+ // Observable result (T4): no create request escapes with a rejected display.
+ fireEvent.click(continueBtn)
+ expect(api.createContext).not.toHaveBeenCalled()
+ })
+
+ // INV-3 (D-B): a >120-char display value with a still-valid ≤63 slug.
+ it('blocks a display value longer than 120 chars even when the slug is valid', async () => {
+ // trim() length 131; toKebabCase() strips the dots → "a" (valid ≤63 slug).
+ await typeName('a' + '.'.repeat(130))
+
+ const continueBtn = screen.getByRole('button', { name: 'Continue' })
+ expect(continueBtn).toBeDisabled()
+ expect(screen.getByText(/too long \(max 120 characters\)/i)).toBeInTheDocument()
+
+ fireEvent.click(continueBtn)
+ expect(api.createContext).not.toHaveBeenCalled()
+ })
+
+ // Positive control: a clean name still enables Continue and creates.
+ it('enables Continue for a valid name and shows the derived identifier', async () => {
+ await typeName('My Context')
+
+ const continueBtn = screen.getByRole('button', { name: 'Continue' })
+ expect(continueBtn).not.toBeDisabled()
+ expect(screen.getByText('my-context')).toBeInTheDocument()
+
+ fireEvent.click(continueBtn)
+ fireEvent.click(screen.getByRole('button', { name: 'Create context' }))
+
+ await waitFor(() => expect(api.createContext).toHaveBeenCalled())
+ const [payload] = (api.createContext as unknown as ReturnType<typeof vi.fn>).mock.calls[0] as [
+ { metadata: { name: string }; spec: { contextId: string; displayName?: string } },
+ ]
+ expect(payload.metadata.name).toBe('my-context')
+ expect(payload.spec.displayName).toBe('My Context')
+ })
+})
diff --git a/control-ui/app/contexts/new/page.tsx b/control-ui/app/contexts/new/page.tsx
index fc5ee7c00..3bef1bdf4 100644
--- a/control-ui/app/contexts/new/page.tsx
+++ b/control-ui/app/contexts/new/page.tsx
@@ -2,6 +2,11 @@
import React, { useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
+import {
+ CONTROL_CHAR_RE,
+ DISPLAY_FIELD_MAX_LENGTH,
+ validateDisplayField,
+} from '@clerum/display-field'
import { AuthGate } from '@components/AuthGate'
import { CreateFlowPanel } from '@components/CreateFlowPanel'
import { CreatePageHeader } from '@components/CreatePageHeader'
@@ -12,10 +17,58 @@ import { IconGroupWork } from '@components/Sidebar/icons'
import { Button, Field, TextAreaInput, TextInput } from '@components/ui'
import { CONTROL_ROUTES } from '@constants/routes'
import { createContext, getMcpServers } from '@lib/api'
-import { toKebabCase } from '@lib/string'
+import { RFC1123_MAX_LENGTH, isValidResourceSlug, toKebabCase } from '@lib/string'
const STEPS = ['Context', 'Connectors'] as const
+// The exact free-text value the create call writes to spec.displayName. Only a
+// non-empty trimmed name is sent (an empty one is omitted from the payload), so
+// the display gate mirrors precisely what the server will validate.
+function displayNameValue(rawName: string): string {
+ return rawName.trim()
+}
+
+// True when the derived slug AND the displayName the server would receive are
+// both acceptable. Mirrors the two server constraints client-side:
+// - slug: RFC1123 DNS label ≤63 (isValidResourceSlug, same as HostWizard).
+// - display: the shared @clerum/display-field rule (D4 — the RULE lives in the
+// package, the same one the server applies; here we only consume it). Empty
+// display is valid: it is omitted from the payload, and the empty case is
+// already blocked by the slug gate.
+function contextNameIsValid(rawName: string): boolean {
+ if (!isValidResourceSlug(rawName)) return false
+ const display = displayNameValue(rawName)
+ if (display.length === 0) return true
+ return validateDisplayField(display, 'spec.displayName') === null
+}
+
+// Human-readable reason the derived slug fails the server RFC1123 constraint, or
+// null when valid (or empty — the empty case is surfaced by the field's own
+// "must contain letters or numbers" message). Matches HostWizard.slugConstraintMessage.
+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
+}
+
+// Human-readable reason the free-text spec.displayName value is rejected, or null
+// when acceptable. The RULE of validity is owned by @clerum/display-field (the
+// SAME rule the server applies, D4); this only maps the machine issue to a
+// message. Empty is intentionally NOT surfaced here — it is omitted from the
+// payload and the empty case is covered by the slug message.
+function displayNamePreflightMessage(rawName: string): string | null {
+ const value = displayNameValue(rawName)
+ if (value.length === 0) return null
+ if (!validateDisplayField(value, 'spec.displayName')) return null
+ if (CONTROL_CHAR_RE.test(value))
+ return "Context name can't contain control or formatting characters."
+ if (value.trim().length > DISPLAY_FIELD_MAX_LENGTH)
+ return `Context name is too long (max ${DISPLAY_FIELD_MAX_LENGTH} characters).`
+ return null
+}
+
const STEP_DETAILS = [
{
description: 'Name and describe it',
@@ -71,15 +124,17 @@ export default function CreateContextPage() {
void loadServers()
}, [])
- // 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/contextId: "".
- const canSubmit = useMemo(() => toKebabCase(contextName).length > 0 && !busy, [busy, contextName])
- const canContinue = step === 0 ? toKebabCase(contextName).length > 0 : true
+ // Gate on the FULL server rules, not just "derived slug non-empty": the slug
+ // must be a valid RFC1123 label (≤63) AND the free-text displayName the server
+ // will receive must satisfy @clerum/display-field. A name that only clears
+ // "non-empty slug" — an over-long slug, or a bidi/control/over-120 display —
+ // passes the client and the server then rejects it (invalid_name / display).
+ const canSubmit = useMemo(() => contextNameIsValid(contextName) && !busy, [busy, contextName])
+ const canContinue = step === 0 ? contextNameIsValid(contextName) : true
function canSelectStep(targetStep: number) {
if (targetStep <= step) return true
- return toKebabCase(contextName).length > 0
+ return contextNameIsValid(contextName)
}
async function handleCreateContext() {
@@ -89,6 +144,14 @@ export default function CreateContextPage() {
try {
const nextName = toKebabCase(contextName)
const trimmedDisplay = contextName.trim()
+ // Hard guard (defense if the gate is bypassed): the displayName is free
+ // text the server validates with @clerum/display-field (D4 — the RULE is
+ // the package's, the same one the server applies). Fail before any write
+ // instead of round-tripping a doomed create.
+ if (trimmedDisplay && validateDisplayField(trimmedDisplay, 'spec.displayName')) {
+ setError(displayNamePreflightMessage(contextName) || 'Context name is not valid.')
+ return
+ }
await createContext({
metadata: { name: nextName },
spec: {
@@ -143,15 +206,23 @@ export default function CreateContextPage() {
placeholder="Context 1"
autoFocus
/>
- {toKebabCase(contextName) ? (
+ {!toKebabCase(contextName) ? (
+ contextName.trim() ? (
+ <span className="cu-field__error">
+ Context name must contain letters or numbers.
+ </span>
+ ) : null
+ ) : slugConstraintMessage(contextName) ? (
+ <span className="cu-field__error">{slugConstraintMessage(contextName)}</span>
+ ) : displayNamePreflightMessage(contextName) ? (
+ <span className="cu-field__error">
+ {displayNamePreflightMessage(contextName)}
+ </span>
+ ) : (
<span className="cu-field__hint">
Identifier: <code>{toKebabCase(contextName)}</code>
</span>
- ) : contextName.trim() ? (
- <span className="cu-field__error">
- Context name must contain letters or numbers.
- </span>
- ) : null}
+ )}
</Field>
<Field label="Description" htmlFor="ctx-description">
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 996b5bad5..b93964ed4 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.398",
+ "version": "0.1.399",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.398",
+ "version": "0.1.399",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-ui/package.json b/control-ui/package.json
index b590a2308..b90eafe75 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.398",
+ "version": "0.1.399",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",