Skip to content

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

TypeScript

fix(hcc): canonicalize Role rule object keys before skip compare

Alfredo Lopezf6a2a1576dd7
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index b8019e259..6bf7bdca1 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.257",
+ "version": "0.1.258",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.257",
+ "version": "0.1.258",
"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 9a4977f96..e041cde2c 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.257",
+ "version": "0.1.258",
"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
index 5064b7813..126c470f6 100644
--- a/host-context-controller/src/__tests__/asApiserverRole.ts
+++ b/host-context-controller/src/__tests__/asApiserverRole.ts
@@ -5,9 +5,9 @@ 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.
+ * inserted in reverse author order, and each rule is rebuilt in
+ * V1PolicyRule.attributeTypeMap order, so a byte-identical fixture cannot hide
+ * a missing canonicalize. The skip must still see `rules` or it fail-opens.
*/
export const RECORDED_ROLE: k8s.V1Role = {
apiVersion: 'rbac.authorization.k8s.io/v1',
@@ -49,6 +49,20 @@ function shuffleLabelKeys(labels: Record<string, string>): Record<string, string
return shuffled
}
+/**
+ * Rebuild a rule in client-node ObjectSerializer / V1PolicyRule.attributeTypeMap
+ * order so a missing key-canonicalize cannot hide behind a cloned builder object.
+ */
+export function asApiserverPolicyRule(rule: k8s.V1PolicyRule): k8s.V1PolicyRule {
+ const live: Record<string, unknown> = {}
+ if (rule.apiGroups !== undefined) live.apiGroups = rule.apiGroups
+ if (rule.nonResourceURLs !== undefined) live.nonResourceURLs = rule.nonResourceURLs
+ if (rule.resourceNames !== undefined) live.resourceNames = rule.resourceNames
+ if (rule.resources !== undefined) live.resources = rule.resources
+ if (rule.verbs !== undefined) live.verbs = rule.verbs
+ return live as unknown as k8s.V1PolicyRule
+}
+
export function asApiserverRole(desired: k8s.V1Role): k8s.V1Role {
const recorded = structuredClone(RECORDED_ROLE)
const labels = desired.metadata?.labels ?? {}
@@ -66,7 +80,7 @@ export function asApiserverRole(desired: k8s.V1Role): k8s.V1Role {
ownerReferences: desired.metadata?.ownerReferences,
selfLink: `/apis/rbac.authorization.k8s.io/v1/namespaces/${desired.metadata?.namespace}/roles/${desired.metadata?.name}`,
},
- rules: structuredClone(desired.rules ?? []),
+ rules: (desired.rules ?? []).map(asApiserverPolicyRule),
}
}
diff --git a/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts b/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
index 1f2a0ff2d..45bb2ddc3 100644
--- a/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
+++ b/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
@@ -36,9 +36,7 @@ function makeHost(secretRef = 'secret'): HostCRD {
}
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
+ return rbacApi.createNamespacedRole.mock.calls[0][0].body as k8s.V1Role
}
describe('Host ensureHostRole no-op gate', () => {
@@ -66,14 +64,23 @@ describe('Host ensureHostRole no-op gate', () => {
it('NOOP-ROLE-1: apiserver-shaped Role with shuffled label keys skips replace', async () => {
rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
+ let existing: k8s.V1Role | undefined
rbacApi.readNamespacedRole.mockImplementation(() => {
- const existing = asApiserverRole(desiredFromCreate(rbacApi))
- expect(existing.rules?.length).toBeGreaterThan(0)
+ existing = asApiserverRole(desiredFromCreate(rbacApi))
return Promise.resolve(existing)
})
const log = vi.spyOn(console, 'log')
try {
await (reconciler as any).ensureHostRole(host)
+ expect(rbacApi.readNamespacedRole).toHaveBeenCalledOnce()
+ expect(existing?.rules?.length).toBeGreaterThan(0)
+ expect(Object.keys(existing!.rules![0] ?? {})).toEqual([
+ 'apiGroups',
+ 'resourceNames',
+ 'resources',
+ 'verbs',
+ ])
+ expect(desiredFromCreate(rbacApi).rules?.length).toBeGreaterThan(0)
expect(rbacApi.replaceNamespacedRole).not.toHaveBeenCalled()
expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([])
} finally {
@@ -83,20 +90,20 @@ describe('Host ensureHostRole no-op gate', () => {
it('NOOP-ROLE-2: rotated secretRef still replaces once', async () => {
rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
+ let existing: k8s.V1Role | undefined
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)
+ existing = asApiserverRole(live)
return Promise.resolve(existing)
})
const log = vi.spyOn(console, 'log')
try {
await (reconciler as any).ensureHostRole(makeHost('rotated-secret'))
+ expect(existing?.rules?.length).toBeGreaterThan(0)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([
'[HostReconciler] Updated Role "host-chatllm-config-reader"',
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 42447a0c7..97e05a0d4 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -4652,9 +4652,12 @@ export class HostReconciler {
* 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).
+ * force a PUT. Label keys are canonicalized. Object keys inside each rule are
+ * also canonicalized: client-node rebuilds V1PolicyRule in attributeTypeMap
+ * order (resourceNames before resources), so a raw JSON.stringify never matches
+ * a live GET (#307). Rule arrays, verbs, and resourceNames stay in author order.
+ * Missing rules or labels, or any compare failure, returns false
+ * (fail-open-to-write).
*/
function roleMatchesDesired(desired: k8s.V1Role, existing: k8s.V1Role): boolean {
try {
@@ -4666,7 +4669,10 @@ function roleMatchesDesired(desired: k8s.V1Role, existing: k8s.V1Role): boolean
) {
return false
}
- return JSON.stringify(desired.rules) === JSON.stringify(existing.rules)
+ return (
+ JSON.stringify(canonicalizeRoleValue(desired.rules)) ===
+ JSON.stringify(canonicalizeRoleValue(existing.rules))
+ )
} catch {
return false
}
@@ -4680,6 +4686,18 @@ function canonicalizeLabelKeys(labels: Record<string, string>): Record<string, s
return canonical
}
+/** Sort object keys recursively. Arrays keep author order. */
+function canonicalizeRoleValue(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(canonicalizeRoleValue)
+ if (typeof value !== 'object' || value === null) return value
+ const canonical: Record<string, unknown> = {}
+ for (const key of Object.keys(value).sort()) {
+ const entry = (value as Record<string, unknown>)[key]
+ if (entry !== undefined) canonical[key] = canonicalizeRoleValue(entry)
+ }
+ return canonical
+}
+
/**
* Kubernetes persists server metadata and defaulted Deployment/PodSpec fields
* that HCC does not author. Remove only those known fields before comparing