Skip to content

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

TypeScript

feat(control-api): validate resource name and display/identifier fields

Diego Zacarias302e72ad7a30
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 49284f613..d052d9440 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.432",
+ "version": "0.1.433",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.432",
+ "version": "0.1.433",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-api/package.json b/control-api/package.json
index 62a5d275c..e2b561351 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.432",
+ "version": "0.1.433",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/resourceFieldValidation.ts b/control-api/src/routes/admin/resourceFieldValidation.ts
new file mode 100644
index 000000000..8c9778ccc
--- /dev/null
+++ b/control-api/src/routes/admin/resourceFieldValidation.ts
@@ -0,0 +1,119 @@
+import { RFC1123_RE } from '../../http/rfc1123.js'
+
+/**
+ * Application-level validation of resource identifiers and display fields for the
+ * generic admin CRUD router (hosts | contexts | communication-channels |
+ * mcp-servers).
+ *
+ * Design (spec alfredo-agent-rename, Decision #7 + F0.3):
+ * - IDENTIFIERS are RFC1123 and enforced HERE, not in the CRD schema. Hardening
+ * an existing field on a live CRD makes the apiserver validate the whole
+ * object on every write (including controller /status patches) and would
+ * reject writes on legacy CRs. So the rules live in control-api instead.
+ * - DISPLAY fields (host.spec.host, context.spec.displayName) are FREE TEXT:
+ * only trimmed length and control characters are constrained.
+ * - RATCHET: on update a field is validated ONLY IF its value changed vs the
+ * current CR, so a legacy resource whose display/identifier is out of norm is
+ * never blocked for unrelated edits.
+ */
+
+/** Max length for a free-text display field (post-trim). */
+export const DISPLAY_FIELD_MAX_LENGTH = 120
+
+// Control characters (C0 range + DEL) are rejected in display fields. Newlines
+// and tabs are control characters too — a display name is a single-line label.
+const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/
+
+export interface FieldIssue {
+ field: string
+ message: string
+}
+
+/**
+ * Validate a `metadata.name` as an RFC1123 DNS label. Returns the FIX-A1 error
+ * envelope (`{error:'invalid_name', field:'metadata.name', message}`) or null.
+ * A missing/non-string name is rejected the same way an empty one is: the K8s
+ * apiserver requires a valid name and we would otherwise collapse its 422 to 500.
+ */
+export function validateResourceName(
+ name: unknown
+): { error: 'invalid_name'; field: 'metadata.name'; message: string } | null {
+ if (typeof name === 'string' && RFC1123_RE.test(name)) return null
+ return {
+ error: 'invalid_name',
+ field: 'metadata.name',
+ message:
+ 'metadata.name must be a valid RFC1123 DNS label: lowercase alphanumeric characters or ' +
+ "'-', starting and ending with an alphanumeric character, at most 63 characters.",
+ }
+}
+
+/**
+ * Validate a free-text display field (present only). Returns an issue or null.
+ * Skips when the field is absent (undefined) — display fields are optional.
+ */
+export function validateDisplayField(value: unknown, field: string): FieldIssue | null {
+ if (value === undefined) return null
+ if (typeof value !== 'string') {
+ return { field, message: `${field} must be a string` }
+ }
+ if (CONTROL_CHAR_RE.test(value)) {
+ return { field, message: `${field} must not contain control characters` }
+ }
+ if (value.trim().length > DISPLAY_FIELD_MAX_LENGTH) {
+ return {
+ field,
+ message: `${field} must be at most ${DISPLAY_FIELD_MAX_LENGTH} characters`,
+ }
+ }
+ return null
+}
+
+/**
+ * Validate an identifier field (present only) as RFC1123. Returns an issue or
+ * null. Skips when absent — presence of identifiers is enforced by the CRD
+ * schema / apiserver, not here.
+ */
+export function validateIdentifierField(value: unknown, field: string): FieldIssue | null {
+ if (value === undefined) return null
+ if (typeof value === 'string' && RFC1123_RE.test(value)) return null
+ return {
+ field,
+ message:
+ `${field} must be a valid RFC1123 DNS label: lowercase alphanumeric characters or ` +
+ "'-', starting and ending with an alphanumeric character, at most 63 characters.",
+ }
+}
+
+/**
+ * Collect display/identifier field issues for a hosts|contexts spec, applying the
+ * ratchet: when `currentSpec` is provided (update), a field is validated only if
+ * its value differs from the current CR; when null (create), every present field
+ * is validated.
+ */
+export function collectResourceSpecFieldIssues(
+ plural: 'hosts' | 'contexts',
+ spec: Record<string, unknown>,
+ currentSpec: Record<string, unknown> | null
+): FieldIssue[] {
+ const issues: FieldIssue[] = []
+ const changed = (key: string): boolean => currentSpec === null || spec[key] !== currentSpec[key]
+
+ if (plural === 'hosts') {
+ if (changed('host')) {
+ const issue = validateDisplayField(spec.host, 'spec.host')
+ if (issue) issues.push(issue)
+ }
+ } else {
+ if (changed('displayName')) {
+ const issue = validateDisplayField(spec.displayName, 'spec.displayName')
+ if (issue) issues.push(issue)
+ }
+ if (changed('contextId')) {
+ const issue = validateIdentifierField(spec.contextId, 'spec.contextId')
+ if (issue) issues.push(issue)
+ }
+ }
+
+ return issues
+}
diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.ts
index 544704dc7..d6b0770f0 100644
--- a/control-api/src/routes/admin/resources.ts
+++ b/control-api/src/routes/admin/resources.ts
@@ -5,7 +5,7 @@ import { enforceNamespace } from '../../http/namespaceAudit.js'
import { validateCommunicationChannelSpec } from '../../http/validateCommunicationChannelSpec.js'
import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'
import { K8sGateway } from '../../k8s.js'
-import { K8sConflictError } from '../../services/resourceService.js'
+import { K8sConflictError, K8sNotFoundError } from '../../services/resourceService.js'
import { ClerumResourceType } from '../../types.js'
import {
registerCommunicationChannelCredentialsRoutes,
@@ -18,6 +18,7 @@ import {
} from './communicationChannelSpecHelpers.js'
import { validateHostSecretRef } from './hostSecrets.js'
import { validateHostSpec } from './hostSpecValidation.js'
+import { collectResourceSpecFieldIssues, validateResourceName } from './resourceFieldValidation.js'
const PROVIDER_SETTINGS_FIELDS: Readonly<Record<string, readonly string[]>> = {
telegramSettings: ['botHandle', 'replyOnlyWhenMentioned'],
@@ -310,6 +311,25 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {
credentials?: Record<string, string>
}
+ // FIX-A1: validate metadata.name (RFC1123) for ALL plurals BEFORE any spec
+ // validation or side effect (e.g. CC credentials Secret creation). An
+ // invalid name would otherwise reach K8s and its 422 would collapse to 500.
+ const nameIssue = validateResourceName(body.metadata?.name)
+ if (nameIssue) {
+ res.status(422).json(nameIssue)
+ return
+ }
+
+ // F0.3: identifier/display field validation for hosts + contexts (create =
+ // no ratchet; every present field is validated).
+ if ((plural === 'hosts' || plural === 'contexts') && body.spec) {
+ const fieldIssues = collectResourceSpecFieldIssues(plural, body.spec, null)
+ if (fieldIssues.length > 0) {
+ res.status(422).json({ errors: fieldIssues })
+ return
+ }
+ }
+
if (plural === 'communicationchannels' && body.spec) {
const errors = validateCommunicationChannelSpec(body.spec)
if (errors.length > 0) {
@@ -460,6 +480,30 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {
spec: Record<string, unknown>
}
+ // F0.3 RATCHET: for hosts + contexts, validate an identifier/display field
+ // ONLY IF its value changed vs the current CR, so a legacy resource whose
+ // spec.host / contextId is out of norm is never blocked for other edits.
+ if ((plural === 'hosts' || plural === 'contexts') && body.spec) {
+ let currentSpec: Record<string, unknown> | null = null
+ try {
+ const current = (await gateway.getResource(plural, req.params.name, ns)) as {
+ spec?: Record<string, unknown>
+ } | null
+ currentSpec = recordValue(current?.spec)
+ } catch (err) {
+ // Missing resource: fall through with currentSpec=null (validate every
+ // present field). The subsequent updateResource surfaces the real 404.
+ // getResource wraps a namespaced 404 as K8sNotFoundError (httpStatus),
+ // which extractK8sStatusCode does not read, so check both.
+ if (!(err instanceof K8sNotFoundError) && extractK8sStatusCode(err) !== 404) throw err
+ }
+ const fieldIssues = collectResourceSpecFieldIssues(plural, body.spec, currentSpec)
+ if (fieldIssues.length > 0) {
+ res.status(422).json({ errors: fieldIssues })
+ return
+ }
+ }
+
if (plural === 'communicationchannels' && body.spec) {
const errors = validateCommunicationChannelSpec(body.spec)
if (errors.length > 0) {
diff --git a/control-api/test/routes.resources.test.ts b/control-api/test/routes.resources.test.ts
index a0daa3bf9..ec45956b8 100644
--- a/control-api/test/routes.resources.test.ts
+++ b/control-api/test/routes.resources.test.ts
@@ -1207,3 +1207,199 @@ describe('routes/resources — Host secretRef anti-spoofing', () => {
expect(res.body.errors[0].field).toBe('spec.secretRef')
})
})
+
+describe('routes/resources — metadata.name validation (FIX-A1 / UT-1)', () => {
+ function makeApp(gateway: MockGateway) {
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminResourcesRouter(gateway as never))
+ return app
+ }
+
+ const PLURALS = ['hosts', 'contexts', 'communication-channels', 'mcp-servers'] as const
+
+ it('accepts an RFC1123 metadata.name for all 4 plurals (201)', async () => {
+ for (const plural of PLURALS) {
+ const gateway = new MockGateway('mcp-host')
+ await request(makeApp(gateway))
+ .post(`/admin/${plural}`)
+ .send({ metadata: { name: 'sales-agent' }, spec: {} })
+ .expect(201)
+ }
+ })
+
+ it('rejects a metadata.name with spaces+capitals with 422 invalid_name for all 4 plurals', async () => {
+ for (const plural of PLURALS) {
+ const gateway = new MockGateway('mcp-host')
+ const res = await request(makeApp(gateway))
+ .post(`/admin/${plural}`)
+ .send({ metadata: { name: 'Sales Agent' }, spec: {} })
+ .expect(422)
+ expect(res.body.error).toBe('invalid_name')
+ expect(res.body.field).toBe('metadata.name')
+ expect(typeof res.body.message).toBe('string')
+ }
+ })
+
+ it('rejects the full invalid-name table with 422 invalid_name (hosts)', async () => {
+ const invalidNames = [
+ '', // empty
+ 'a'.repeat(64), // 64+ chars (max label length is 63)
+ '-x', // leading hyphen
+ 'x-', // trailing hyphen
+ 'UPPER', // uppercase
+ 'esp ace', // space
+ 'under_score', // underscore
+ 'dot.name', // dot
+ '\u{1F680}', // emoji
+ ]
+ for (const name of invalidNames) {
+ const gateway = new MockGateway('mcp-host')
+ const res = await request(makeApp(gateway))
+ .post('/admin/hosts')
+ .send({ metadata: { name }, spec: {} })
+ .expect(422)
+ expect(res.body.error).toBe('invalid_name')
+ expect(res.body.field).toBe('metadata.name')
+ }
+ })
+})
+
+describe('routes/resources — display & identifier spec validation (F0.3 / UT-6)', () => {
+ function makeApp(gateway: MockGateway) {
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminResourcesRouter(gateway as never))
+ return app
+ }
+
+ it('accepts a free-text display spec.host (spaces + capitals) on create (201)', async () => {
+ const gateway = new MockGateway('mcp-host')
+ await request(makeApp(gateway))
+ .post('/admin/hosts')
+ .send({
+ metadata: { name: 'product-agent' },
+ spec: { host: 'Product Agents', contextRef: 'c1' },
+ })
+ .expect(201)
+ })
+
+ it('rejects a spec.host longer than 120 chars (422)', async () => {
+ const gateway = new MockGateway('mcp-host')
+ const res = await request(makeApp(gateway))
+ .post('/admin/hosts')
+ .send({
+ metadata: { name: 'product-agent' },
+ spec: { host: 'x'.repeat(200), contextRef: 'c1' },
+ })
+ .expect(422)
+ expect(res.body.errors[0].field).toBe('spec.host')
+ })
+
+ it('rejects a spec.displayName with a control character on context create (422)', async () => {
+ const gateway = new MockGateway('mcp-server')
+ const res = await request(makeApp(gateway))
+ .post('/admin/contexts')
+ .send({
+ metadata: { name: 'my-context' },
+ spec: {
+ contextId: 'my-context',
+ mcpServers: [],
+ displayName: `bad${String.fromCharCode(7)}name`,
+ },
+ })
+ .expect(422)
+ expect(res.body.errors[0].field).toBe('spec.displayName')
+ })
+
+ it('accepts a free-text display spec.displayName (spaces + capitals) on context create (201)', async () => {
+ const gateway = new MockGateway('mcp-server')
+ await request(makeApp(gateway))
+ .post('/admin/contexts')
+ .send({
+ metadata: { name: 'my-context' },
+ spec: { contextId: 'my-context', mcpServers: [], displayName: 'My Context' },
+ })
+ .expect(201)
+ })
+
+ it('rejects a non-RFC1123 spec.contextId on context create (422)', async () => {
+ const gateway = new MockGateway('mcp-server')
+ const res = await request(makeApp(gateway))
+ .post('/admin/contexts')
+ .send({
+ metadata: { name: 'my-context' },
+ spec: { contextId: 'My Context', mcpServers: [] },
+ })
+ .expect(422)
+ expect(res.body.errors[0].field).toBe('spec.contextId')
+ })
+
+ it('accepts an RFC1123 spec.contextId on context create (201)', async () => {
+ const gateway = new MockGateway('mcp-server')
+ await request(makeApp(gateway))
+ .post('/admin/contexts')
+ .send({
+ metadata: { name: 'my-context' },
+ spec: { contextId: 'my-context', mcpServers: [] },
+ })
+ .expect(201)
+ })
+
+ it('ratchet: PUT of a legacy host with an out-of-norm spec.host, WITHOUT changing it, succeeds (200)', async () => {
+ const gateway = new MockGateway('mcp-host')
+ const legacyHost = 'x'.repeat(200)
+ // Seed a legacy CR directly (bypassing router validation) to simulate pre-existing bad data.
+ await gateway.createResource(
+ 'hosts',
+ { metadata: { name: 'legacy-host' }, spec: { host: legacyHost, contextRef: 'c1' } },
+ config.hostsNamespace
+ )
+ // Edit an unrelated field; spec.host is echoed unchanged.
+ await request(makeApp(gateway))
+ .put('/admin/hosts/legacy-host')
+ .send({ spec: { host: legacyHost, contextRef: 'c2' } })
+ .expect(200)
+ })
+
+ it('ratchet: PUT that changes spec.host to an invalid value is rejected (422)', async () => {
+ const gateway = new MockGateway('mcp-host')
+ await gateway.createResource(
+ 'hosts',
+ { metadata: { name: 'legacy-host' }, spec: { host: 'Fine Name', contextRef: 'c1' } },
+ config.hostsNamespace
+ )
+ const res = await request(makeApp(gateway))
+ .put('/admin/hosts/legacy-host')
+ .send({ spec: { host: 'y'.repeat(200), contextRef: 'c1' } })
+ .expect(422)
+ expect(res.body.errors[0].field).toBe('spec.host')
+ })
+
+ it('ratchet: PUT of a legacy context with an out-of-norm spec.contextId, WITHOUT changing it, succeeds (200)', async () => {
+ const gateway = new MockGateway('mcp-server')
+ await gateway.createResource(
+ 'contexts',
+ { metadata: { name: 'legacy-ctx' }, spec: { contextId: 'Legacy Ctx', mcpServers: [] } },
+ config.contextsNamespace
+ )
+ await request(makeApp(gateway))
+ .put('/admin/contexts/legacy-ctx')
+ .send({ spec: { contextId: 'Legacy Ctx', mcpServers: ['a'] } })
+ .expect(200)
+ })
+
+ it('ratchet: PUT that changes spec.contextId to an invalid value is rejected (422)', async () => {
+ const gateway = new MockGateway('mcp-server')
+ await gateway.createResource(
+ 'contexts',
+ { metadata: { name: 'legacy-ctx' }, spec: { contextId: 'legacy-ctx', mcpServers: [] } },
+ config.contextsNamespace
+ )
+ const res = await request(makeApp(gateway))
+ .put('/admin/contexts/legacy-ctx')
+ .send({ spec: { contextId: 'New Bad Id', mcpServers: [] } })
+ .expect(422)
+ expect(res.body.errors[0].field).toBe('spec.contextId')
+ })
+})