Skip to content

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

TypeScript

fix(hcc): enforce single-owner policy convergence

Alfredo Lopeze7064a7f408b
diff --git a/host-context-controller/README.md b/host-context-controller/README.md
index 8ec691a52..6bf128ed3 100644
--- a/host-context-controller/README.md
+++ b/host-context-controller/README.md
@@ -119,7 +119,8 @@ McpServers carrying a `clerum.io/recipe-bindings` annotation (set for WorkflowRe
### Reconciliation Lifecycle
-- **Startup** — Ensures L0/L1 defaults, reconciles all Contexts and all McpServer egress bindings, then deletes orphaned context-allow policies in the MCP server namespace, plus orphaned rpc-proxy-egress and external-egress policies, whose owning CRD no longer exists (`fullReconcile`).
+- **Startup safety** — Ensures L0/L1 defaults, revokes stale or orphaned context-allow, rpc-proxy-egress, and external-egress policies from authoritative Context/McpServer inventories, then certifies readiness safety.
+- **Startup additive convergence** — Reconciles Context allows after certification. The dedicated external-egress coordinator is the sole owner of McpServer egress creation, per-server startup gating, retry, and periodic DNS refresh; a failed binding blocks only that server's runtime.
- **Context ADDED/MODIFIED/DELETED** — Creates, updates, or removes the L2 policy set for that context.
- **McpServer ADDED/MODIFIED/DELETED** — Reconciles L3 external egress (before the workload Deployment is created) and recipe binding policies.
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index ea37a6044..d3d8ef71e 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.176",
+ "version": "0.1.177",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.176",
+ "version": "0.1.177",
"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 a605aef45..fdff33b31 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.176",
+ "version": "0.1.177",
"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/externalEgressConvergenceCoordinator.test.ts b/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
index 8521b148d..8d515f8de 100644
--- a/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
+++ b/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
@@ -528,6 +528,39 @@ describe('ExternalEgressConvergenceCoordinator', () => {
instance.stop()
})
+ it('keeps a failed startup DNS gate isolated and recovers it through the dedicated retry', async () => {
+ vi.useFakeTimers()
+ const selected = server('dns-held-server')
+ const dnsFailure = new Error('dns resolution failed')
+ const mutate = vi.fn().mockRejectedValueOnce(dnsFailure).mockResolvedValue(undefined)
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ let instance!: ExternalEgressConvergenceCoordinator
+ const built = coordinator({
+ mutate,
+ replay: async (type, current, retry) => {
+ const completion = await instance.reconcile(type, current, { retry })
+ completion?.complete()
+ },
+ })
+ instance = built.instance
+ built.servers.set(selected.name, selected)
+
+ const gates = instance.prepareStartupGates([selected])
+ await expect(gates.waitFor(selected)).resolves.toBe(false)
+ expect(mutate).toHaveBeenCalledOnce()
+ expect(error).toHaveBeenCalledWith(
+ `[K8s] Initial external egress reconciliation failed for ${selected.namespace}/${selected.name}; ` +
+ 'runtime reconciliation will stay blocked until retry succeeds:',
+ dnsFailure
+ )
+
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(mutate).toHaveBeenCalledTimes(2)
+ await vi.advanceTimersByTimeAsync(30000)
+ expect(mutate).toHaveBeenCalledTimes(2)
+ instance.stop()
+ })
+
it('retires a direct mutation lease when desired revision changes in place', async () => {
const selected = server('web-search', 1)
const replacement = server('web-search', 2)
diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.ts
index 1909cfeab..9cb78ca20 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -3337,6 +3337,48 @@ describe('McpServerWatcher startup', () => {
errorSpy.mockRestore()
})
+ it('does not report a post-certification additive failure as a readiness safety failure', async () => {
+ vi.useFakeTimers()
+ const additiveFailure = new AggregateError(
+ [new Error('Context policy API unavailable')],
+ 'One or more additive Context NetworkPolicy reconciliations failed'
+ )
+ mocks.netPolFullReconcile.mockImplementationOnce(
+ async (
+ _contexts: unknown,
+ _servers: unknown,
+ options?: { onAuthoritativeRevocationComplete?: () => void }
+ ) => {
+ options?.onAuthoritativeRevocationComplete?.()
+ throw additiveFailure
+ }
+ )
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const watcher = new McpServerWatcher()
+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')
+ stubAuthoritativeInventoryWatch(watcher, 'Context')
+ vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)
+ vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)
+ vi.spyOn(watcher as any, 'startCommunicationChannelWatch').mockResolvedValue(undefined)
+
+ await watcher.start()
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(true)
+ expect(errorSpy).toHaveBeenCalledWith(
+ '[K8s] Initial NetworkPolicy post-certification additive reconciliation failed:',
+ additiveFailure
+ )
+ expect(errorSpy).not.toHaveBeenCalledWith(
+ '[K8s] Initial NetworkPolicy background reconciliation failed:',
+ additiveFailure
+ )
+ expect((watcher as any).initialConvergenceRetryTimers.has('NetworkPolicy')).toBe(true)
+
+ await watcher.stop()
+ errorSpy.mockRestore()
+ })
+
it.each([
['McpServer', 'startMcpServerWatch'],
['Context', 'startContextWatch'],
@@ -3570,7 +3612,8 @@ describe('McpServerWatcher startup', () => {
)
})
const netPol = (watcher as any).netPolReconciler
- netPol.reconcileExternalEgress.mockRejectedValueOnce(new Error('dns resolution failed'))
+ const dnsFailure = new Error('dns resolution failed')
+ netPol.reconcileExternalEgress.mockRejectedValueOnce(dnsFailure)
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
stubAuthoritativeInventoryWatch(watcher, 'McpServer')
@@ -3590,6 +3633,12 @@ describe('McpServerWatcher startup', () => {
)
expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(1)
expect(reconciler.reconcile).not.toHaveBeenCalled()
+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(true)
+ expect((watcher as any).initialConvergenceRetryTimers.has('NetworkPolicy')).toBe(false)
+ expect(errorSpy).not.toHaveBeenCalledWith(
+ '[K8s] Initial NetworkPolicy background reconciliation failed:',
+ dnsFailure
+ )
watcher.stop()
errorSpy.mockRestore()
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index 3b58dcdd6..174b8fb13 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -2598,11 +2598,14 @@ export class McpServerWatcher implements McpServerProvider {
}
private async runInitialNetworkPolicyConvergenceCore(): Promise<void> {
- // A NetworkPolicy full pass mixes Context- and McpServer-derived positive
- // effects with orphan cleanup. Running it from a partial inventory would
- // be neither a full convergence nor safe evidence of success. Recovery of
- // either missing LIST -> WATCH pair schedules a fresh current-cache pass.
+ // A NetworkPolicy full pass combines authoritative Context/McpServer allow
+ // revocation with additive Context policy effects. External egress
+ // creation and DNS refresh have one separate owner: the startup/resync
+ // coordinator. Running safety from a partial inventory would be neither a
+ // full convergence nor safe evidence of success. Recovery of either
+ // missing LIST -> WATCH pair schedules a fresh current-cache pass.
if (!this.contextCacheSynced || !this.mcpServerCacheSynced) return
+ let authoritativeRevocationCompleted = false
try {
const initialContexts = [...this.contexts.values()]
const initialServers = [...this.servers.values()]
@@ -2646,10 +2649,11 @@ export class McpServerWatcher implements McpServerProvider {
this.networkPolicyRevocationServerGeneration = serverInventoryGeneration
this.networkPolicyRevocationContextRevision = this.contextDesiredRevision
this.networkPolicyRevocationServerRevision = this.mcpServerDesiredRevision
+ authoritativeRevocationCompleted = true
// Start runtime convergence at the safety boundary, before this full
- // pass enters additive Context and DNS refresh work. Startup egress
- // gates may now preserve only policies certified by this exact
- // authoritative inventory generation.
+ // pass enters additive Context work. Startup egress gates may now
+ // preserve only policies certified by this exact authoritative
+ // inventory generation.
void this.runInitialMcpServerConvergence()
},
})
@@ -2660,7 +2664,12 @@ export class McpServerWatcher implements McpServerProvider {
)
this.clearInitialConvergenceRetry('NetworkPolicy')
} catch (error) {
- console.error('[K8s] Initial NetworkPolicy background reconciliation failed:', error)
+ console.error(
+ authoritativeRevocationCompleted
+ ? '[K8s] Initial NetworkPolicy post-certification additive reconciliation failed:'
+ : '[K8s] Initial NetworkPolicy background reconciliation failed:',
+ error
+ )
this.scheduleInitialConvergenceRetry('NetworkPolicy')
}
}
diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.ts
index 4ca1c9693..49f429bf2 100644
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@ -526,6 +526,82 @@ describe('NetworkPolicyReconciler', () => {
// ─── L2: Context-Based Policies ────────────────────────────────────
describe('L2 — reconcileContext', () => {
+ it('refuses to adopt a foreign policy that collides with a live Context policy name', async () => {
+ const server: McpServerCRD = {
+ name: 'mongo',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'dev',
+ image: 'mongo:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ }
+ const rec = makeReconciler(mockApi, new Map([[server.name, server]]))
+ const context: ContextCRD = {
+ name: 'dev',
+ namespace: 'mcp-server',
+ spec: { contextId: 'dev', mcpServers: [server.name] },
+ }
+ mockApi.createNamespacedNetworkPolicy.mockRejectedValueOnce(
+ Object.assign(new Error('already exists'), { code: 409 })
+ )
+ mockApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
+ metadata: {
+ name: 'ctx-dev-mongo',
+ namespace: 'mcp-server',
+ uid: 'foreign-uid',
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'foreign-controller',
+ 'clerum.io/policy-type': 'context-allow',
+ 'clerum.io/context': 'dev',
+ 'clerum.io/mcpserver': 'mongo',
+ },
+ },
+ })
+
+ await expect(rec.reconcileContext(context)).rejects.toThrow(/ownership/i)
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('refuses to replace an HCC Context policy owned by a different Context/server pair', async () => {
+ const server: McpServerCRD = {
+ name: 'b-c',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'a',
+ image: 'mongo:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ }
+ const rec = makeReconciler(mockApi, new Map([[server.name, server]]))
+ const context: ContextCRD = {
+ name: 'a',
+ namespace: 'mcp-server',
+ spec: { contextId: 'a', mcpServers: ['b-c'] },
+ }
+ mockApi.createNamespacedNetworkPolicy.mockRejectedValueOnce(
+ Object.assign(new Error('already exists'), { code: 409 })
+ )
+ mockApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
+ metadata: {
+ name: 'ctx-a-b-c',
+ namespace: 'mcp-server',
+ uid: 'other-hcc-owner-uid',
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'host-context-controller',
+ 'clerum.io/policy-type': 'context-allow',
+ 'clerum.io/context': 'a-b',
+ 'clerum.io/mcpserver': 'c',
+ },
+ },
+ })
+
+ await expect(rec.reconcileContext(context)).rejects.toThrow(/ownership/i)
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
it('creates context-allow ingress policy per server in mcp-server namespace', async () => {
const cache = new Map<string, McpServerCRD>()
cache.set('mongo', {
@@ -971,6 +1047,70 @@ describe('NetworkPolicyReconciler', () => {
// ─── L3: External Egress ───────────────────────────────────────────
describe('L3 — reconcileExternalEgress', () => {
+ it('refuses to adopt a foreign policy that collides with an external-egress name', async () => {
+ const server: McpServerCRD = {
+ name: 'openai-mcp',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'dev',
+ image: 'openai:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ egressBindings: [{ cidr: '104.18.0.0/16', port: 443 }],
+ },
+ }
+ mockApi.createNamespacedNetworkPolicy.mockRejectedValueOnce(
+ Object.assign(new Error('already exists'), { code: 409 })
+ )
+ mockApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
+ metadata: {
+ name: 'ext-egress-openai-mcp-104-18-0-0-16-443',
+ namespace: 'mcp-server',
+ uid: 'foreign-uid',
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'foreign-controller',
+ 'clerum.io/policy-type': 'external-egress',
+ 'clerum.io/mcpserver': server.name,
+ },
+ },
+ })
+
+ await expect(reconciler.reconcileExternalEgress(server)).rejects.toThrow(/ownership/i)
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('refuses to replace an HCC external-egress policy owned by a different server', async () => {
+ const server: McpServerCRD = {
+ name: 'openai-mcp',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'dev',
+ image: 'openai:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ egressBindings: [{ cidr: '104.18.0.0/16', port: 443 }],
+ },
+ }
+ mockApi.createNamespacedNetworkPolicy.mockRejectedValueOnce(
+ Object.assign(new Error('already exists'), { code: 409 })
+ )
+ mockApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
+ metadata: {
+ name: 'ext-egress-openai-mcp-104-18-0-0-16-443',
+ namespace: 'mcp-server',
+ uid: 'other-hcc-owner-uid',
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'host-context-controller',
+ 'clerum.io/policy-type': 'external-egress',
+ 'clerum.io/mcpserver': 'different-server',
+ },
+ },
+ })
+
+ await expect(reconciler.reconcileExternalEgress(server)).rejects.toThrow(/ownership/i)
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
it('creates egress policy for CIDR binding', async () => {
const server: McpServerCRD = {
name: 'openai-mcp',
@@ -2297,54 +2437,6 @@ describe('NetworkPolicyReconciler', () => {
await fullPass
})
- it('retires a full-pass external-egress lease when desired state is replaced', async () => {
- const selected: McpServerCRD = {
- name: 'full-pass-egress',
- namespace: 'mcp-server',
- uid: 'full-pass-egress-uid',
- generation: 1,
- spec: {
- contextRef: 'dev',
- image: 'full-pass-egress:old',
- transport: { type: 'streamableHttp', port: 3000 },
- egressBindings: [{ dns: 'old.example', port: 443 }],
- },
- }
- const replacement: McpServerCRD = {
- ...selected,
- generation: 2,
- spec: {
- ...selected.spec,
- image: 'full-pass-egress:new',
- egressBindings: [{ dns: 'new.example', port: 443 }],
- },
- }
- let current = selected
- let selectedLease: (() => boolean) | undefined
- const mutationStarted = deferred()
- const releaseMutation = deferred()
- vi.spyOn(reconciler, 'reconcileExternalEgress').mockImplementationOnce(
- async (_server, options) => {
- selectedLease = options?.isCurrent
- mutationStarted.resolve(undefined)
- await releaseMutation.promise
- }
- )
-
- const fullPass = reconciler.fullReconcile([], [selected], {
- ensureDefaults: false,
- serverInventoryAuthoritative: () => true,
- resolveCurrentServer: () => current,
- })
- await mutationStarted.promise
- expect(selectedLease?.()).toBe(true)
-
- current = replacement
- expect(selectedLease?.()).toBe(false)
- releaseMutation.resolve(undefined)
- await fullPass
- })
-
it('deletes orphaned Context policies in all three namespaces through the canonical contextId effect key', async () => {
const effectKeys: string[] = []
mockApi.listNamespacedNetworkPolicy.mockImplementation(
@@ -2726,32 +2818,19 @@ describe('NetworkPolicyReconciler', () => {
namespace: 'mcp-server',
spec: { contextId, mcpServers: [] },
}))
- const server: McpServerCRD = {
- name: 'later-egress-server',
- namespace: 'mcp-server',
- spec: {
- contextRef: 'bbb-healthy',
- image: 'later:latest',
- transport: { type: 'streamableHttp', port: 3000 },
- egressBindings: [{ cidr: '203.0.113.10/32', port: 443, protocol: 'TCP' }],
- },
- }
const ordering: string[] = []
const additiveFailure = new Error('poisoned additive Context')
vi.spyOn(reconciler, 'reconcileContext').mockImplementation(async context => {
ordering.push(`context:${context.spec.contextId}`)
if (context.spec.contextId === 'aaa-poisoned') throw additiveFailure
})
- vi.spyOn(reconciler, 'reconcileExternalEgress').mockImplementation(async current => {
- ordering.push(`server:${current.name}`)
- })
const onAuthoritativeRevocationComplete = vi.fn(() => {
ordering.push('certify')
})
const errorLog = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const error = await reconciler
- .fullReconcile(contexts, [server], {
+ .fullReconcile(contexts, [], {
ensureDefaults: false,
contextInventoryAuthoritative: () => true,
serverInventoryAuthoritative: () => true,
@@ -2764,60 +2843,13 @@ describe('NetworkPolicyReconciler', () => {
expect(error).toBeInstanceOf(AggregateError)
expect((error as AggregateError).errors).toEqual([additiveFailure])
- expect(ordering).toEqual([
- 'certify',
- 'context:aaa-poisoned',
- 'context:bbb-healthy',
- 'server:later-egress-server',
- ])
+ expect(ordering).toEqual(['certify', 'context:aaa-poisoned', 'context:bbb-healthy'])
expect(errorLog).toHaveBeenCalledWith(
'[NetPol] Additive Context reconciliation failed for "aaa-poisoned":',
additiveFailure
)
})
- it('does not let one post-certification McpServer failure starve later server refreshes', async () => {
- const servers: McpServerCRD[] = ['aaa-poisoned', 'bbb-healthy'].map(name => ({
- name,
- namespace: 'mcp-server',
- spec: {
- contextRef: 'default',
- image: `${name}:latest`,
- transport: { type: 'streamableHttp', port: 3000 },
- egressBindings: [{ cidr: '203.0.113.10/32', port: 443, protocol: 'TCP' }],
- },
- }))
- const ordering: string[] = []
- const additiveFailure = new Error('poisoned additive McpServer')
- vi.spyOn(reconciler, 'reconcileExternalEgress').mockImplementation(async server => {
- ordering.push(server.name)
- if (server.name === 'aaa-poisoned') throw additiveFailure
- })
- const onAuthoritativeRevocationComplete = vi.fn()
- const errorLog = vi.spyOn(console, 'error').mockImplementation(() => undefined)
-
- const error = await reconciler
- .fullReconcile([], servers, {
- ensureDefaults: false,
- contextInventoryAuthoritative: () => true,
- serverInventoryAuthoritative: () => true,
- onAuthoritativeRevocationComplete,
- })
- .then(
- () => undefined,
- failure => failure
- )
-
- expect(error).toBeInstanceOf(AggregateError)
- expect((error as AggregateError).errors).toEqual([additiveFailure])
- expect(ordering).toEqual(['aaa-poisoned', 'bbb-healthy'])
- expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
- expect(errorLog).toHaveBeenCalledWith(
- '[NetPol] Additive external-egress reconciliation failed for "aaa-poisoned":',
- additiveFailure
- )
- })
-
it('replaces same-name Context allow policies in every lane before certification', async () => {
const oldServer: McpServerCRD = {
name: 'live-server',
@@ -2890,6 +2922,81 @@ describe('NetworkPolicyReconciler', () => {
expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
})
+ it.each([
+ ['context-ingress', 'mcp-server'],
+ ['context-host-egress', 'mcp-host'],
+ ['context-rpc-egress', 'rpc-proxy'],
+ ])(
+ 'refuses a same-name %s safety replacement owned by another server',
+ async (_lane, targetNamespace) => {
+ const oldServer: McpServerCRD = {
+ name: 'live-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'live:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ }
+ const currentServer: McpServerCRD = {
+ ...oldServer,
+ spec: {
+ ...oldServer.spec,
+ transport: { type: 'streamableHttp', port: 4000 },
+ },
+ }
+ const liveContext: ContextCRD = {
+ name: 'live-context-resource',
+ namespace: 'mcp-server',
+ spec: { contextId: 'live-context', mcpServers: [oldServer.name] },
+ }
+ const serverCache = new Map([[oldServer.name, oldServer]])
+ const rec = makeReconciler(mockApi, serverCache, mockCustomApi)
+
+ await rec.reconcileContext(liveContext)
+ const oldPolicies = mockApi.createNamespacedNetworkPolicy.mock.calls.map(call => {
+ const policy = (call[0] as { body: k8s.V1NetworkPolicy }).body
+ if (policy.metadata?.namespace !== targetNamespace) return policy
+ return {
+ ...policy,
+ metadata: {
+ ...policy.metadata,
+ labels: {
+ ...policy.metadata?.labels,
+ 'clerum.io/mcpserver': 'different-server',
+ },
+ },
+ }
+ })
+
+ vi.clearAllMocks()
+ serverCache.set(currentServer.name, currentServer)
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(
+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {
+ if (labelSelector?.includes('external-egress')) return { items: [] }
+ return {
+ items: oldPolicies.filter(policy => policy.metadata?.namespace === namespace),
+ }
+ }
+ )
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ await expect(
+ rec.fullReconcile([liveContext], [currentServer], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete,
+ })
+ ).rejects.toThrow(/ownership/i)
+
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalledWith(
+ expect.objectContaining({ namespace: targetNamespace })
+ )
+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()
+ }
+ )
+
it('fails the safety pass without certifying when a same-name Context replacement fails', async () => {
const oldServer: McpServerCRD = {
name: 'live-server',
@@ -3007,7 +3114,7 @@ describe('NetworkPolicyReconciler', () => {
expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
- it('revokes same-name DNS egress before certifying and refreshes it additively', async () => {
+ it('revokes same-name DNS egress before certifying and leaves refresh to its coordinator', async () => {
const oldServer: McpServerCRD = {
name: 'live-server',
namespace: 'mcp-server',
@@ -3062,8 +3169,8 @@ describe('NetworkPolicyReconciler', () => {
})
expect(ordering.slice(0, 2)).toEqual(['delete', 'certify'])
- expect(ordering).toContain('replace')
- expect(ordering.indexOf('replace')).toBeGreaterThan(ordering.indexOf('certify'))
+ expect(ordering).not.toContain('replace')
+ expect(dns.resolve4).not.toHaveBeenCalled()
expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
})
@@ -3120,7 +3227,7 @@ describe('NetworkPolicyReconciler', () => {
serverInventoryAuthoritative: () => true,
onAuthoritativeRevocationComplete,
})
- ).rejects.toThrow('One or more additive NetworkPolicy reconciliations failed')
+ ).resolves.toBeUndefined()
expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(
expect.objectContaining({
@@ -3129,7 +3236,8 @@ describe('NetworkPolicyReconciler', () => {
})
)
expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
- expect(ordering.slice(0, 3)).toEqual(['delete', 'certify', 'dns'])
+ expect(dns.resolve4).not.toHaveBeenCalled()
+ expect(ordering).toEqual(['delete', 'certify'])
})
it('revokes a renamed DNS binding before certification and performs no DNS lookup on the safety path', async () => {
@@ -3184,7 +3292,8 @@ describe('NetworkPolicyReconciler', () => {
onAuthoritativeRevocationComplete,
})
- expect(ordering.slice(0, 3)).toEqual(['delete', 'certify', 'dns'])
+ expect(ordering).toEqual(['delete', 'certify'])
+ expect(dns.resolve4).not.toHaveBeenCalled()
expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
name: oldPolicy.metadata!.name!,
namespace: oldServer.namespace,
@@ -3259,7 +3368,8 @@ describe('NetworkPolicyReconciler', () => {
onAuthoritativeRevocationComplete,
})
- expect(ordering.slice(0, 4)).toEqual(['replace', 'delete', 'certify', 'dns'])
+ expect(ordering).toEqual(['replace', 'delete', 'certify'])
+ expect(dns.resolve4).not.toHaveBeenCalled()
})
it('aborts certification when an identity-bound safety delete reports a recreate conflict', async () => {
@@ -3368,7 +3478,7 @@ describe('NetworkPolicyReconciler', () => {
serverInventoryAuthoritative: () => true,
onAuthoritativeRevocationComplete,
})
- ).rejects.toThrow(/changed identity or ownership/)
+ ).rejects.toThrow(/ownership/)
expect(mockApi.readNamespacedNetworkPolicy).toHaveBeenCalledWith({
name: existing.metadata!.name!,
@@ -3475,34 +3585,22 @@ describe('NetworkPolicyReconciler', () => {
currentPolicies = []
return {}
})
- const additiveStarted = deferred()
- const releaseAdditive = deferred()
- vi.spyOn(rec, 'reconcileExternalEgress').mockImplementationOnce(async () => {
- additiveStarted.resolve(undefined)
- await releaseAdditive.promise
- })
const onAuthoritativeRevocationComplete = vi.fn()
- const fullPass = rec.fullReconcile([], [server], {
+ await rec.fullReconcile([], [server], {
ensureDefaults: false,
contextInventoryAuthoritative: () => true,
serverInventoryAuthoritative: () => true,
onAuthoritativeRevocationComplete,
})
- await additiveStarted.promise
- try {
- expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(
- expect.objectContaining({
- name: existing!.metadata!.name!,
- namespace: server.namespace,
- })
- )
- expect(dns.resolve4).not.toHaveBeenCalled()
- } finally {
- releaseAdditive.resolve(undefined)
- await fullPass
- }
+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: existing!.metadata!.name!,
+ namespace: server.namespace,
+ })
+ )
+ expect(dns.resolve4).not.toHaveBeenCalled()
})
it('does not certify safety when a same-intent DNS policy cannot be revoked', async () => {
@@ -3868,7 +3966,7 @@ describe('NetworkPolicyReconciler', () => {
}
})
- it('reconciles external egress policies for existing servers on startup', async () => {
+ it('leaves startup external egress creation to its dedicated coordinator', async () => {
const server: McpServerCRD = {
name: 'airtable-mcp',
namespace: 'mcp-server',
@@ -3888,17 +3986,8 @@ describe('NetworkPolicyReconciler', () => {
return arg.body.metadata.labels['clerum.io/policy-type'] === 'external-egress'
}
)
- expect(externalPolicies).toHaveLength(1)
- const body = (
- externalPolicies[0][0] as {
- body: {
- metadata: { name: string }
- spec: { egress: Array<{ ports: Array<{ port: number }> }> }
- }
- }
- ).body
- expect(body.metadata.name).toContain('ext-egress-airtable-mcp')
- expect(body.spec.egress[0].ports[0].port).toBe(443)
+ expect(externalPolicies).toHaveLength(0)
+ expect(dns.resolve4).not.toHaveBeenCalled()
})
it('deletes orphaned external egress policies for servers no longer present', async () => {
@@ -4093,7 +4182,7 @@ describe('NetworkPolicyReconciler', () => {
)
})
- it('finishes desired McpServer reconciliation but stops external-egress orphan cleanup when authority is lost after inventory listing', async () => {
+ it('stops external-egress orphan cleanup when authority is lost after inventory listing', async () => {
const desiredServer: McpServerCRD = {
name: 'current-server',
namespace: 'mcp-server',
@@ -4103,9 +4192,6 @@ describe('NetworkPolicyReconciler', () => {
transport: { type: 'streamableHttp', url: 'http://current:3000', port: 3000 },
},
}
- const reconcileExternalEgress = vi
- .spyOn(reconciler, 'reconcileExternalEgress')
- .mockResolvedValue(undefined)
const serverInventoryAuthoritative = vi
.fn()
.mockReturnValueOnce(true)
@@ -4136,12 +4222,6 @@ describe('NetworkPolicyReconciler', () => {
serverInventoryAuthoritative,
})
- expect(reconcileExternalEgress).toHaveBeenCalledWith(
- desiredServer,
- expect.objectContaining({
- isCurrent: expect.any(Function),
- })
- )
expect(serverInventoryAuthoritative).toHaveBeenCalled()
expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith({
name: 'ext-egress-deleted-server-api-example-com-443',
@@ -4286,7 +4366,16 @@ describe('NetworkPolicyReconciler', () => {
await reconciler.cleanupExternalEgress('openai-mcp', 'mcp-server')
- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'ext-egress-openai-mcp-api-443',
+ namespace: 'mcp-server',
+ body: {
+ preconditions: {
+ uid: 'mcp-server:ext-egress-openai-mcp-api-443:uid',
+ resourceVersion: '1',
+ },
+ },
+ })
})
it('fails closed when stale external egress policy deletion fails', async () => {
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index cc20adab1..b199502cd 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -787,23 +787,21 @@ export class NetworkPolicyReconciler {
if (!isCurrent()) return
const hostEgressName = desired.hostEgress.metadata!.name!
- await applyNetworkPolicy(
- this.networkingApi,
+ await this.applyOwnedPolicy(
hostEgressName,
config.hostNamespace,
desired.hostEgress,
- '[NetPol]',
+ 'context-host-egress',
isCurrent
)
if (!isCurrent()) return
const rpcProxyEgressName = desired.rpcProxyEgress.metadata!.name!
- await applyNetworkPolicy(
- this.networkingApi,
+ await this.applyOwnedPolicy(
rpcProxyEgressName,
config.rpcProxyNamespace,
desired.rpcProxyEgress,
- '[NetPol]',
+ 'context-rpc-egress',
isCurrent
)
}
@@ -853,7 +851,7 @@ export class NetworkPolicyReconciler {
return false
}
} else {
- await this.deletePolicy(existingName, isCurrent)
+ await this.deleteSafetyPolicySnapshot(config.namespace, existing, isCurrent)
}
onRevoked?.()
} else if (
@@ -874,7 +872,13 @@ export class NetworkPolicyReconciler {
return false
}
} else {
- await this.applyPolicy(existingName, desired, isCurrent)
+ await this.replaceSafetyPolicySnapshot(
+ config.namespace,
+ existing,
+ desired,
+ 'context-ingress',
+ isCurrent
+ )
}
onRevoked?.()
}
@@ -894,7 +898,7 @@ export class NetworkPolicyReconciler {
return false
}
} else {
- await this.deleteEgressPolicy(existingName, isCurrent)
+ await this.deleteSafetyPolicySnapshot(config.hostNamespace, existing, isCurrent)
}
onRevoked?.()
} else if (
@@ -915,12 +919,11 @@ export class NetworkPolicyReconciler {
return false
}
} else {
- await applyNetworkPolicy(
- this.networkingApi,
- existingName,
+ await this.replaceSafetyPolicySnapshot(
config.hostNamespace,
+ existing,
desired,
- '[NetPol]',
+ 'context-host-egress',
isCurrent
)
}
@@ -944,7 +947,7 @@ export class NetworkPolicyReconciler {
return false
}
} else {
- await this.deletePolicyInNamespace(config.rpcProxyNamespace, existingName, isCurrent)
+ await this.deleteSafetyPolicySnapshot(config.rpcProxyNamespace, existing, isCurrent)
}
onRevoked?.()
} else if (
@@ -965,12 +968,11 @@ export class NetworkPolicyReconciler {
return false
}
} else {
- await applyNetworkPolicy(
- this.networkingApi,
- existingName,
+ await this.replaceSafetyPolicySnapshot(
config.rpcProxyNamespace,
+ existing,
desired,
- '[NetPol]',
+ 'context-rpc-egress',
isCurrent
)
}
@@ -992,17 +994,15 @@ export class NetworkPolicyReconciler {
const policies = await this.listPoliciesForContext(contextId)
for (const policy of policies) {
- const name = policy.metadata?.name || ''
if (deleteAllowed && !(await deleteAllowed())) return
- await this.deletePolicy(name)
+ await this.deleteSafetyPolicySnapshot(config.namespace, policy)
}
// Also delete L2 egress counterparts in mcp-host namespace
const egressPolicies = await this.listEgressPoliciesForContext(contextId)
for (const policy of egressPolicies) {
- const name = policy.metadata?.name || ''
if (deleteAllowed && !(await deleteAllowed())) return
- await this.deleteEgressPolicy(name)
+ await this.deleteSafetyPolicySnapshot(config.hostNamespace, policy)
}
// Also delete L2 rpc-proxy egress policies
@@ -1410,11 +1410,14 @@ export class NetworkPolicyReconciler {
options.onAuthoritativeRevocationComplete?.()
}
- // Additive convergence happens only after every stale allow policy implied
- // by the authoritative inventory has been revoked. A slow or failing
- // positive effect therefore cannot extend a stale-permission window after
- // readiness becomes available.
- const additiveFailures: unknown[] = []
+ // Additive Context convergence happens only after every stale allow policy
+ // implied by the authoritative inventory has been revoked. A slow or
+ // failing positive effect therefore cannot extend a stale-permission
+ // window after readiness becomes available. External egress creation and
+ // DNS refresh intentionally do not run here:
+ // ExternalEgressConvergenceCoordinator is their sole startup, retry, and
+ // periodic-resync owner.
+ const contextAdditiveFailures: unknown[] = []
for (const context of contexts) {
const contextId = context.spec.contextId
try {
@@ -1432,45 +1435,15 @@ export class NetworkPolicyReconciler {
await this.reconcileContext(current, { isCurrent: contextEffectIsCurrent })
})
} catch (error) {
- additiveFailures.push(error)
+ contextAdditiveFailures.push(error)
console.error(`[NetPol] Additive Context reconciliation failed for "${contextId}":`, error)
}
}
- // Refresh and create external egress policies after certification. The
- // safety phase above revokes every DNS-derived allow because its resolved
- // IP set cannot be proven current without a fresh lookup. DNS latency and
- // failure therefore gate only the affected runtime, never global readiness.
- for (const server of servers) {
- try {
- await runServerEffect(server.name, async () => {
- const current = options.resolveCurrentServer
- ? options.resolveCurrentServer(server.name)
- : server
- if (!current) return
- const serverEffectIsCurrent = (): boolean => {
- if (!(options.serverInventoryAuthoritative?.() ?? true)) return false
- if (!options.resolveCurrentServer) return true
- const latest = options.resolveCurrentServer(current.name)
- return latest !== undefined && sameMcpServerDesiredRevision(current, latest)
- }
- await this.reconcileExternalEgress(current, {
- isCurrent: serverEffectIsCurrent,
- })
- })
- } catch (error) {
- additiveFailures.push(error)
- console.error(
- `[NetPol] Additive external-egress reconciliation failed for "${server.name}":`,
- error
- )
- }
- }
-
- if (additiveFailures.length > 0) {
+ if (contextAdditiveFailures.length > 0) {
throw new AggregateError(
- additiveFailures,
- 'One or more additive NetworkPolicy reconciliations failed'
+ contextAdditiveFailures,
+ 'One or more additive Context NetworkPolicy reconciliations failed'
)
}
@@ -1696,8 +1669,7 @@ export class NetworkPolicyReconciler {
server.namespace,
unprovableDnsPolicies,
async () => isCurrent(),
- onRevoked,
- true
+ onRevoked
)
if (!isCurrent()) return false
@@ -1706,8 +1678,7 @@ export class NetworkPolicyReconciler {
server.namespace,
stale,
async () => isCurrent(),
- onRevoked,
- true
+ onRevoked
)
return isCurrent()
}
@@ -1817,12 +1788,11 @@ export class NetworkPolicyReconciler {
}
desiredPolicyNames.add(name)
- await applyNetworkPolicy(
- this.networkingApi,
+ await this.applyOwnedPolicy(
name,
server.namespace,
this.buildPublicWebEgressPolicy(server, name),
- '[NetPol]',
+ 'external-egress',
isCurrent
)
continue
@@ -1890,12 +1860,11 @@ export class NetworkPolicyReconciler {
desiredPolicyNames.add(name)
const desiredPolicy = this.buildExactHostEgressPolicy(server, name, binding, cidrs)
- await applyNetworkPolicy(
- this.networkingApi,
+ await this.applyOwnedPolicy(
name,
server.namespace,
desiredPolicy,
- '[NetPol]',
+ 'external-egress',
isCurrent
)
}
@@ -1958,8 +1927,7 @@ export class NetworkPolicyReconciler {
namespace: string,
policies?: k8s.V1NetworkPolicy[],
deleteAllowed?: () => Promise<boolean>,
- onDeleted?: () => void,
- requireSnapshotIdentity = false
+ onDeleted?: () => void
): Promise<void> {
const policiesToDelete =
policies ?? (await this.listExternalEgressPoliciesForServer(serverName, namespace))
@@ -1969,15 +1937,10 @@ export class NetworkPolicyReconciler {
if (!name) continue
try {
if (deleteAllowed && !(await deleteAllowed())) return
- const deleted = requireSnapshotIdentity
- ? await this.deleteSafetyPolicySnapshot(namespace, policy)
- : await this.networkingApi
- .deleteNamespacedNetworkPolicy({ name, namespace })
- .then(() => true)
- if (deleted) {
+ await this.deleteSafetyPolicySnapshot(namespace, policy, undefined, () => {
console.log(`[NetPol] Deleted external egress policy "${name}"`)
onDeleted?.()
- }
+ })
} catch (error: unknown) {
if (getErrorCode(error) !== 404) {
console.error(`[NetPol] Failed to delete external egress policy "${name}":`, error)
@@ -2318,17 +2281,47 @@ export class NetworkPolicyReconciler {
name: string,
policy: k8s.V1NetworkPolicy,
isCurrent?: () => boolean
+ ): Promise<void> {
+ await this.applyOwnedPolicy(name, config.namespace, policy, 'context-ingress', isCurrent)
+ }
+
+ private async applyOwnedPolicy(
+ name: string,
+ namespace: string,
+ policy: k8s.V1NetworkPolicy,
+ lane: SafetyInventoryLane,
+ isCurrent?: () => boolean
): Promise<void> {
await applyNetworkPolicy(
this.networkingApi,
name,
- config.namespace,
+ namespace,
policy,
'[NetPol]',
- isCurrent
+ isCurrent,
+ existing => this.assertPolicyOwnership(name, existing, policy, lane)
)
}
+ private assertPolicyOwnership(
+ name: string,
+ existing: k8s.V1NetworkPolicy,
+ desired: k8s.V1NetworkPolicy,
+ lane: SafetyInventoryLane
+ ): void {
+ const classification = classifySafetyInventoryPolicy(existing, lane)
+ const existingLabels = existing.metadata?.labels ?? {}
+ const desiredLabels = desired.metadata?.labels ?? {}
+ const ownerLabels =
+ lane === 'external-egress' ? [MCPSERVER_LABEL] : [CONTEXT_LABEL, MCPSERVER_LABEL]
+ if (
+ (classification !== 'owned' && classification !== 'repairable') ||
+ ownerLabels.some(label => existingLabels[label] !== desiredLabels[label])
+ ) {
+ throw new Error(`NetworkPolicy "${name}" has conflicting ownership for the ${lane} lane`)
+ }
+ }
+
private safetyPolicyIdentity(policy: k8s.V1NetworkPolicy): {
name: string
uid: string
@@ -2353,7 +2346,8 @@ export class NetworkPolicyReconciler {
private async deleteSafetyPolicySnapshot(
namespace: string,
policy: k8s.V1NetworkPolicy,
- isCurrent?: () => boolean
+ isCurrent?: () => boolean,
+ onDeleted?: () => void
): Promise<boolean> {
if (isCurrent && !isCurrent()) return false
const { name, uid, resourceVersion } = this.safetyPolicyIdentity(policy)
@@ -2364,6 +2358,7 @@ export class NetworkPolicyReconciler {
body: { preconditions: { uid, resourceVersion } },
})
console.log(`[NetPol] Deleted safety-inventory policy "${name}" in ${namespace}`)
+ onDeleted?.()
return true
} catch (error: unknown) {
if (getErrorCode(error) === 404) {
@@ -2398,16 +2393,12 @@ export class NetworkPolicyReconciler {
})
if (!isCurrent()) return false
const actual = this.safetyPolicyIdentity(live)
- const classification = classifySafetyInventoryPolicy(live, lane)
- if (
- actual.uid !== expected.uid ||
- actual.resourceVersion !== expected.resourceVersion ||
- (classification !== 'owned' && classification !== 'repairable')
- ) {
+ if (actual.uid !== expected.uid || actual.resourceVersion !== expected.resourceVersion) {
throw new Error(
`NetworkPolicy "${expected.name}" changed identity or ownership after the authoritative safety inventory`
)
}
+ this.assertPolicyOwnership(expected.name, live, desired, lane)
await this.networkingApi.replaceNamespacedNetworkPolicy({
name: expected.name,
namespace,
@@ -2437,25 +2428,6 @@ export class NetworkPolicyReconciler {
return isCurrent()
}
- /** Delete a NetworkPolicy in mcp-server namespace. */
- private async deletePolicy(name: string, isCurrent?: () => boolean): Promise<void> {
- try {
- if (isCurrent && !isCurrent()) return
- await this.networkingApi.deleteNamespacedNetworkPolicy({
- name,
- namespace: config.namespace,
- })
- console.log(`[NetPol] Deleted policy "${name}"`)
- } catch (error: unknown) {
- if (getErrorCode(error) === 404) {
- console.log(`[NetPol] Policy "${name}" already gone`)
- } else {
- console.error(`[NetPol] Failed to delete policy "${name}":`, error)
- throw error
- }
- }
- }
-
/** List L2 egress counterpart policies in mcp-host namespace for a given context. */
private async listEgressPoliciesForContext(contextId: string): Promise<k8s.V1NetworkPolicy[]> {
try {
@@ -2470,25 +2442,6 @@ export class NetworkPolicyReconciler {
}
}
- /** Delete a NetworkPolicy in mcp-host namespace (L2 egress counterpart). */
- private async deleteEgressPolicy(name: string, isCurrent?: () => boolean): Promise<void> {
- try {
- if (isCurrent && !isCurrent()) return
- await this.networkingApi.deleteNamespacedNetworkPolicy({
- name,
- namespace: config.hostNamespace,
- })
- console.log(`[NetPol] Deleted L2 egress policy "${name}"`)
- } catch (error: unknown) {
- if (getErrorCode(error) === 404) {
- console.log(`[NetPol] L2 egress policy "${name}" already gone`)
- } else {
- console.error(`[NetPol] Failed to delete L2 egress policy "${name}":`, error)
- throw error
- }
- }
- }
-
// ─── RPC-Proxy Egress (L2) ──────────────────────────────────────────
private buildRpcProxyEgressPolicy(
@@ -2538,9 +2491,8 @@ export class NetworkPolicyReconciler {
try {
const policies = await this.listRpcProxyEgressPoliciesForContext(contextId)
for (const policy of policies) {
- const name = policy.metadata?.name || ''
if (deleteAllowed && !(await deleteAllowed())) return
- await this.deletePolicyInNamespace(config.rpcProxyNamespace, name)
+ await this.deleteSafetyPolicySnapshot(config.rpcProxyNamespace, policy)
}
} catch (error) {
console.error(
@@ -2584,26 +2536,6 @@ export class NetworkPolicyReconciler {
}
}
- /** Delete a NetworkPolicy in an arbitrary namespace. */
- private async deletePolicyInNamespace(
- namespace: string,
- name: string,
- isCurrent?: () => boolean
- ): Promise<void> {
- try {
- if (isCurrent && !isCurrent()) return
- await this.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace })
- console.log(`[NetPol] Deleted rpc-proxy egress policy "${name}"`)
- } catch (error: unknown) {
- if (getErrorCode(error) === 404) {
- console.log(`[NetPol] rpc-proxy egress policy "${name}" already gone`)
- } else {
- console.error(`[NetPol] Failed to delete policy "${name}" in ${namespace}:`, error)
- throw error
- }
- }
- }
-
/** Delete a formerly static NetworkPolicy that is now generated dynamically. */
private async deleteLegacyStaticPolicy(namespace: string, name: string): Promise<void> {
try {
diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.ts
index 3fe113c70..72967b99e 100644
--- a/host-context-controller/src/utils.ts
+++ b/host-context-controller/src/utils.ts
@@ -36,6 +36,8 @@ export async function replaceWithConflictRetry<
* when a meaningful change is still required.
*/
isUpToDate?: (body: T, existing: T) => boolean
+ /** Reject an object whose identity or ownership is unsafe to replace. */
+ validateExisting?: (existing: T) => void
/** Rechecked immediately before every Kubernetes write attempt. */
mutationAllowed?: () => boolean
maxAttempts?: number
@@ -49,11 +51,13 @@ export async function replaceWithConflictRetry<
replace,
mergeExisting,
isUpToDate,
+ validateExisting,
mutationAllowed,
maxAttempts = 3,
} = opts
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const existing = await read()
+ validateExisting?.(existing)
const desired = resolveBody ? await resolveBody() : body
const base: T = {
...desired,
@@ -176,7 +180,8 @@ export async function applyNetworkPolicy(
namespace: string,
policy: k8s.V1NetworkPolicy,
logPrefix = '[NetPol]',
- mutationAllowed?: () => boolean
+ mutationAllowed?: () => boolean,
+ validateExisting?: (existing: k8s.V1NetworkPolicy) => void
): Promise<void> {
if (mutationAllowed && !mutationAllowed()) return
try {
@@ -195,5 +200,6 @@ export async function applyNetworkPolicy(
read: () => api.readNamespacedNetworkPolicy({ name, namespace }),
replace: body => api.replaceNamespacedNetworkPolicy({ name, namespace, body }),
mutationAllowed,
+ validateExisting,
})
}
diff --git a/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts b/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts
index 7abd63ab8..1168cec7c 100644
--- a/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts
+++ b/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts
@@ -122,6 +122,8 @@ describe('NetworkPolicyReconciler rpc-proxy egress', () => {
metadata: {
name: 'rpc-egress-ctx-gamma-mongodb-mcp',
namespace: 'rpc-proxy',
+ uid: 'rpc-delete-uid',
+ resourceVersion: '7',
labels: {
'clerum.io/managed-by': 'host-context-controller',
'clerum.io/policy-type': 'rpc-proxy-egress',
@@ -147,7 +149,18 @@ describe('NetworkPolicyReconciler rpc-proxy egress', () => {
await reconciler.reconcileContext(ctx1)
const existingRpcProxyPolicies = mockApply.mock.calls
.filter(call => call[2] === 'rpc-proxy')
- .map(call => call[3] as k8s.V1NetworkPolicy)
+ .map(call => {
+ const policy = call[3] as k8s.V1NetworkPolicy
+ const name = policy.metadata?.name
+ return {
+ ...policy,
+ metadata: {
+ ...policy.metadata,
+ uid: `rpc-proxy:${name}:uid`,
+ resourceVersion: '1',
+ },
+ }
+ })
expect(existingRpcProxyPolicies).toHaveLength(2)
vi.clearAllMocks()
@@ -177,6 +190,12 @@ describe('NetworkPolicyReconciler rpc-proxy egress', () => {
expect(mockNetApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
name: 'rpc-egress-ctx-delta-airtable-mcp',
namespace: 'rpc-proxy',
+ body: {
+ preconditions: {
+ uid: 'rpc-proxy:rpc-egress-ctx-delta-airtable-mcp:uid',
+ resourceVersion: '1',
+ },
+ },
})
expect(mockNetApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith({
name: 'rpc-egress-ctx-delta-mongodb-mcp',
diff --git a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
index b440f0470..8675d0341 100755
--- a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
+++ b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
@@ -78,6 +78,7 @@ ORIGINAL_DNS_CONFIG=""
DNS_BLOCKER_IP=""
DNS_RELEASE_COUNT_AT_HOLD=0
DNS_HOLD_COUNT_AT_ARM=0
+DNS_HOLD_COUNT_AT_RETRY_SCHEDULE=0
UPSTREAM_DNS_IP=""
NEW_HCC_POD=""
HCC_UID=""
@@ -184,20 +185,6 @@ hcc_log_contains() {
grep -Fq "$marker" <<<"$logs"
}
-hcc_log_count() {
- local marker=$1 logs
- [ -n "$NEW_HCC_POD" ] || return 1
- logs="$(kctl logs "pod/${NEW_HCC_POD}" -n "$HCC_NS" \
- -c host-context-controller 2>/dev/null)" || return 1
- grep -Fc "$marker" <<<"$logs" || true
-}
-
-hcc_log_count_exceeds() {
- local marker=$1 baseline=$2 current
- current="$(hcc_log_count "$marker")" || return 1
- [ "$current" -gt "$baseline" ]
-}
-
dns_log_contains() {
local marker=$1 logs
logs="$(kctl logs "deployment/${DNS_BLOCKER_NAME}" -n "$HCC_NS" 2>/dev/null)" ||
@@ -231,14 +218,6 @@ dns_released_since_hold() {
[ "$(dns_release_count)" -gt "$DNS_RELEASE_COUNT_AT_HOLD" ]
}
-initial_network_policy_failure_is_absent() {
- local logs
- [ -n "$NEW_HCC_POD" ] || return 1
- logs="$(kctl logs "pod/${NEW_HCC_POD}" -n "$HCC_NS" \
- -c host-context-controller 2>/dev/null)" || return 1
- ! grep -Fq "Initial NetworkPolicy background reconciliation failed:" <<<"$logs"
-}
-
external_egress_retry_progress_is_observed() {
local logs marker
[ -n "$NEW_HCC_POD" ] || return 1
@@ -255,12 +234,8 @@ external_egress_retry_progress_is_observed() {
' <<<"$logs"
}
-external_egress_retry_rearmed_is_observed() {
- local logs
- [ -n "$NEW_HCC_POD" ] || return 1
- logs="$(kctl logs "pod/${NEW_HCC_POD}" -n "$HCC_NS" \
- -c host-context-controller 2>/dev/null)" || return 1
- grep -Fq "Scheduling external egress retry 2/3 for McpServer \"${MCP_NAME}\"" <<<"$logs"
+dns_retry_query_observed_since_schedule() {
+ [ "$(dns_hold_count)" -gt "$DNS_HOLD_COUNT_AT_RETRY_SCHEDULE" ]
}
hcc_identity_is_stable() {
@@ -1271,7 +1246,7 @@ dns_patch="$(jq -cn --arg nameserver "$DNS_BLOCKER_IP" '
options:[
{name:"ndots",value:"1"},
{name:"timeout",value:"30"},
- {name:"attempts",value:"20"}
+ {name:"attempts",value:"1"}
]
}
}}}}
@@ -1370,8 +1345,10 @@ external_egress_policy_absent ||
wait_until 120 "a real same-intent external-egress retry to be scheduled" \
external_egress_retry_progress_is_observed ||
die "the held same-intent refresh did not schedule a real retry"
+DNS_HOLD_COUNT_AT_RETRY_SCHEDULE="$(dns_hold_count)" ||
+ die "could not snapshot DNS hold evidence after the same-intent retry was scheduled"
wait_until 180 "the scheduled same-intent external-egress retry to execute" \
- external_egress_retry_rearmed_is_observed ||
+ dns_retry_query_observed_since_schedule ||
die "the scheduled same-intent external-egress retry did not execute"
probe_new_hcc_ready_endpoint ||
die "HCC lost readiness after a same-intent DNS retry (${HCC_READY_PROBE_DIAGNOSTIC:-HCC_READY_PROBE category=unknown})"
@@ -1452,8 +1429,14 @@ initial_empty_context_log="[NetPol] Reconciling context \"${CONTEXT_ID}\" — al
wait_until 120 "initial NetworkPolicy pass to reconcile the fixture's empty Context snapshot" \
hcc_log_contains "$initial_empty_context_log" ||
die "initial NetworkPolicy pass never reconciled the fixture's empty Context"
-initial_network_policy_failure_is_absent ||
- die "the DNS hold unexpectedly failed the readiness safety lane"
+wait_until 120 "a real divergent external-egress retry to be scheduled" \
+ external_egress_retry_progress_is_observed ||
+ die "the held divergent refresh did not schedule a real retry"
+DNS_HOLD_COUNT_AT_RETRY_SCHEDULE="$(dns_hold_count)" ||
+ die "could not snapshot DNS hold evidence after the divergent retry was scheduled"
+wait_until 180 "the scheduled divergent external-egress retry to execute" \
+ dns_retry_query_observed_since_schedule ||
+ die "the scheduled divergent external-egress retry did not execute"
context_policies_absent ||
die "Context policy appeared before the isolated MODIFIED event"
@@ -1465,10 +1448,6 @@ wait_until 60 "Context API to expose the latest server membership" context_watch
wait_until 60 "HCC Context watch to observe the update during the blocked fleet pass" \
hcc_log_contains "Context watch event: MODIFIED for ${CONTEXT_NAME}" ||
die "HCC did not observe the real Context update while initial MCP convergence was blocked"
-modified_context_log="[NetPol] Reconciling context \"${CONTEXT_ID}\" — allowed servers: [${MCP_NAME}]"
-wait_until 60 "MODIFIED handler to reconcile the fixture's latest Context snapshot" \
- hcc_log_contains "$modified_context_log" ||
- die "the observed MODIFIED event never reconciled the latest Context membership"
wait_until 120 "all three latest-Context NetworkPolicies to converge during the MCP hold" \
context_policies_converged ||
die "Context policies remained blocked behind the held McpServer convergence"
@@ -1490,14 +1469,6 @@ hcc_identity_is_stable ||
ok "the MODIFIED handler, not the initial empty-Context pass, converged all three policies"
ok "global readiness and Context progress continued while the affected runtime stayed blocked"
-initial_policy_run_marker="Running initial NetworkPolicy background reconciliation"
-initial_policy_complete_marker="[NetPol] Full reconciliation complete"
-initial_policy_run_count_before_release="$(hcc_log_count "$initial_policy_run_marker")" ||
- die "could not snapshot initial NetworkPolicy run evidence before DNS release"
-initial_policy_complete_count_before_release="$(
- hcc_log_count "$initial_policy_complete_marker"
-)" || die "could not snapshot initial NetworkPolicy completion evidence before DNS release"
-
release_dns_blocker ||
die "could not release the fixture DNS query"
wait_until 30 "DNS blocker to answer the held query" \
@@ -1514,14 +1485,6 @@ wait_until 300 "McpServer runtime, status, and latest Context NetworkPolicies to
wait_until 300 "all peer MCP/Context runtimes to converge after releasing the held primary egress" \
peer_fleet_converged ||
die "peer MCP/Context fleet did not converge after the held primary egress was released"
-wait_until 60 "initial NetworkPolicy full pass to run" \
- hcc_log_count_exceeds \
- "$initial_policy_run_marker" "$initial_policy_run_count_before_release" ||
- die "initial NetworkPolicy convergence was not observed after releasing MCP convergence"
-wait_until 60 "initial NetworkPolicy retry to complete after DNS release" \
- hcc_log_count_exceeds \
- "$initial_policy_complete_marker" "$initial_policy_complete_count_before_release" ||
- die "initial NetworkPolicy convergence did not recover after DNS release"
hcc_identity_is_stable ||
die "HCC restarted instead of completing the released background convergence"
final_probe="$(probe_hcc_final_context)" ||
diff --git a/scripts/tests/test-hcc-watch-recovery-gate.sh b/scripts/tests/test-hcc-watch-recovery-gate.sh
index 5554eb527..a7baf4043 100755
--- a/scripts/tests/test-hcc-watch-recovery-gate.sh
+++ b/scripts/tests/test-hcc-watch-recovery-gate.sh
@@ -301,20 +301,11 @@ for case_name in detached minikube-profile-missing minikube-profile profile-name
fi
done
-network_policy_failure_absent_function="$(
- sed -n '/^initial_network_policy_failure_is_absent() {$/,/^}$/p' "$MCP_READINESS_GATE"
-)"
retry_progress_function="$(
sed -n '/^external_egress_retry_progress_is_observed() {$/,/^}$/p' "$MCP_READINESS_GATE"
)"
-retry_rearmed_function="$(
- sed -n '/^external_egress_retry_rearmed_is_observed() {$/,/^}$/p' "$MCP_READINESS_GATE"
-)"
-hcc_log_count_function="$(
- sed -n '/^hcc_log_count() {$/,/^}$/p' "$MCP_READINESS_GATE"
-)"
-hcc_log_count_exceeds_function="$(
- sed -n '/^hcc_log_count_exceeds() {$/,/^}$/p' "$MCP_READINESS_GATE"
+retry_query_function="$(
+ sed -n '/^dns_retry_query_observed_since_schedule() {$/,/^}$/p' "$MCP_READINESS_GATE"
)"
if (
NEW_HCC_POD=hcc-pod
@@ -325,19 +316,14 @@ if (
MOCK_HCC_LOG='
[K8s] Initial external egress reconciliation failed for mcp-server/e2e-held-server; runtime reconciliation will stay blocked until retry succeeds: dns timeout
[K8s] Scheduling external egress retry 1/3 for McpServer "e2e-held-server" in 5000ms
-[K8s] Scheduling external egress retry 2/3 for McpServer "e2e-held-server" in 15000ms
'
kctl() { printf '%s\n' "$MOCK_HCC_LOG"; }
- eval "$network_policy_failure_absent_function"
eval "$retry_progress_function"
- eval "$retry_rearmed_function"
- initial_network_policy_failure_is_absent &&
- external_egress_retry_progress_is_observed &&
- external_egress_retry_rearmed_is_observed
+ external_egress_retry_progress_is_observed
); then
- pass "DNS failure remains in the additive runtime lane and does not fail readiness safety"
+ pass "DNS failure is attributed to the dedicated external-egress retry lane"
else
- fail "the injected DNS hold can leak into readiness safety or hide runtime retry progress"
+ fail "the injected DNS hold cannot prove dedicated external-egress retry progress"
fi
if (
NEW_HCC_POD=hcc-pod
@@ -380,62 +366,30 @@ else
fail "a valid early retry marker is lost in a high-volume log buffer"
fi
if (
- NEW_HCC_POD=hcc-pod
- HCC_NS=control-plane
- MCP_NS=mcp-server
- MCP_NAME=e2e-held-server
- CONTEXT_NAME=e2e-context
- MOCK_HCC_LOG='[K8s] Initial NetworkPolicy background reconciliation failed: denied'
- kctl() { printf '%s\n' "$MOCK_HCC_LOG"; }
- eval "$network_policy_failure_absent_function"
- ! initial_network_policy_failure_is_absent
+ DNS_HOLD_COUNT_AT_RETRY_SCHEDULE=3
+ dns_hold_count() { printf '%s\n' 4; }
+ eval "$retry_query_function"
+ dns_retry_query_observed_since_schedule
); then
- pass "the safety predicate rejects an observed NetworkPolicy failure"
+ pass "a post-schedule DNS query proves the dedicated retry executed"
else
- fail "an observed NetworkPolicy safety failure can masquerade as clean certification"
+ fail "a fresh DNS query after scheduling does not prove retry execution"
fi
if (
- NEW_HCC_POD=hcc-pod
- HCC_NS=control-plane
- MCP_NS=mcp-server
- MCP_NAME=e2e-held-server
- CONTEXT_NAME=e2e-context
- kctl() { return 1; }
- eval "$network_policy_failure_absent_function"
- ! initial_network_policy_failure_is_absent
+ DNS_HOLD_COUNT_AT_RETRY_SCHEDULE=3
+ dns_hold_count() { printf '%s\n' 3; }
+ eval "$retry_query_function"
+ ! dns_retry_query_observed_since_schedule
); then
- pass "the safety predicate fails closed when HCC logs are unavailable"
+ pass "a pre-schedule DNS query cannot satisfy retry execution"
else
- fail "the safety predicate passes vacuously when HCC logs are unavailable"
+ fail "stale DNS evidence can masquerade as retry execution"
fi
-
-if (
- NEW_HCC_POD=hcc-pod
- HCC_NS=control-plane
- marker='[NetPol] Full reconciliation complete'
- MOCK_HCC_LOG="$marker"
- kctl() { printf '%s\n' "$MOCK_HCC_LOG"; }
- eval "$hcc_log_count_function"
- eval "$hcc_log_count_exceeds_function"
- baseline="$(hcc_log_count "$marker")" &&
- ! hcc_log_count_exceeds "$marker" "$baseline" &&
- MOCK_HCC_LOG="${MOCK_HCC_LOG}"$'\n'"$marker" &&
- hcc_log_count_exceeds "$marker" "$baseline"
-); then
- pass "post-release NetworkPolicy waits require evidence newer than their baseline snapshot"
-else
- fail "post-release NetworkPolicy waits can pass on a pre-release log marker"
-fi
-# Literal source-code assertions bind both final waits to their pre-release
-# counters; a plain contains check would make either wait vacuous.
-# shellcheck disable=SC2016
-if grep -Fq 'initial_policy_run_count_before_release="$(hcc_log_count "$initial_policy_run_marker")"' \
- "$MCP_READINESS_GATE" &&
- grep -Fq 'initial_policy_complete_count_before_release="$(' "$MCP_READINESS_GATE" &&
- [ "$(grep -Fc 'hcc_log_count_exceeds \' "$MCP_READINESS_GATE")" = 2 ]; then
- pass "both final NetworkPolicy waits are causally fenced by pre-release counts"
+if grep -Fq '{name:"timeout",value:"30"}' "$MCP_READINESS_GATE" &&
+ grep -Fq '{name:"attempts",value:"1"}' "$MCP_READINESS_GATE"; then
+ pass "the DNS fixture disables resolver retransmits that could counterfeit retry execution"
else
- fail "a final NetworkPolicy wait is not fenced from earlier startup logs"
+ fail "the DNS fixture can mistake a resolver retransmit for a dedicated retry"
fi
# Keep the runtime log contract consumed above tied to its producer. Template
@@ -448,15 +402,11 @@ if grep -Fq 'Initial external egress reconciliation failed for ${key};' \
"$HCC_EGRESS_COORDINATOR" &&
grep -Fq 'for McpServer "${this.retryIntents.get(key)!.server.name}"' \
"$HCC_EGRESS_COORDINATOR" &&
- grep -Fq 'Initial NetworkPolicy background reconciliation failed:' \
- "$HCC_K8S_CLIENT" &&
grep -Fq 'Context watch event: ${type} for ${context.name}' \
"$HCC_K8S_CLIENT" &&
grep -Fq 'Running initial NetworkPolicy background reconciliation...' \
"$HCC_K8S_CLIENT" &&
grep -Fq 'Reconciling context "${contextId}" — allowed servers: [${allowedServers.join(' \
- "$HCC_NETWORK_POLICY_RECONCILER" &&
- grep -Fq "[NetPol] Full reconciliation complete" \
"$HCC_NETWORK_POLICY_RECONCILER"; then
pass "MCP readiness log predicates remain bound to their runtime producers"
else