Skip to content

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

TypeScript

fix(hcc): land jozer Role-skip review nits after #487

Alfredo Lopez0af923c4e723
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 4a7a1abf2..10b5eb217 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.261",
+ "version": "0.1.262",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.261",
+ "version": "0.1.262",
"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 c880b3031..c16855c1c 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.261",
+ "version": "0.1.262",
"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__/asApiserverNetworkPolicy.ts b/host-context-controller/src/__tests__/asApiserverNetworkPolicy.ts
index cced0c850..9fedb9333 100644
--- a/host-context-controller/src/__tests__/asApiserverNetworkPolicy.ts
+++ b/host-context-controller/src/__tests__/asApiserverNetworkPolicy.ts
@@ -1,5 +1,6 @@
import { vi } from 'vitest'
import type * as k8s from '@kubernetes/client-node'
+import { updatedLogs } from '../../test/__fixtures__/updatedLogs'
/**
* Recorded kube-apiserver GET of a NetworkPolicy after client-node decode
@@ -121,7 +122,5 @@ export function asApiserverNetworkPolicy(
}
export function updatedPolicyLogs(log: ReturnType<typeof vi.spyOn>, needle: string): string[] {
- return log.mock.calls
- .map((call: unknown[]) => String(call[0]))
- .filter((line: string) => line.includes('Updated') && line.includes(needle))
+ return updatedLogs(log, 'Updated', needle)
}
diff --git a/host-context-controller/src/__tests__/asApiserverRole.ts b/host-context-controller/src/__tests__/asApiserverRole.ts
index 449c2f3d9..c51578c0d 100644
--- a/host-context-controller/src/__tests__/asApiserverRole.ts
+++ b/host-context-controller/src/__tests__/asApiserverRole.ts
@@ -1,5 +1,6 @@
import { vi } from 'vitest'
import type * as k8s from '@kubernetes/client-node'
+import { updatedLogs } from '../../test/__fixtures__/updatedLogs'
/**
* Recorded kube-apiserver GET of a namespaced Role (`kubectl get role -o json`
@@ -56,37 +57,37 @@ function shuffleLabelKeys(labels: Record<string, string>): Record<string, string
*/
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
+ if (rule.apiGroups !== undefined) live.apiGroups = structuredClone(rule.apiGroups)
+ if (rule.nonResourceURLs !== undefined)
+ live.nonResourceURLs = structuredClone(rule.nonResourceURLs)
+ if (rule.resourceNames !== undefined) live.resourceNames = structuredClone(rule.resourceNames)
+ if (rule.resources !== undefined) live.resources = structuredClone(rule.resources)
+ if (rule.verbs !== undefined) live.verbs = structuredClone(rule.verbs)
return live as unknown as k8s.V1PolicyRule
}
export function asApiserverRole(desired: k8s.V1Role): k8s.V1Role {
+ const desiredClone = structuredClone(desired)
const recorded = structuredClone(RECORDED_ROLE)
- const labels = desired.metadata?.labels ?? {}
+ const labels = desiredClone.metadata?.labels ?? {}
return {
...recorded,
metadata: {
...recorded.metadata,
- name: desired.metadata?.name,
- namespace: desired.metadata?.namespace,
+ name: desiredClone.metadata?.name,
+ namespace: desiredClone.metadata?.namespace,
labels: shuffleLabelKeys({ ...labels }),
annotations: {
...recorded.metadata?.annotations,
- ...desired.metadata?.annotations,
+ ...desiredClone.metadata?.annotations,
},
- ownerReferences: desired.metadata?.ownerReferences,
- selfLink: `/apis/rbac.authorization.k8s.io/v1/namespaces/${desired.metadata?.namespace}/roles/${desired.metadata?.name}`,
+ ownerReferences: desiredClone.metadata?.ownerReferences,
+ selfLink: `/apis/rbac.authorization.k8s.io/v1/namespaces/${desiredClone.metadata?.namespace}/roles/${desiredClone.metadata?.name}`,
},
- rules: (desired.rules ?? []).map(asApiserverPolicyRule),
+ rules: (desiredClone.rules ?? []).map(asApiserverPolicyRule),
}
}
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))
+ return updatedLogs(log, 'Updated Role', needle)
}
diff --git a/host-context-controller/src/__tests__/asApiserverService.ts b/host-context-controller/src/__tests__/asApiserverService.ts
index 0ed36b51c..1e20ef67d 100644
--- a/host-context-controller/src/__tests__/asApiserverService.ts
+++ b/host-context-controller/src/__tests__/asApiserverService.ts
@@ -1,5 +1,6 @@
import { vi } from 'vitest'
import type * as k8s from '@kubernetes/client-node'
+import { updatedLogs } from '../../test/__fixtures__/updatedLogs'
/**
* Recorded kube-apiserver GET of a ClusterIP Service (`kubectl get svc -o json`
@@ -81,7 +82,5 @@ export function asApiserverService(
}
export function updatedServiceLogs(log: ReturnType<typeof vi.spyOn>, needle: string): string[] {
- return log.mock.calls
- .map((call: unknown[]) => String(call[0]))
- .filter((line: string) => line.includes('Updated') && line.includes(needle))
+ return updatedLogs(log, 'Updated', needle)
}
diff --git a/host-context-controller/src/__tests__/channelReaderServiceNoopGate.test.ts b/host-context-controller/src/__tests__/channelReaderServiceNoopGate.test.ts
index b3452ec28..3e090f275 100644
--- a/host-context-controller/src/__tests__/channelReaderServiceNoopGate.test.ts
+++ b/host-context-controller/src/__tests__/channelReaderServiceNoopGate.test.ts
@@ -12,16 +12,12 @@ import {
createMockCustomApi,
createMockNetworkingApi,
createMockRbacApi,
+ makeStubKc,
} from '../../test/__fixtures__/testMocks'
import { HostReconciler } from '../hostReconciler'
import type { HostCRD } from '../types'
import { asApiserverService, updatedServiceLogs } from './asApiserverService'
-function makeStubKc(): k8s.KubeConfig {
- const stub = new Proxy({}, { get: () => vi.fn() })
- return { makeApiClient: () => stub } as unknown as k8s.KubeConfig
-}
-
function makeHost(): HostCRD {
return {
name: 'chatllm',
diff --git a/host-context-controller/src/__tests__/hostNetworkPolicyNoopGate.test.ts b/host-context-controller/src/__tests__/hostNetworkPolicyNoopGate.test.ts
index 654ecbdb4..2fa4f8053 100644
--- a/host-context-controller/src/__tests__/hostNetworkPolicyNoopGate.test.ts
+++ b/host-context-controller/src/__tests__/hostNetworkPolicyNoopGate.test.ts
@@ -12,16 +12,12 @@ import {
createMockCustomApi,
createMockNetworkingApi,
createMockRbacApi,
+ makeStubKc,
} from '../../test/__fixtures__/testMocks'
import { HostReconciler } from '../hostReconciler'
import type { HostCRD } from '../types'
import { asApiserverNetworkPolicy } from './asApiserverNetworkPolicy'
-function makeStubKc(): k8s.KubeConfig {
- const stub = new Proxy({}, { get: () => vi.fn() })
- return { makeApiClient: () => stub } as unknown as k8s.KubeConfig
-}
-
function makeHost(): HostCRD {
return {
name: 'chatllm',
diff --git a/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts b/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
index 0a01930c3..9735bd350 100644
--- a/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
+++ b/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import * as k8s from '@kubernetes/client-node'
import { createHash } from 'crypto'
+import { makeStubKc } from '../../test/__fixtures__/testMocks'
import { config as hccConfig } from '../config'
import { HostReconciler, type ResolvedSfsMount } from '../hostReconciler'
import { issueMcpHostRuntimeTokens } from '../mcpHostRuntimeTokenIssuerClient'
@@ -39,21 +40,6 @@ vi.mock('../gfsHostBinding', () => ({
})),
}))
-// Stand-in KubeConfig that returns a stub for every makeApiClient — buildDeployment
-// is a pure function that doesn't touch the API but the constructor still resolves
-// these.
-function makeStubKc(): k8s.KubeConfig {
- const stub = new Proxy(
- {},
- {
- get: () => vi.fn(),
- }
- )
- return {
- makeApiClient: () => stub,
- } as unknown as k8s.KubeConfig
-}
-
function makeHost(): HostCRD {
return {
name: 'team-mission',
diff --git a/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts b/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
index 747fd12bf..a2b1cc7bd 100644
--- a/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
+++ b/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
@@ -13,17 +13,13 @@ import {
createMockCustomApi,
createMockNetworkingApi,
createMockRbacApi,
+ makeStubKc,
} from '../../test/__fixtures__/testMocks'
import { HOST_LABEL } from '../constants'
import { HostReconciler } from '../hostReconciler'
import type { HostCRD } from '../types'
import { asApiserverPolicyRule, 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',
@@ -90,6 +86,9 @@ describe('Host ensureHostRole no-op gate', () => {
expect(authoredKeys).toEqual(['apiGroups', 'resources', 'resourceNames', 'verbs'])
expect(liveKeys).toEqual(['apiGroups', 'resourceNames', 'resources', 'verbs'])
expect(authoredKeys).not.toEqual(liveKeys)
+ const authoredLabelKeys = Object.keys(desiredFromCreate(rbacApi).metadata?.labels ?? {})
+ const liveLabelKeys = Object.keys(existing!.metadata?.labels ?? {})
+ expect(authoredLabelKeys).not.toEqual(liveLabelKeys)
expect(desiredFromCreate(rbacApi).rules?.length).toBeGreaterThan(0)
expect(rbacApi.replaceNamespacedRole).not.toHaveBeenCalled()
expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([])
@@ -272,6 +271,25 @@ describe('Host ensureHostRole no-op gate', () => {
}
})
+ it('NOOP-ROLE-9: extra live admission label skips replace', async () => {
+ rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
+ let existing: k8s.V1Role | undefined
+ rbacApi.readNamespacedRole.mockImplementation(() => {
+ existing = asApiserverRole(desiredFromCreate(rbacApi))
+ existing.metadata!.labels!['argocd.argoproj.io/instance'] = 'clerum-dev'
+ return Promise.resolve(existing)
+ })
+ const log = vi.spyOn(console, 'log')
+ try {
+ await (reconciler as any).ensureHostRole(host)
+ expect(existing?.metadata?.labels?.['argocd.argoproj.io/instance']).toBe('clerum-dev')
+ expect(rbacApi.replaceNamespacedRole).not.toHaveBeenCalled()
+ expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([])
+ } finally {
+ log.mockRestore()
+ }
+ })
+
it('FIXTURE-ROLE-1: asApiserverPolicyRule follows V1PolicyRule.attributeTypeMap', () => {
expect(V1PolicyRule.getAttributeTypeMap().map(entry => entry.name)).toEqual([
'apiGroups',
diff --git a/host-context-controller/src/__tests__/hostServiceNoopGate.test.ts b/host-context-controller/src/__tests__/hostServiceNoopGate.test.ts
index 81fa7339a..b72c4561f 100644
--- a/host-context-controller/src/__tests__/hostServiceNoopGate.test.ts
+++ b/host-context-controller/src/__tests__/hostServiceNoopGate.test.ts
@@ -12,16 +12,12 @@ import {
createMockCustomApi,
createMockNetworkingApi,
createMockRbacApi,
+ makeStubKc,
} from '../../test/__fixtures__/testMocks'
import { HostReconciler } from '../hostReconciler'
import type { HostCRD } from '../types'
import { asApiserverService, updatedServiceLogs } from './asApiserverService'
-function makeStubKc(): k8s.KubeConfig {
- const stub = new Proxy({}, { get: () => vi.fn() })
- return { makeApiClient: () => stub } as unknown as k8s.KubeConfig
-}
-
function makeHost(): HostCRD {
return {
name: 'chatllm',
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 9b20b53f3..4e0fb01ac 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -56,6 +56,7 @@ import {
import {
applyNetworkPolicy,
canonicalStringify,
+ canonicalizeValue,
getErrorCode,
preserveDeploymentAnnotations,
preserveServiceAssignedFields,
@@ -4654,54 +4655,43 @@ 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. 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).
+ * `rbacLabels` and `rules`. Server metadata and annotations are ignored — the
+ * builder does not write annotations, and comparing them would force a PUT.
+ *
+ * Label comparison is a subset of the keys HCC authors. Extra live labels
+ * (Kyverno/Gatekeeper add-labels, ArgoCD instance, cost tags) must not force a
+ * PUT that strips them and re-enters the write loop. A missing or changed
+ * authored key still fail-opens to write, so a later third `rbacLabels` key
+ * still lands. `isHccOwnedHostResource` keys on the same two labels today.
+ *
+ * Object keys inside each rule are 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 {
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
+ const desiredLabels = desired.metadata?.labels
+ const existingLabels = existing.metadata?.labels
+ if (!desiredLabels || !existingLabels) return false
+ const authored: Record<string, string> = {}
+ const liveAuthored: Record<string, string> = {}
+ for (const key of Object.keys(desiredLabels)) {
+ if (existingLabels[key] === undefined) return false
+ authored[key] = desiredLabels[key]
+ liveAuthored[key] = existingLabels[key]
}
return (
- JSON.stringify(canonicalizeRoleValue(desired.rules)) ===
- JSON.stringify(canonicalizeRoleValue(existing.rules))
+ JSON.stringify(canonicalizeValue({ labels: authored, rules: desired.rules })) ===
+ JSON.stringify(canonicalizeValue({ labels: liveAuthored, rules: 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
-}
-
-/** 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
@@ -4837,7 +4827,7 @@ function normalizeDeploymentForComparison(deployment: k8s.V1Deployment): unknown
}
}
- return normalizeDeploymentValue(normalized)
+ return canonicalizeValue(normalized)
}
function normalizeContainerDefaults(container: k8s.V1Container): void {
@@ -4869,19 +4859,3 @@ function normalizeVolumeDefaults(volume: k8s.V1Volume): void {
delete volume.persistentVolumeClaim.readOnly
}
}
-
-function normalizeDeploymentValue(value: unknown): unknown {
- if (Array.isArray(value)) return value.map(normalizeDeploymentValue)
- if (!isDeploymentObject(value)) return value
-
- const normalized: Record<string, unknown> = {}
- for (const key of Object.keys(value).sort()) {
- const entry = value[key]
- if (entry !== undefined) normalized[key] = normalizeDeploymentValue(entry)
- }
- return normalized
-}
-
-function isDeploymentObject(value: unknown): value is Record<string, unknown> {
- return typeof value === 'object' && value !== null && !Array.isArray(value)
-}
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index 140e92bff..0f87d59b9 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -47,6 +47,7 @@ import {
} from './types'
import {
applyNetworkPolicy,
+ canonicalizeValue,
getErrorCode,
networkPolicyMatchesDesired,
replaceWithConflictRetry,
@@ -121,14 +122,7 @@ export function sameContextDesiredRevision(expected: ContextCRD, current: Contex
}
function canonicalizeNetworkPolicyValue(value: unknown): unknown {
- if (Array.isArray(value)) return value.map(canonicalizeNetworkPolicyValue)
- if (value === null || typeof value !== 'object') return value
- return Object.fromEntries(
- Object.entries(value as Record<string, unknown>)
- .filter(([, entry]) => entry !== undefined)
- .sort(([left], [right]) => left.localeCompare(right))
- .map(([key, entry]) => [key, canonicalizeNetworkPolicyValue(entry)])
- )
+ return canonicalizeValue(value)
}
function sameNetworkPolicySpec(
@@ -320,9 +314,9 @@ export function isAllowedExternalEgressCidr(cidr: string): boolean {
}
/**
- * Recursively canonicalize a value: sort every object's keys while preserving
- * array order. Used to compare policy egress without JSON.stringify key-order
- * fragility.
+ * egressSignature walker: deep key-sort, keep undefined-valued keys.
+ * Distinct from `canonicalizeValue` (no-op gates drop undefined). Do not fold
+ * this into the shared helper (#299 / #473).
*/
function canonicalize(value: unknown): unknown {
if (Array.isArray(value)) return value.map(canonicalize)
diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.ts
index f82d3459f..1a82991e3 100644
--- a/host-context-controller/src/utils.ts
+++ b/host-context-controller/src/utils.ts
@@ -236,23 +236,7 @@ function normalizeServiceForComparison(service: k8s.V1Service): unknown {
}
}
- return normalizeServiceValue(normalized)
-}
-
-function normalizeServiceValue(value: unknown): unknown {
- if (Array.isArray(value)) return value.map(normalizeServiceValue)
- if (!isServiceObject(value)) return value
-
- const normalized: Record<string, unknown> = {}
- for (const key of Object.keys(value).sort()) {
- const entry = value[key]
- if (entry !== undefined) normalized[key] = normalizeServiceValue(entry)
- }
- return normalized
-}
-
-function isServiceObject(value: unknown): value is Record<string, unknown> {
- return typeof value === 'object' && value !== null && !Array.isArray(value)
+ return canonicalizeValue(normalized)
}
/**
@@ -296,7 +280,7 @@ function normalizeNetworkPolicyForComparison(policy: k8s.V1NetworkPolicy): unkno
}
}
- return normalizeServiceValue(normalized)
+ return canonicalizeValue(normalized)
}
/** Create-or-replace a NetworkPolicy (409 catch → conflict-retry replace). */
@@ -331,6 +315,27 @@ export async function applyNetworkPolicy(
})
}
+/**
+ * Recursive key-sort used by the no-op gates (Role, Service, Deployment,
+ * NetworkPolicy apply). Arrays keep author order. Undefined-valued keys are
+ * dropped. A second copy of this walk is a #307-class drift: the skip would
+ * silently stop matching.
+ *
+ * Distinct from `canonicalStringify` (top-level Secret key list) and from the
+ * egressSignature walker in networkPolicyReconciler, which keeps undefined
+ * keys. Do not unify those (#473 / #299).
+ */
+export function canonicalizeValue(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(canonicalizeValue)
+ 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] = canonicalizeValue(entry)
+ }
+ return canonical
+}
+
/**
* Stable JSON for hashing: object keys are emitted in sorted order, so the
* digest of a Secret's data depends on its content and not on the order the
diff --git a/host-context-controller/test/__fixtures__/testMocks.ts b/host-context-controller/test/__fixtures__/testMocks.ts
index a69108be8..478bd5b90 100644
--- a/host-context-controller/test/__fixtures__/testMocks.ts
+++ b/host-context-controller/test/__fixtures__/testMocks.ts
@@ -290,3 +290,9 @@ export function asNetworkingApi(mock: MockNetworkingApi): k8s.NetworkingV1Api {
export function asRbacApi(mock: MockRbacApi): k8s.RbacAuthorizationV1Api {
return mock as unknown as k8s.RbacAuthorizationV1Api
}
+
+/** Constructor-only KubeConfig: every makeApiClient returns an empty stub. */
+export function makeStubKc(): k8s.KubeConfig {
+ const stub = new Proxy({}, { get: () => vi.fn() })
+ return { makeApiClient: () => stub } as unknown as k8s.KubeConfig
+}
diff --git a/host-context-controller/test/__fixtures__/updatedLogs.ts b/host-context-controller/test/__fixtures__/updatedLogs.ts
new file mode 100644
index 000000000..eb765dcb1
--- /dev/null
+++ b/host-context-controller/test/__fixtures__/updatedLogs.ts
@@ -0,0 +1,8 @@
+import { vi } from 'vitest'
+
+/** Shared log filter for the no-op-gate suites. Every needle must match. */
+export function updatedLogs(log: ReturnType<typeof vi.spyOn>, ...needles: string[]): string[] {
+ return log.mock.calls
+ .map((call: unknown[]) => String(call[0]))
+ .filter((line: string) => needles.every(needle => line.includes(needle)))
+}
diff --git a/host-context-controller/test/hostReconciler.test.ts b/host-context-controller/test/hostReconciler.test.ts
index b8347b82e..5a2650808 100644
--- a/host-context-controller/test/hostReconciler.test.ts
+++ b/host-context-controller/test/hostReconciler.test.ts
@@ -1025,7 +1025,24 @@ describe('HostReconciler — per-Host RBAC scaffolding', () => {
it('rewrites Role resourceNames when spec.secretRef changes (replace path)', async () => {
const { reconciler, rbacApi } = createReconciler()
rbacApi.createNamespacedRole.mockRejectedValueOnce({ code: 409 })
- rbacApi.readNamespacedRole.mockResolvedValue({ metadata: { resourceVersion: '7' } })
+ rbacApi.readNamespacedRole.mockImplementation(async () => {
+ const desired = rbacApi.createNamespacedRole.mock.calls[0][0].body as {
+ metadata?: { labels?: Record<string, string> }
+ rules?: Array<{ resources?: string[]; verbs?: string[]; resourceNames?: string[] }>
+ }
+ const live = structuredClone(desired)
+ const secretRule = live.rules?.find(
+ rule => rule.resources?.[0] === 'secrets' && rule.verbs?.includes('get')
+ )
+ if (!secretRule?.resourceNames) {
+ throw new Error('expected the created Role to carry a secrets get rule')
+ }
+ secretRule.resourceNames[0] = 'host-secret'
+ return {
+ ...live,
+ metadata: { ...live.metadata, resourceVersion: '7' },
+ }
+ })
await reconciler.reconcile(makeHost({ spec: { secretRef: 'rotated-secret' } } as never))
@@ -1045,6 +1062,17 @@ describe('HostReconciler — per-Host RBAC scaffolding', () => {
expect(replaced.metadata.resourceVersion).toBe('7')
})
+ it('replaces a live Role that has no rules (fail-open-to-write)', async () => {
+ const { reconciler, rbacApi } = createReconciler()
+ rbacApi.createNamespacedRole.mockRejectedValueOnce({ code: 409 })
+ rbacApi.readNamespacedRole.mockResolvedValue({ metadata: { resourceVersion: '7' } })
+
+ await reconciler.reconcile(makeHost({ spec: { secretRef: 'rotated-secret' } } as never))
+
+ expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledTimes(1)
+ expect(rbacApi.replaceNamespacedRole.mock.calls[0][0].body.metadata.resourceVersion).toBe('7')
+ })
+
it('cleans up RBAC on reconcileDelete', async () => {
const { reconciler, coreApi, rbacApi } = createReconciler()
await reconciler.reconcileDelete('alpha-host', 'mcp-host')
diff --git a/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts b/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts
index f8696e57e..731d44bbe 100644
--- a/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts
+++ b/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts
@@ -15,10 +15,13 @@ vi.mock('../src/config', () => ({
},
}))
-vi.mock('../src/utils', () => ({
- getErrorCode: (err: any) => err?.code,
- applyNetworkPolicy: vi.fn().mockResolvedValue(undefined),
-}))
+vi.mock('../src/utils', async importOriginal => {
+ const actual = await importOriginal<typeof import('../src/utils')>()
+ return {
+ ...actual,
+ applyNetworkPolicy: vi.fn().mockResolvedValue(undefined),
+ }
+})
const mockApply = vi.mocked(applyNetworkPolicy)
diff --git a/host-context-controller/test/networkPolicyReconciler.minimalInfra.test.ts b/host-context-controller/test/networkPolicyReconciler.minimalInfra.test.ts
index 04e7b3b33..346476c38 100644
--- a/host-context-controller/test/networkPolicyReconciler.minimalInfra.test.ts
+++ b/host-context-controller/test/networkPolicyReconciler.minimalInfra.test.ts
@@ -16,10 +16,13 @@ vi.mock('../src/config', () => ({
},
}))
-vi.mock('../src/utils', () => ({
- getErrorCode: (err: { code?: number }) => err?.code,
- applyNetworkPolicy: vi.fn().mockResolvedValue(undefined),
-}))
+vi.mock('../src/utils', async importOriginal => {
+ const actual = await importOriginal<typeof import('../src/utils')>()
+ return {
+ ...actual,
+ applyNetworkPolicy: vi.fn().mockResolvedValue(undefined),
+ }
+})
const mockApply = vi.mocked(applyNetworkPolicy)
diff --git a/host-context-controller/test/networkPolicyReconciler.nodeLocalDns.test.ts b/host-context-controller/test/networkPolicyReconciler.nodeLocalDns.test.ts
index 9d0db5860..8273ef576 100644
--- a/host-context-controller/test/networkPolicyReconciler.nodeLocalDns.test.ts
+++ b/host-context-controller/test/networkPolicyReconciler.nodeLocalDns.test.ts
@@ -22,10 +22,13 @@ vi.mock('../src/config', () => ({
},
}))
-vi.mock('../src/utils', () => ({
- getErrorCode: (err: { code?: number }) => err?.code,
- applyNetworkPolicy: vi.fn().mockResolvedValue(undefined),
-}))
+vi.mock('../src/utils', async importOriginal => {
+ const actual = await importOriginal<typeof import('../src/utils')>()
+ return {
+ ...actual,
+ applyNetworkPolicy: vi.fn().mockResolvedValue(undefined),
+ }
+})
const mockApply = vi.mocked(applyNetworkPolicy)
diff --git a/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts b/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts
index 6acb165b3..7838b14d2 100644
--- a/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts
+++ b/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts
@@ -16,11 +16,13 @@ vi.mock('../src/config', () => ({
},
}))
-// Mock utils
-vi.mock('../src/utils', () => ({
- getErrorCode: (err: any) => err?.code,
- applyNetworkPolicy: vi.fn().mockResolvedValue(undefined),
-}))
+vi.mock('../src/utils', async importOriginal => {
+ const actual = await importOriginal<typeof import('../src/utils')>()
+ return {
+ ...actual,
+ applyNetworkPolicy: vi.fn().mockResolvedValue(undefined),
+ }
+})
const mockApply = vi.mocked(applyNetworkPolicy)