Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): reject silently pruned context displayName (R1-M6)
Diego Zacariase984ebb10507
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex e580496e1..7a68d2d8d 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.439",+ "version": "0.1.440","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.439",+ "version": "0.1.440","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.jsonindex cde104553..caddbdcb8 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.439",+ "version": "0.1.440","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/resources.ts b/control-api/src/routes/admin/resources.tsindex 7fa6bb489..fff233e27 100644--- a/control-api/src/routes/admin/resources.ts+++ b/control-api/src/routes/admin/resources.ts@@ -150,6 +150,72 @@ async function rollbackPrunedCommunicationChannelUpdate(}}+/**+ * Deploy-order guard for the additive context `spec.displayName` field (PR #304).+ *+ * `spec.displayName` is a new, optional, additive field on the context CRD. If a+ * create/update carries a non-empty `spec.displayName` but the CRD applied to+ * the cluster does NOT yet declare the field (deploy-order skew: control-ui+ * writes the field before the CRD update lands), the apiserver PRUNES the+ * unknown field SILENTLY and returns success — the display name is lost with no+ * error surfaced to the operator.+ *+ * This is a pure read-after-write check: it compares the value the caller sent+ * against the object the apiserver actually persisted. A create/replace returns+ * the persisted object AFTER pruning, so this reuses that response with NO extra+ * apiserver read (preserving the N1 single-read-per-PUT optimization).+ *+ * STRICTLY SCOPED to `contexts` + `spec.displayName` — the only additive field+ * at pruning risk in this PR. Do NOT generalize to other fields or resources:+ * that would be a decision module (which fields, precedence) requiring its own+ * mini-spec, not a one-field hardening net.+ */+function contextDisplayNameNotPersisted(+ requestedSpec: Record<string, unknown>,+ persisted: unknown+): boolean {+ const requested = requestedSpec.displayName+ // Only fire when the caller actually asked for a non-empty display name.+ if (typeof requested !== 'string' || requested.trim() === '') return false+ const persistedSpec = recordValue((persisted as { spec?: unknown } | null)?.spec) || {}+ // Missing (pruned) OR differs from what was sent — either way it did not+ // round-trip. displayName is stored verbatim (free text, no server-side+ // normalization), so a mismatch here means loss, not transformation.+ return persistedSpec.displayName !== requested+}++function sendPrunedDisplayNameError(res: Response): void {+ console.warn('[Admin] Context spec.displayName was pruned by the apiserver (CRD outdated)')+ res.status(409).json({+ code: 'context_crd_outdated',+ error:+ 'Context spec.displayName was not persisted by Kubernetes; the context CRD does not ' ++ 'support spec.displayName. Apply the latest clerum-crds (which add spec.displayName) ' ++ 'before setting a display name.',+ })+}++/**+ * Best-effort rollback of a context whose create silently dropped+ * `spec.displayName`. Unlike the update path, a POST is NOT idempotent: leaving+ * the pruned context in place would make the operator's retry (after applying+ * the CRD) collide with a 409 AlreadyExists. Deleting it restores a clean retry+ * path. Mirrors rollbackPrunedCommunicationChannelCreate.+ */+async function rollbackPrunedContextCreate(+ gateway: K8sGateway,+ name: string,+ namespace: string+): Promise<void> {+ try {+ await gateway.deleteResource('contexts', name, namespace)+ } catch (err) {+ console.warn(+ `[Admin] context pruned-displayName rollback failed for "${name}": ${err instanceof Error ? err.message : String(err)}`+ )+ }+}+/*** Return true if the CC spec has at least one non-empty provider array* (telegram, slack, teams, or email). These are the providers that require a@@ -458,6 +524,15 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {return}}+ if (+ plural === 'contexts' &&+ body.spec &&+ contextDisplayNameNotPersisted(body.spec, created)+ ) {+ await rollbackPrunedContextCreate(gateway, body.metadata.name, ns)+ sendPrunedDisplayNameError(res)+ return+ }res.status(201).json(created)}))@@ -594,6 +669,20 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {return}}+ if (+ plural === 'contexts' &&+ body.spec &&+ contextDisplayNameNotPersisted(body.spec, updated)+ ) {+ // Deliberately NO spec restore (unlike the CC update rollback): the+ // context's other spec fields persisted legitimately, and a PUT is+ // idempotent — once the operator applies the CRD and replays the same+ // request, spec.displayName round-trips and the whole spec converges.+ // Restoring the prior spec would instead discard those legitimate+ // edits. The loud 409 is the recovery signal.+ sendPrunedDisplayNameError(res)+ return+ }res.status(200).json(updated)} catch (err) {// AP-6: the caller sent the resourceVersion it read and the resourcediff --git a/control-api/test/routes.resources.contextDisplayNamePruning.test.ts b/control-api/test/routes.resources.contextDisplayNamePruning.test.tsnew file mode 100644index 000000000..514fcf8b3--- /dev/null+++ b/control-api/test/routes.resources.contextDisplayNamePruning.test.ts@@ -0,0 +1,196 @@+import { describe, expect, it, vi } from 'vitest'+import express from 'express'+import request from 'supertest'+import { config } from '../src/config.js'+import { createAdminResourcesRouter } from '../src/routes/admin/resources.js'+import { ResourceService } from '../src/services/resourceService.js'++// R1-M6 — deploy-order guard against silent pruning of the additive context+// `spec.displayName` field (PR #304).+//+// The productor real is the K8s apiserver: on a create/replace it returns the+// object AFTER pruning unknown fields. We reproduce that behaviour at the+// apiserver boundary (customApi.{create,replace}NamespacedCustomObject) through+// the REAL ResourceService — NOT with a hand-written fixture — so the object the+// route inspects is exactly the shape an outdated CRD would emit: a persisted+// context whose `spec.displayName` was silently dropped even though the request+// carried it.+//+// This mirrors the N1 test's real-service-against-a-customApi-spy pattern.+function realServiceGateway(opts: { pruneDisplayName: boolean }): {+ gateway: {+ getResource: ResourceService['getResource']+ updateResource: ResourceService['updateResource']+ createResource: ResourceService['createResource']+ deleteResource: ResourceService['deleteResource']+ }+ store: Map<string, Record<string, unknown>>+ deleteNamespacedCustomObject: ReturnType<typeof vi.fn>+} {+ const ns = config.contextsNamespace+ let rv = 0+ const store = new Map<string, Record<string, unknown>>()++ // Simulate the apiserver of an OUTDATED CRD: it does not know+ // `spec.displayName`, so it prunes it before persisting.+ const persistWithPruning = (body: Record<string, unknown>): Record<string, unknown> => {+ if (!opts.pruneDisplayName) return body+ const spec = { ...(body.spec as Record<string, unknown>) }+ delete spec.displayName+ return { ...body, spec }+ }++ const getNamespacedCustomObject = vi.fn(async ({ name }: { name: string }) => {+ const obj = store.get(name)+ if (!obj) {+ const err = new Error(`contexts/${name} not found`) as Error & { code: number }+ err.code = 404+ throw err+ }+ return obj+ })+ const replaceNamespacedCustomObject = vi.fn(+ async ({ name, body }: { name: string; body: Record<string, unknown> }) => {+ const persisted = persistWithPruning(body)+ const stored = {+ ...persisted,+ metadata: {+ ...(persisted.metadata as Record<string, unknown>),+ resourceVersion: String(++rv),+ },+ }+ store.set(name, stored)+ return stored+ }+ )+ const createNamespacedCustomObject = vi.fn(+ async ({ body }: { body: Record<string, unknown> & { metadata: { name: string } } }) => {+ const persisted = persistWithPruning(body)+ const stored = {+ ...persisted,+ metadata: {+ ...(persisted.metadata as Record<string, unknown>),+ resourceVersion: String(++rv),+ },+ }+ store.set(body.metadata.name, stored)+ return stored+ }+ )+ const deleteNamespacedCustomObject = vi.fn(async ({ name }: { name: string }) => {+ const existed = store.delete(name)+ return { deleted: existed }+ })++ const customApi = {+ getNamespacedCustomObject,+ replaceNamespacedCustomObject,+ createNamespacedCustomObject,+ deleteNamespacedCustomObject,+ } as unknown as ConstructorParameters<typeof ResourceService>[0]+ const svc = new ResourceService(customApi, ns, { contexts: ns })+ const gateway = {+ getResource: svc.getResource.bind(svc),+ updateResource: svc.updateResource.bind(svc),+ createResource: svc.createResource.bind(svc),+ deleteResource: svc.deleteResource.bind(svc),+ }+ return { gateway, store, deleteNamespacedCustomObject }+}++function makeApp(gateway: ReturnType<typeof realServiceGateway>['gateway']): express.Express {+ const app = express()+ app.use(express.json())+ app.use(createAdminResourcesRouter(gateway as never))+ return app+}++describe('routes/resources — context spec.displayName deploy-order guard (R1-M6)', () => {+ it('rejects a create whose spec.displayName the apiserver pruned (409) and rolls back the orphan', async () => {+ const { gateway, store } = realServiceGateway({ pruneDisplayName: true })+ const app = makeApp(gateway)++ const res = await request(app)+ .post('/admin/contexts')+ .send({+ metadata: { name: 'ctx-display' },+ spec: { contextId: 'ctx-display', mcpServers: [], displayName: 'My Context' },+ })+ .expect(409)++ // Observable result (T4): the operator gets a machine-readable error, not a+ // 200 with the display name silently gone.+ expect(res.body.code).toBe('context_crd_outdated')+ expect(res.body.error).toContain('spec.displayName')+ // The orphan context (created before the guard fired) was rolled back, so a+ // retry after the CRD is applied does not collide with AlreadyExists.+ expect(store.has('ctx-display')).toBe(false)+ })++ it('accepts a create whose spec.displayName round-trips (201)', async () => {+ const { gateway } = realServiceGateway({ pruneDisplayName: false })+ const app = makeApp(gateway)++ const res = await request(app)+ .post('/admin/contexts')+ .send({+ metadata: { name: 'ctx-display' },+ spec: { contextId: 'ctx-display', mcpServers: [], displayName: 'My Context' },+ })+ .expect(201)++ expect(res.body.spec.displayName).toBe('My Context')+ })++ it('rejects an update whose spec.displayName the apiserver pruned (409)', async () => {+ const { gateway } = realServiceGateway({ pruneDisplayName: true })+ // Seed a context WITHOUT displayName so the create itself does not trip the+ // guard; the loss happens on the subsequent PUT that adds displayName.+ await gateway.createResource(+ 'contexts',+ { metadata: { name: 'ctx-display' }, spec: { contextId: 'ctx-display', mcpServers: [] } },+ config.contextsNamespace+ )+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/contexts/ctx-display')+ .send({ spec: { contextId: 'ctx-display', mcpServers: [], displayName: 'My Context' } })+ .expect(409)++ expect(res.body.code).toBe('context_crd_outdated')+ expect(res.body.error).toContain('spec.displayName')+ })++ it('accepts an update whose spec.displayName round-trips (200)', async () => {+ const { gateway } = realServiceGateway({ pruneDisplayName: false })+ await gateway.createResource(+ 'contexts',+ { metadata: { name: 'ctx-display' }, spec: { contextId: 'ctx-display', mcpServers: [] } },+ config.contextsNamespace+ )+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/contexts/ctx-display')+ .send({ spec: { contextId: 'ctx-display', mcpServers: [], displayName: 'My Context' } })+ .expect(200)++ expect(res.body.spec.displayName).toBe('My Context')+ })++ it('does not fire when the request omits spec.displayName (200, no false positive)', async () => {+ const { gateway } = realServiceGateway({ pruneDisplayName: true })+ await gateway.createResource(+ 'contexts',+ { metadata: { name: 'ctx-nodisplay' }, spec: { contextId: 'ctx-nodisplay', mcpServers: [] } },+ config.contextsNamespace+ )+ const app = makeApp(gateway)++ await request(app)+ .put('/admin/contexts/ctx-nodisplay')+ .send({ spec: { contextId: 'ctx-nodisplay', mcpServers: ['a'] } })+ .expect(200)+ })+})