Skip to content

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

TypeScript

fix(hcc): skip no-op Host Role replaces

Alfredo Lopezddb3f450cd90
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index d25fd9e7f..ae4172910 100644
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.255",
+ "version": "0.1.256",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.255",
+ "version": "0.1.256",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index f2fa3361b..de345e343 100644
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.255",
+ "version": "0.1.256",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --git a/host-context-controller/src/__tests__/asApiserverRole.ts b/host-context-controller/src/__tests__/asApiserverRole.ts
new file mode 100644
index 000000000..5064b7813
--- /dev/null
+++ b/host-context-controller/src/__tests__/asApiserverRole.ts
@@ -0,0 +1,77 @@
+import { vi } from 'vitest'
+import type * as k8s from '@kubernetes/client-node'
+
+/**
+ * Recorded kube-apiserver GET of a namespaced Role (`kubectl get role -o json`
+ * shape), not a field list copied from the comparator. Stamp
+ * controller-owned name/labels/rules via `asApiserverRole`. Label keys are
+ * inserted in reverse author order so a byte-identical fixture cannot hide a
+ * missing canonicalize. Do not reconstruct rules from desired alone when
+ * asserting the read carried `rules` — the skip must see them or it fail-opens.
+ */
+export const RECORDED_ROLE: k8s.V1Role = {
+ apiVersion: 'rbac.authorization.k8s.io/v1',
+ kind: 'Role',
+ metadata: {
+ annotations: {
+ 'kubectl.kubernetes.io/last-applied-configuration': '{}',
+ },
+ creationTimestamp: new Date('2026-04-01T00:00:00.000Z'),
+ generation: 1,
+ managedFields: [
+ {
+ apiVersion: 'rbac.authorization.k8s.io/v1',
+ fieldsType: 'FieldsV1',
+ fieldsV1: { 'f:rules': {} },
+ manager: 'kube-apiserver',
+ operation: 'Update',
+ time: new Date('2026-04-01T00:00:00.000Z'),
+ },
+ ],
+ name: 'recorded-role',
+ namespace: 'recorded-ns',
+ resourceVersion: '1784167',
+ uid: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
+ selfLink: '/apis/rbac.authorization.k8s.io/v1/namespaces/recorded-ns/roles/recorded-role',
+ labels: {
+ 'clerum.io/host': 'recorded',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ rules: [],
+}
+
+function shuffleLabelKeys(labels: Record<string, string>): Record<string, string> {
+ const shuffled: Record<string, string> = {}
+ for (const key of Object.keys(labels).reverse()) {
+ shuffled[key] = labels[key]
+ }
+ return shuffled
+}
+
+export function asApiserverRole(desired: k8s.V1Role): k8s.V1Role {
+ const recorded = structuredClone(RECORDED_ROLE)
+ const labels = desired.metadata?.labels ?? {}
+ return {
+ ...recorded,
+ metadata: {
+ ...recorded.metadata,
+ name: desired.metadata?.name,
+ namespace: desired.metadata?.namespace,
+ labels: shuffleLabelKeys({ ...labels }),
+ annotations: {
+ ...recorded.metadata?.annotations,
+ ...desired.metadata?.annotations,
+ },
+ ownerReferences: desired.metadata?.ownerReferences,
+ selfLink: `/apis/rbac.authorization.k8s.io/v1/namespaces/${desired.metadata?.namespace}/roles/${desired.metadata?.name}`,
+ },
+ rules: structuredClone(desired.rules ?? []),
+ }
+}
+
+export function updatedRoleLogs(log: ReturnType<typeof vi.spyOn>, needle: string): string[] {
+ return log.mock.calls
+ .map((call: unknown[]) => String(call[0]))
+ .filter((line: string) => line.includes('Updated Role') && line.includes(needle))
+}
diff --git a/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts b/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
new file mode 100644
index 000000000..1f2a0ff2d
--- /dev/null
+++ b/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
@@ -0,0 +1,108 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type * as k8s from '@kubernetes/client-node'
+import {
+ type MockRbacApi,
+ asAppsApi,
+ asCoreApi,
+ asCustomApi,
+ asNetworkingApi,
+ asRbacApi,
+ createMockAppsApi,
+ createMockCoreApi,
+ createMockCustomApi,
+ createMockNetworkingApi,
+ createMockRbacApi,
+} from '../../test/__fixtures__/testMocks'
+import { HostReconciler } from '../hostReconciler'
+import type { HostCRD } from '../types'
+import { asApiserverRole, updatedRoleLogs } from './asApiserverRole'
+
+function makeStubKc(): k8s.KubeConfig {
+ const stub = new Proxy({}, { get: () => vi.fn() })
+ return { makeApiClient: () => stub } as unknown as k8s.KubeConfig
+}
+
+function makeHost(secretRef = 'secret'): HostCRD {
+ return {
+ name: 'chatllm',
+ namespace: 'mcp-host',
+ uid: 'chatllm-uid',
+ spec: {
+ host: 'chatllm',
+ contextRef: 'ctx',
+ secretRef,
+ },
+ }
+}
+
+function desiredFromCreate(rbacApi: MockRbacApi): k8s.V1Role {
+ const body = rbacApi.createNamespacedRole.mock.calls[0][0].body as k8s.V1Role
+ expect(body.rules?.length).toBeGreaterThan(0)
+ return body
+}
+
+describe('Host ensureHostRole no-op gate', () => {
+ let rbacApi: MockRbacApi
+ let reconciler: HostReconciler
+ const host = makeHost()
+
+ beforeEach(() => {
+ rbacApi = createMockRbacApi()
+ reconciler = new HostReconciler(makeStubKc(), {
+ coreApi: asCoreApi(createMockCoreApi()),
+ appsApi: asAppsApi(createMockAppsApi()),
+ networkingApi: asNetworkingApi(createMockNetworkingApi()),
+ rbacApi: asRbacApi(rbacApi),
+ customApi: asCustomApi(createMockCustomApi()),
+ })
+ })
+
+ it('CREATE-ROLE-1: successful create never reads or replaces', async () => {
+ await (reconciler as any).ensureHostRole(host)
+ expect(rbacApi.createNamespacedRole).toHaveBeenCalledOnce()
+ expect(rbacApi.readNamespacedRole).not.toHaveBeenCalled()
+ expect(rbacApi.replaceNamespacedRole).not.toHaveBeenCalled()
+ })
+
+ it('NOOP-ROLE-1: apiserver-shaped Role with shuffled label keys skips replace', async () => {
+ rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
+ rbacApi.readNamespacedRole.mockImplementation(() => {
+ const existing = asApiserverRole(desiredFromCreate(rbacApi))
+ expect(existing.rules?.length).toBeGreaterThan(0)
+ return Promise.resolve(existing)
+ })
+ const log = vi.spyOn(console, 'log')
+ try {
+ await (reconciler as any).ensureHostRole(host)
+ expect(rbacApi.replaceNamespacedRole).not.toHaveBeenCalled()
+ expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([])
+ } finally {
+ log.mockRestore()
+ }
+ })
+
+ it('NOOP-ROLE-2: rotated secretRef still replaces once', async () => {
+ rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
+ rbacApi.readNamespacedRole.mockImplementation(() => {
+ const live = structuredClone(desiredFromCreate(rbacApi))
+ const secretRule = live.rules?.find(
+ (rule: k8s.V1PolicyRule) => rule.resources?.[0] === 'secrets' && rule.verbs?.includes('get')
+ )
+ expect(secretRule?.resourceNames?.[0]).toBe('rotated-secret')
+ secretRule!.resourceNames![0] = host.spec.secretRef
+ const existing = asApiserverRole(live)
+ expect(existing.rules?.length).toBeGreaterThan(0)
+ return Promise.resolve(existing)
+ })
+ const log = vi.spyOn(console, 'log')
+ try {
+ await (reconciler as any).ensureHostRole(makeHost('rotated-secret'))
+ expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
+ expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([
+ '[HostReconciler] Updated Role "host-chatllm-config-reader"',
+ ])
+ } finally {
+ log.mockRestore()
+ }
+ })
+})
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 9d42f94d7..f5fbf95c5 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -952,6 +952,7 @@ export class HostReconciler {
// Already exists — replace to pick up rotated secretRef / new resourceNames.
try {
const existing = await this.rbacApi.readNamespacedRole({ name, namespace: host.namespace })
+ if (roleMatchesDesired(body, existing)) return
body.metadata!.resourceVersion = existing.metadata?.resourceVersion
await this.rbacApi.replaceNamespacedRole({ name, namespace: host.namespace, body })
console.log(`[HostReconciler] Updated Role "${name}"`)
@@ -4656,6 +4657,38 @@ export class HostReconciler {
* ignored. Pod-template annotations are merged by preserveDeploymentAnnotations
* before this comparison.
*/
+/**
+ * True when the desired Role matches the live object on the fields HCC authors:
+ * `rbacLabels` and `rules` in author order. Server metadata and annotations are
+ * ignored — the builder does not write annotations, and comparing them would
+ * force a PUT. Label keys are canonicalized; rules, verbs, and resourceNames
+ * are not sorted. Missing rules or labels, or any compare failure, returns
+ * false (fail-open-to-write, #307).
+ */
+function roleMatchesDesired(desired: k8s.V1Role, existing: k8s.V1Role): boolean {
+ try {
+ if (!desired.rules || !existing.rules) return false
+ if (!desired.metadata?.labels || !existing.metadata?.labels) return false
+ if (
+ JSON.stringify(canonicalizeLabelKeys(desired.metadata.labels)) !==
+ JSON.stringify(canonicalizeLabelKeys(existing.metadata.labels))
+ ) {
+ return false
+ }
+ return JSON.stringify(desired.rules) === JSON.stringify(existing.rules)
+ } catch {
+ return false
+ }
+}
+
+function canonicalizeLabelKeys(labels: Record<string, string>): Record<string, string> {
+ const canonical: Record<string, string> = {}
+ for (const key of Object.keys(labels).sort()) {
+ canonical[key] = labels[key]
+ }
+ return canonical
+}
+
function deploymentMatchesDesired(desired: k8s.V1Deployment, existing: k8s.V1Deployment): boolean {
return (
JSON.stringify(normalizeDeploymentForComparison(desired)) ===