Skip to content

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

TypeScript

fix(hcc): fence readiness revocation snapshots

Alfredo Lopez6b8e8a660a4c
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index f7a9bf6c5..d340287bc 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.170",
+ "version": "0.1.171",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.170",
+ "version": "0.1.171",
"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 b82fa88ea..e0bf3e74e 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.170",
+ "version": "0.1.171",
"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/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.ts
index 2051c8c69..ba373b457 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -286,6 +286,13 @@ vi.mock('./hostReconciler', () => ({
}))
vi.mock('./networkPolicyReconciler', () => ({
+ sameContextDesiredRevision: (
+ expected: { name: string; namespace: string; spec: unknown },
+ current: { name: string; namespace: string; spec: unknown }
+ ) =>
+ expected.name === current.name &&
+ expected.namespace === current.namespace &&
+ JSON.stringify(expected.spec) === JSON.stringify(current.spec),
NetworkPolicyReconciler: class {
ensureDefaultPolicies = mocks.ensureDefaultPolicies
fullReconcile = mocks.netPolFullReconcile
@@ -759,6 +766,8 @@ describe('McpServerWatcher startup', () => {
ensureDefaults: false,
contextInventoryAuthoritative: expect.any(Function),
serverInventoryAuthoritative: expect.any(Function),
+ contextDesiredRevision: expect.any(Function),
+ serverDesiredRevision: expect.any(Function),
})
)
})
@@ -1112,6 +1121,7 @@ describe('McpServerWatcher startup', () => {
const reconciler = (watcher as any).reconciler
const netPol = (watcher as any).netPolReconciler
const callback = (watcher as any).getMcpServerWatchCallback()
+ expect((watcher as any).mcpServerDesiredRevision).toBe(0)
await callback('MODIFIED', {
metadata: {
@@ -1132,6 +1142,7 @@ describe('McpServerWatcher startup', () => {
expect(changed).toHaveBeenCalledOnce()
expect(reconciler.reconcile).not.toHaveBeenCalled()
expect(netPol.reconcileExternalEgress).not.toHaveBeenCalled()
+ expect((watcher as any).mcpServerDesiredRevision).toBe(0)
await callback('MODIFIED', {
metadata: {
@@ -1145,6 +1156,76 @@ describe('McpServerWatcher startup', () => {
spec: { ...previousServer.spec, image: 'clerum/status-server:next' },
})
expect(reconciler.reconcile).toHaveBeenCalledOnce()
+ expect((watcher as any).mcpServerDesiredRevision).toBe(1)
+ await watcher.stop()
+ })
+
+ it('advances McpServer desired revision for owner addition and deletion', async () => {
+ const serverObject = {
+ metadata: {
+ name: 'revision-server',
+ namespace: 'mcp-server',
+ uid: 'revision-server-uid',
+ generation: 1,
+ },
+ spec: {
+ contextRef: 'default',
+ image: 'clerum/revision-server:test',
+ transport: { type: 'streamableHttp' as const, port: 3000 },
+ },
+ }
+ const watcher = new McpServerWatcher()
+ const callback = (watcher as any).getMcpServerWatchCallback()
+
+ expect((watcher as any).mcpServerDesiredRevision).toBe(0)
+ await callback('ADDED', serverObject)
+ expect((watcher as any).mcpServerDesiredRevision).toBe(1)
+ await callback('DELETED', serverObject)
+ expect((watcher as any).mcpServerDesiredRevision).toBe(2)
+
+ await watcher.stop()
+ })
+
+ it('advances Context desired revision only when the authoritative desired cache changes', async () => {
+ const watcher = new McpServerWatcher()
+ let contextWatchCallback:
+ | ((
+ type: string,
+ apiObj: {
+ metadata: { name: string; namespace: string }
+ spec: { contextId: string; mcpServers: string[] }
+ }
+ ) => Promise<void>)
+ | undefined
+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {
+ contextWatchCallback = callback
+ return { abort: vi.fn() }
+ })
+ await (watcher as any).startContextWatch('context-desired-revision-rv')
+ ;(watcher as any).contextCacheSynced = true
+ ;(watcher as any).mcpServerCacheSynced = true
+
+ const added = {
+ metadata: { name: 'revision-context', namespace: 'mcp-server' },
+ spec: { contextId: 'revision-context', mcpServers: [] as string[] },
+ }
+ expect((watcher as any).contextDesiredRevision).toBe(0)
+ await contextWatchCallback!('ADDED', added)
+ expect((watcher as any).contextDesiredRevision).toBe(1)
+
+ await contextWatchCallback!('MODIFIED', added)
+ expect((watcher as any).contextDesiredRevision).toBe(1)
+
+ const modified = {
+ ...added,
+ spec: { ...added.spec, mcpServers: ['revision-server'] },
+ }
+ await contextWatchCallback!('MODIFIED', modified)
+ expect((watcher as any).contextDesiredRevision).toBe(2)
+
+ await contextWatchCallback!('DELETED', modified)
+ expect((watcher as any).contextDesiredRevision).toBe(3)
+
await watcher.stop()
})
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index afeb83c05..b4f6c06b5 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -52,7 +52,7 @@ import {
initialConvergenceLastSuccessTimestampSeconds,
initialConvergenceRetriesTotal,
} from './metrics'
-import { NetworkPolicyReconciler } from './networkPolicyReconciler'
+import { NetworkPolicyReconciler, sameContextDesiredRevision } from './networkPolicyReconciler'
import { McpServerReconciler } from './reconciler'
import { SharedFileSystemReconciler } from './sharedFileSystemReconciler'
import {
@@ -623,6 +623,8 @@ export class McpServerWatcher implements McpServerProvider {
private communicationChannels: Map<string, CommunicationChannelCRD> = new Map()
private mcpWatchGeneration = 0
private contextWatchGeneration = 0
+ private mcpServerDesiredRevision = 0
+ private contextDesiredRevision = 0
// Readiness covers authoritative revocation, not additive fleet completion.
// Generations bind the completed safety sweep to the exact LIST -> WATCH
// pair that supplied its absence decisions. A recovered watch invalidates
@@ -2513,6 +2515,8 @@ export class McpServerWatcher implements McpServerProvider {
resolveCurrentContextById: contextId =>
[...this.contexts.values()].find(context => context.spec.contextId === contextId),
resolveCurrentServer: name => this.servers.get(name),
+ contextDesiredRevision: () => this.contextDesiredRevision,
+ serverDesiredRevision: () => this.mcpServerDesiredRevision,
onAuthoritativeRevocationComplete: () => {
if (!contextInventoryAuthoritative() || !serverInventoryAuthoritative()) return
this.networkPolicyRevocationContextGeneration = contextInventoryGeneration
@@ -3043,13 +3047,17 @@ export class McpServerWatcher implements McpServerProvider {
const previous = this.servers.get(server.name)
// Update cache
+ let desiredStateChanged = false
if (type === 'ADDED' || type === 'MODIFIED') {
+ desiredStateChanged =
+ previous === undefined || !sameMcpServerDesiredRevision(previous, server)
this.servers.set(server.name, server)
} else if (type === 'DELETED') {
if (!previous?.uid || !server.uid || previous.uid === server.uid) {
- this.servers.delete(server.name)
+ desiredStateChanged = this.servers.delete(server.name)
}
}
+ if (desiredStateChanged) this.mcpServerDesiredRevision += 1
// HCC writes McpServer status during reconciliation. Those writes emit
// MODIFIED events but do not change the desired runtime or policy state.
@@ -3351,11 +3359,15 @@ export class McpServerWatcher implements McpServerProvider {
const previous = this.contexts.get(context.name)
// Cache the context for cross-resource re-reconciliation
+ let desiredStateChanged = false
if (type === 'ADDED' || type === 'MODIFIED') {
+ desiredStateChanged =
+ previous === undefined || !sameContextDesiredRevision(previous, context)
this.contexts.set(context.name, context)
} else if (type === 'DELETED') {
- this.contexts.delete(context.name)
+ desiredStateChanged = this.contexts.delete(context.name)
}
+ if (desiredStateChanged) this.contextDesiredRevision += 1
// Re-reconcile every SFS this Context referenced before or after the
// change so SharedFileSystem.status.mountedByContexts stays in sync
diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.ts
index 3fe821902..a5370aeff 100644
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@ -2013,6 +2013,351 @@ describe('NetworkPolicyReconciler', () => {
}
})
+ it('revokes same-name Context allow policies whose authoritative server port changed', async () => {
+ 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 => (call[0] as { body: k8s.V1NetworkPolicy }).body
+ )
+ expect(oldPolicies).toHaveLength(3)
+
+ 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),
+ }
+ }
+ )
+ vi.spyOn(rec, 'reconcileContext').mockResolvedValue(undefined)
+ vi.spyOn(rec, 'reconcileExternalEgress').mockResolvedValue(undefined)
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ await rec.fullReconcile([liveContext], [currentServer], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete,
+ })
+
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'ctx-live-context-live-server',
+ namespace: 'mcp-server',
+ })
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'ctx-live-context-live-server-egress',
+ namespace: 'mcp-host',
+ })
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'rpc-egress-live-context-live-server',
+ namespace: 'rpc-proxy',
+ })
+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
+ })
+
+ it('retains authoritative same-name policies when only API object key order differs', async () => {
+ const server: McpServerCRD = {
+ name: 'live-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'live:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ }
+ const liveContext: ContextCRD = {
+ name: 'live-context-resource',
+ namespace: 'mcp-server',
+ spec: { contextId: 'live-context', mcpServers: [server.name] },
+ }
+ const rec = makeReconciler(mockApi, new Map([[server.name, server]]), mockCustomApi)
+ const reverseObjectKeys = (value: unknown): unknown => {
+ if (Array.isArray(value)) return value.map(reverseObjectKeys)
+ if (value === null || typeof value !== 'object') return value
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>)
+ .reverse()
+ .map(([key, entry]) => [key, reverseObjectKeys(entry)])
+ )
+ }
+
+ await rec.reconcileContext(liveContext)
+ const existingPolicies = mockApi.createNamespacedNetworkPolicy.mock.calls.map(call => {
+ const policy = (call[0] as { body: k8s.V1NetworkPolicy }).body
+ return { ...policy, spec: reverseObjectKeys(policy.spec) as k8s.V1NetworkPolicySpec }
+ })
+ vi.clearAllMocks()
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(
+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {
+ if (labelSelector?.includes('external-egress')) return { items: [] }
+ return {
+ items: existingPolicies.filter(policy => policy.metadata?.namespace === namespace),
+ }
+ }
+ )
+ vi.spyOn(rec, 'reconcileContext').mockResolvedValue(undefined)
+ vi.spyOn(rec, 'reconcileExternalEgress').mockResolvedValue(undefined)
+
+ await rec.fullReconcile([liveContext], [server], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ })
+
+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('revokes same-name DNS egress whose protocol or resolved IP cannot be proven current', async () => {
+ const oldServer: McpServerCRD = {
+ name: 'live-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'live:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'TCP' }],
+ },
+ }
+ const currentServer: McpServerCRD = {
+ ...oldServer,
+ spec: {
+ ...oldServer.spec,
+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'UDP' }],
+ },
+ }
+ const rec = makeReconciler(mockApi, new Map([[oldServer.name, oldServer]]), mockCustomApi)
+
+ await rec.reconcileExternalEgress(oldServer)
+ const oldPolicy = mockApi.createNamespacedNetworkPolicy.mock.calls
+ .map(call => (call[0] as { body: k8s.V1NetworkPolicy }).body)
+ .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')
+ expect(oldPolicy).toBeDefined()
+
+ vi.clearAllMocks()
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(
+ async ({ labelSelector }: { labelSelector?: string }) =>
+ labelSelector?.includes('external-egress') ? { items: [oldPolicy!] } : { items: [] }
+ )
+ vi.spyOn(rec, 'reconcileExternalEgress').mockResolvedValue(undefined)
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ await rec.fullReconcile([], [currentServer], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete,
+ })
+
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: oldPolicy!.metadata!.name!,
+ namespace: 'mcp-server',
+ })
+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
+ })
+
+ it('does not certify revocation when an earlier Context changes while a later owner is paused', async () => {
+ const contexts: ContextCRD[] = ['first', 'later'].map(contextId => ({
+ name: `${contextId}-resource`,
+ namespace: 'mcp-server',
+ spec: { contextId, mcpServers: [] },
+ }))
+ const currentContexts = new Map(contexts.map(context => [context.name, context]))
+ let contextDesiredRevision = 10
+ let laterPaused = false
+ const laterStarted = deferred()
+ const releaseLater = deferred()
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ const fullPass = reconciler.fullReconcile(contexts, [], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ resolveCurrentContext: name => currentContexts.get(name),
+ runContextEffect: async (contextId, work) => {
+ if (contextId === 'later' && !laterPaused) {
+ laterPaused = true
+ laterStarted.resolve(undefined)
+ await releaseLater.promise
+ }
+ await work()
+ },
+ contextDesiredRevision: () => contextDesiredRevision,
+ onAuthoritativeRevocationComplete,
+ })
+
+ await laterStarted.promise
+ currentContexts.set('first-resource', {
+ ...contexts[0],
+ spec: { ...contexts[0].spec, mcpServers: ['replacement'] },
+ })
+ contextDesiredRevision += 1
+ releaseLater.resolve(undefined)
+
+ await expect(fullPass).rejects.toThrow(/desired NetworkPolicy inventory changed/i)
+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()
+ })
+
+ it('does not certify revocation when a new owner is added after the global inventory LISTs', async () => {
+ const anchorContext: ContextCRD = {
+ name: 'anchor-resource',
+ namespace: 'mcp-server',
+ spec: { contextId: 'anchor', mcpServers: [] },
+ }
+ const currentContexts = new Map([[anchorContext.name, anchorContext]])
+ let contextDesiredRevision = 21
+ const safetyEffectStarted = deferred()
+ const releaseSafetyEffect = deferred()
+ let safetyEffectPaused = false
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ const fullPass = reconciler.fullReconcile([anchorContext], [], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ resolveCurrentContext: name => currentContexts.get(name),
+ runContextEffect: async (_contextId, work) => {
+ if (!safetyEffectPaused) {
+ safetyEffectPaused = true
+ safetyEffectStarted.resolve(undefined)
+ await releaseSafetyEffect.promise
+ }
+ await work()
+ },
+ contextDesiredRevision: () => contextDesiredRevision,
+ onAuthoritativeRevocationComplete,
+ })
+
+ await safetyEffectStarted.promise
+ currentContexts.set('late-resource', {
+ name: 'late-resource',
+ namespace: 'mcp-server',
+ spec: { contextId: 'late', mcpServers: [] },
+ })
+ contextDesiredRevision += 1
+ releaseSafetyEffect.resolve(undefined)
+
+ await expect(fullPass).rejects.toThrow(/desired NetworkPolicy inventory changed/i)
+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()
+ })
+
+ it('does not certify revocation when a new McpServer owner is added after inventory LISTs', async () => {
+ const anchorServer: McpServerCRD = {
+ name: 'anchor-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'anchor:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ }
+ const currentServers = new Map([[anchorServer.name, anchorServer]])
+ let serverDesiredRevision = 31
+ const safetyEffectStarted = deferred()
+ const releaseSafetyEffect = deferred()
+ let safetyEffectPaused = false
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ const fullPass = reconciler.fullReconcile([], [anchorServer], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ resolveCurrentServer: name => currentServers.get(name),
+ runServerEffect: async (_serverName, work) => {
+ if (!safetyEffectPaused) {
+ safetyEffectPaused = true
+ safetyEffectStarted.resolve(undefined)
+ await releaseSafetyEffect.promise
+ }
+ await work()
+ },
+ serverDesiredRevision: () => serverDesiredRevision,
+ onAuthoritativeRevocationComplete,
+ })
+
+ await safetyEffectStarted.promise
+ currentServers.set('late-server', {
+ name: 'late-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'late:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ })
+ serverDesiredRevision += 1
+ releaseSafetyEffect.resolve(undefined)
+
+ await expect(fullPass).rejects.toThrow(/desired NetworkPolicy inventory changed/i)
+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()
+ })
+
+ it('does not certify revocation when desired inventory changes while default policies are ensured', async () => {
+ const context: ContextCRD = {
+ name: 'default-window-context',
+ namespace: 'mcp-server',
+ spec: { contextId: 'default-window', mcpServers: [] },
+ }
+ const server: McpServerCRD = {
+ name: 'default-window-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default-window',
+ image: 'default-window:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ }
+ let contextDesiredRevision = 41
+ let serverDesiredRevision = 51
+ const defaultsStarted = deferred()
+ const releaseDefaults = deferred()
+ const onAuthoritativeRevocationComplete = vi.fn()
+ vi.spyOn(reconciler, 'ensureDefaultPolicies').mockImplementation(async () => {
+ defaultsStarted.resolve(undefined)
+ await releaseDefaults.promise
+ })
+
+ const fullPass = reconciler.fullReconcile([context], [server], {
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ contextDesiredRevision: () => contextDesiredRevision,
+ serverDesiredRevision: () => serverDesiredRevision,
+ onAuthoritativeRevocationComplete,
+ })
+
+ await defaultsStarted.promise
+ contextDesiredRevision += 1
+ serverDesiredRevision += 1
+ releaseDefaults.resolve(undefined)
+
+ await expect(fullPass).rejects.toThrow(/desired NetworkPolicy inventory changed/i)
+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()
+ })
+
it('does not signal authoritative revocation when a live-owner delete fails', async () => {
const liveContext: ContextCRD = {
name: 'live-context-resource',
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index d6273ccc8..26a5c8f95 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -49,7 +49,7 @@ type NetworkPolicyMutationOptions = {
isCurrent?: () => boolean
}
-function sameContextDesiredRevision(expected: ContextCRD, current: ContextCRD): boolean {
+export function sameContextDesiredRevision(expected: ContextCRD, current: ContextCRD): boolean {
return (
expected.name === current.name &&
expected.namespace === current.namespace &&
@@ -57,6 +57,27 @@ function sameContextDesiredRevision(expected: ContextCRD, current: ContextCRD):
)
}
+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)])
+ )
+}
+
+function sameNetworkPolicySpec(
+ existing: k8s.V1NetworkPolicy,
+ desired: k8s.V1NetworkPolicy
+): boolean {
+ return (
+ JSON.stringify(canonicalizeNetworkPolicyValue(existing.spec)) ===
+ JSON.stringify(canonicalizeNetworkPolicyValue(desired.spec))
+ )
+}
+
const GROUP = 'clerum.io'
const VERSION = 'v1alpha1'
const PLURAL_MCPSERVERS = 'mcpservers'
@@ -188,6 +209,13 @@ export interface NetworkPolicyFullReconcileOptions {
resolveCurrentContext?: (name: string) => ContextCRD | undefined
resolveCurrentContextById?: (contextId: string) => ContextCRD | undefined
resolveCurrentServer?: (name: string) => McpServerCRD | undefined
+ /**
+ * Monotonic desired-state revisions fence ordinary watch events that arrive
+ * after an owner has completed its safety turn. Watch generations remain the
+ * separate authority fence for LIST -> WATCH recovery.
+ */
+ contextDesiredRevision?: () => number
+ serverDesiredRevision?: () => number
/**
* Called only after every authoritative orphan-allow revocation lane has
* completed. Additive Context/McpServer convergence intentionally happens
@@ -468,54 +496,21 @@ export class NetworkPolicyReconciler {
// ─── Context-Based Policies ──────────────────────────────────────────
- /**
- * Reconcile NetworkPolicies for a Context CRD.
- * Creates one policy per allowed MCP server.
- */
- async reconcileContext(
+ private buildContextAllowPolicies(
context: ContextCRD,
- options: NetworkPolicyMutationOptions = {}
- ): Promise<void> {
- const callerIsCurrent = options.isCurrent ?? (() => true)
- if (!callerIsCurrent()) return
+ server: McpServerCRD
+ ): {
+ ingress: k8s.V1NetworkPolicy
+ hostEgress: k8s.V1NetworkPolicy
+ rpcProxyEgress: k8s.V1NetworkPolicy
+ } {
const contextId = context.spec.contextId
- const allowedServers = context.spec.mcpServers || []
- const selectedServers = new Map(
- allowedServers.map(serverName => [serverName, this.serverCache.get(serverName)])
- )
- const isCurrent = (): boolean =>
- callerIsCurrent() &&
- allowedServers.every(serverName => {
- const selected = selectedServers.get(serverName)
- const current = this.serverCache.get(serverName)
- if (!selected || !current) return selected === current
- return sameMcpServerDesiredRevision(selected, current)
- })
- if (!isCurrent()) return
-
- console.log(
- `[NetPol] Reconciling context "${contextId}" — allowed servers: [${allowedServers.join(', ')}]`
- )
-
- const existingPolicies = await this.listPoliciesForContext(contextId)
- if (!isCurrent()) return
-
- // Create or update policies for each allowed server
- for (const serverName of allowedServers) {
- if (!isCurrent()) return
- const server = this.serverCache.get(serverName)
- if (!server) {
- console.warn(
- `[NetPol] McpServer "${serverName}" not found in cache — skipping policy for context "${contextId}"`
- )
- continue
- }
-
- const name = this.policyName(contextId, serverName)
- const port = server.spec.transport.port || 3000
+ const serverName = server.name
+ const name = this.policyName(contextId, serverName)
+ const port = server.spec.transport.port || 3000
- // L2 ingress: allow scoped mcp-host/rpc-proxy access to this MCP server.
- const ingressPolicy: k8s.V1NetworkPolicy = {
+ return {
+ ingress: {
apiVersion: 'networking.k8s.io/v1',
kind: 'NetworkPolicy',
metadata: {
@@ -564,7 +559,6 @@ export class NetworkPolicyReconciler {
},
},
{
- // MCP Proxy ingress: allow proxy to reach MCP servers
namespaceSelector: {
matchLabels: {
'kubernetes.io/metadata.name': config.namespace,
@@ -581,19 +575,12 @@ export class NetworkPolicyReconciler {
},
],
},
- }
-
- await this.applyPolicy(name, ingressPolicy, isCurrent)
- if (!isCurrent()) return
-
- // L2 egress counterpart: allow traffic FROM mcp-host pods TO this MCP server
- // Without this, L0 egress deny-all blocks agents from reaching MCP servers.
- const egressName = `${name}-egress`
- const egressPolicy: k8s.V1NetworkPolicy = {
+ },
+ hostEgress: {
apiVersion: 'networking.k8s.io/v1',
kind: 'NetworkPolicy',
metadata: {
- name: egressName,
+ name: `${name}-egress`,
namespace: config.hostNamespace,
labels: {
[MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
@@ -630,20 +617,79 @@ export class NetworkPolicyReconciler {
},
],
},
+ },
+ rpcProxyEgress: this.buildRpcProxyEgressPolicy(contextId, serverName, port),
+ }
+ }
+
+ /**
+ * Reconcile NetworkPolicies for a Context CRD.
+ * Creates one policy per allowed MCP server.
+ */
+ async reconcileContext(
+ context: ContextCRD,
+ options: NetworkPolicyMutationOptions = {}
+ ): Promise<void> {
+ const callerIsCurrent = options.isCurrent ?? (() => true)
+ if (!callerIsCurrent()) return
+ const contextId = context.spec.contextId
+ const allowedServers = context.spec.mcpServers || []
+ const selectedServers = new Map(
+ allowedServers.map(serverName => [serverName, this.serverCache.get(serverName)])
+ )
+ const isCurrent = (): boolean =>
+ callerIsCurrent() &&
+ allowedServers.every(serverName => {
+ const selected = selectedServers.get(serverName)
+ const current = this.serverCache.get(serverName)
+ if (!selected || !current) return selected === current
+ return sameMcpServerDesiredRevision(selected, current)
+ })
+ if (!isCurrent()) return
+
+ console.log(
+ `[NetPol] Reconciling context "${contextId}" — allowed servers: [${allowedServers.join(', ')}]`
+ )
+
+ const existingPolicies = await this.listPoliciesForContext(contextId)
+ if (!isCurrent()) return
+
+ // Create or update policies for each allowed server.
+ for (const serverName of allowedServers) {
+ if (!isCurrent()) return
+ const server = this.serverCache.get(serverName)
+ if (!server) {
+ console.warn(
+ `[NetPol] McpServer "${serverName}" not found in cache — skipping policy for context "${contextId}"`
+ )
+ continue
}
+ const desired = this.buildContextAllowPolicies(context, server)
+ const ingressName = desired.ingress.metadata!.name!
+ await this.applyPolicy(ingressName, desired.ingress, isCurrent)
+ if (!isCurrent()) return
+
+ const hostEgressName = desired.hostEgress.metadata!.name!
await applyNetworkPolicy(
this.networkingApi,
- egressName,
+ hostEgressName,
config.hostNamespace,
- egressPolicy,
+ desired.hostEgress,
'[NetPol]',
isCurrent
)
if (!isCurrent()) return
- // L2 rpc-proxy egress: allow rpc-proxy pods to reach this MCP server
- await this.ensureRpcProxyEgress(contextId, serverName, port, isCurrent)
+ const rpcProxyEgressName = desired.rpcProxyEgress.metadata!.name!
+ await applyNetworkPolicy(
+ this.networkingApi,
+ rpcProxyEgressName,
+ config.rpcProxyNamespace,
+ desired.rpcProxyEgress,
+ '[NetPol]',
+ isCurrent
+ )
}
await this.revokeStaleContextAllows(context, isCurrent, { context: existingPolicies })
@@ -661,15 +707,17 @@ export class NetworkPolicyReconciler {
if (!isCurrent()) return false
const contextId = context.spec.contextId
const allowedServers = context.spec.mcpServers || []
- const desiredNames = new Set(
- allowedServers.map(serverName => this.policyName(contextId, serverName))
- )
- const desiredEgressNames = new Set(
- allowedServers.map(serverName => `${this.policyName(contextId, serverName)}-egress`)
- )
- const desiredRpcProxyNames = new Set(
- allowedServers.map(serverName => `rpc-egress-${contextId}-${serverName}`)
- )
+ const desiredIngress = new Map<string, k8s.V1NetworkPolicy>()
+ const desiredHostEgress = new Map<string, k8s.V1NetworkPolicy>()
+ const desiredRpcProxyEgress = new Map<string, k8s.V1NetworkPolicy>()
+ for (const serverName of allowedServers) {
+ const server = this.serverCache.get(serverName)
+ if (!server) continue
+ const desired = this.buildContextAllowPolicies(context, server)
+ desiredIngress.set(desired.ingress.metadata!.name!, desired.ingress)
+ desiredHostEgress.set(desired.hostEgress.metadata!.name!, desired.hostEgress)
+ desiredRpcProxyEgress.set(desired.rpcProxyEgress.metadata!.name!, desired.rpcProxyEgress)
+ }
const existingPolicies =
listedPolicies?.context ?? (await this.listPoliciesForContext(contextId))
@@ -677,8 +725,9 @@ export class NetworkPolicyReconciler {
for (const existing of existingPolicies) {
if (!isCurrent()) return false
const existingName = existing.metadata?.name || ''
- if (!desiredNames.has(existingName)) {
- console.log(`[NetPol] Deleting orphaned policy "${existingName}"`)
+ const desired = desiredIngress.get(existingName)
+ if (!desired || !sameNetworkPolicySpec(existing, desired)) {
+ console.log(`[NetPol] Deleting stale or orphaned policy "${existingName}"`)
await this.deletePolicy(existingName, isCurrent)
}
}
@@ -689,8 +738,9 @@ export class NetworkPolicyReconciler {
for (const existing of existingEgressPolicies) {
if (!isCurrent()) return false
const existingName = existing.metadata?.name || ''
- if (!desiredEgressNames.has(existingName)) {
- console.log(`[NetPol] Deleting orphaned L2 egress policy "${existingName}"`)
+ const desired = desiredHostEgress.get(existingName)
+ if (!desired || !sameNetworkPolicySpec(existing, desired)) {
+ console.log(`[NetPol] Deleting stale or orphaned L2 egress policy "${existingName}"`)
await this.deleteEgressPolicy(existingName, isCurrent)
}
}
@@ -701,8 +751,9 @@ export class NetworkPolicyReconciler {
for (const existing of existingRpcProxyPolicies) {
if (!isCurrent()) return false
const existingName = existing.metadata?.name || ''
- if (!desiredRpcProxyNames.has(existingName)) {
- console.log(`[NetPol] Deleting orphaned rpc-proxy egress policy "${existingName}"`)
+ const desired = desiredRpcProxyEgress.get(existingName)
+ if (!desired || !sameNetworkPolicySpec(existing, desired)) {
+ console.log(`[NetPol] Deleting stale or orphaned rpc-proxy egress policy "${existingName}"`)
await this.deletePolicyInNamespace(config.rpcProxyNamespace, existingName, isCurrent)
}
}
@@ -748,6 +799,11 @@ export class NetworkPolicyReconciler {
): Promise<void> {
console.log(`[NetPol] Running full reconciliation for ${contexts.length} Context(s)`)
+ // The revision fence starts at invocation, before any asynchronous
+ // default-policy setup can interleave a watch update with this snapshot.
+ const selectedContextDesiredRevision = options.contextDesiredRevision?.()
+ const selectedServerDesiredRevision = options.serverDesiredRevision?.()
+
if (options.ensureDefaults !== false) {
await this.ensureDefaultPolicies()
}
@@ -956,8 +1012,13 @@ export class NetworkPolicyReconciler {
}
}
+ const inventoryDesiredRevisionChanged =
+ (selectedContextDesiredRevision !== undefined &&
+ options.contextDesiredRevision?.() !== selectedContextDesiredRevision) ||
+ (selectedServerDesiredRevision !== undefined &&
+ options.serverDesiredRevision?.() !== selectedServerDesiredRevision)
if (
- liveDesiredRevisionChanged &&
+ (liveDesiredRevisionChanged || inventoryDesiredRevisionChanged) &&
contextCleanupAuthoritative() &&
serverCleanupAuthoritative()
) {
@@ -1034,11 +1095,110 @@ export class NetworkPolicyReconciler {
// ─── L3 External Egress ────────────────────────────────────────────
- private desiredExternalEgressPolicyNames(server: McpServerCRD): Set<string> {
- const desired = new Set<string>()
+ private buildPublicWebEgressPolicy(server: McpServerCRD, name: string): k8s.V1NetworkPolicy {
+ return {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: {
+ name,
+ namespace: server.namespace,
+ labels: {
+ [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
+ [POLICY_TYPE_LABEL]: EXTERNAL_EGRESS_POLICY_TYPE,
+ [MCPSERVER_LABEL]: server.name,
+ [EGRESS_CLASS_LABEL]: 'public-web',
+ },
+ },
+ spec: {
+ podSelector: {
+ matchLabels: { [MCPSERVER_LABEL]: server.name },
+ },
+ policyTypes: ['Egress'],
+ egress: [
+ {
+ to: [
+ {
+ ipBlock: {
+ cidr: '0.0.0.0/0',
+ except: PUBLIC_EGRESS_EXCEPT_CIDRS,
+ },
+ },
+ ],
+ ports: [
+ { port: 443, protocol: 'TCP' },
+ { port: 80, protocol: 'TCP' },
+ ],
+ },
+ ],
+ },
+ }
+ }
+
+ private buildExactHostEgressPolicy(
+ server: McpServerCRD,
+ name: string,
+ binding: EgressBinding,
+ cidrs: string[]
+ ): k8s.V1NetworkPolicy {
+ return {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: {
+ name,
+ namespace: server.namespace,
+ labels: {
+ [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
+ [POLICY_TYPE_LABEL]: EXTERNAL_EGRESS_POLICY_TYPE,
+ [MCPSERVER_LABEL]: server.name,
+ [EGRESS_CLASS_LABEL]: 'exact-host',
+ },
+ },
+ spec: {
+ podSelector: {
+ matchLabels: { [MCPSERVER_LABEL]: server.name },
+ },
+ policyTypes: ['Egress'],
+ egress: cidrs.map(cidr => ({
+ to: [{ ipBlock: { cidr } }],
+ ports: [{ port: binding.port!, protocol: binding.protocol ?? 'TCP' }],
+ })),
+ },
+ }
+ }
+
+ private desiredProvableExternalEgressPolicies(
+ server: McpServerCRD
+ ): Map<string, k8s.V1NetworkPolicy> {
+ const desired = new Map<string, k8s.V1NetworkPolicy>()
for (const binding of server.spec.egressBindings ?? []) {
const name = this.externalEgressPolicyName(server.name, binding)
- if (name) desired.add(name)
+ if (!name) continue
+ const egressClass = binding.egressClass ?? 'exact-host'
+ if (
+ egressClass === 'public-web' &&
+ !binding.dns &&
+ !binding.cidr &&
+ binding.port === undefined &&
+ binding.protocol === undefined
+ ) {
+ desired.set(name, this.buildPublicWebEgressPolicy(server, name))
+ continue
+ }
+ if (
+ egressClass === 'exact-host' &&
+ binding.cidr &&
+ isAllowedExternalEgressCidr(binding.cidr) &&
+ binding.port !== undefined &&
+ Number.isInteger(binding.port) &&
+ binding.port >= 1 &&
+ binding.port <= 65535
+ ) {
+ desired.set(name, this.buildExactHostEgressPolicy(server, name, binding, [binding.cidr]))
+ }
+ // DNS-derived IPs are intentionally not retained in the safety phase:
+ // their currentness cannot be proven without the slow external lookup.
+ // The additive phase resolves DNS and recreates the policy after stale
+ // allows have been revoked and readiness can become available.
}
return desired
}
@@ -1053,13 +1213,15 @@ export class NetworkPolicyReconciler {
listedPolicies ??
(await this.listExternalEgressPoliciesForServer(server.name, server.namespace))
if (!isCurrent()) return false
- const desiredPolicyNames = this.desiredExternalEgressPolicyNames(server)
+ const desiredPolicies = this.desiredProvableExternalEgressPolicies(server)
await this.cleanupExternalEgress(
server.name,
server.namespace,
existingPolicies.filter(policy => {
const name = policy.metadata?.name
- return Boolean(name) && !desiredPolicyNames.has(name!)
+ if (!name) return false
+ const desired = desiredPolicies.get(name)
+ return !desired || !sameNetworkPolicySpec(policy, desired)
}),
async () => isCurrent()
)
@@ -1168,56 +1330,17 @@ export class NetworkPolicyReconciler {
}
desiredPolicyNames.add(name)
-
- const policy: k8s.V1NetworkPolicy = {
- apiVersion: 'networking.k8s.io/v1',
- kind: 'NetworkPolicy',
- metadata: {
- name,
- namespace: server.namespace,
- labels: {
- [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
- [POLICY_TYPE_LABEL]: EXTERNAL_EGRESS_POLICY_TYPE,
- [MCPSERVER_LABEL]: server.name,
- [EGRESS_CLASS_LABEL]: egressClass,
- },
- },
- spec: {
- podSelector: {
- matchLabels: { [MCPSERVER_LABEL]: server.name },
- },
- policyTypes: ['Egress'],
- egress: [
- {
- to: [
- {
- ipBlock: {
- cidr: '0.0.0.0/0',
- except: PUBLIC_EGRESS_EXCEPT_CIDRS,
- },
- },
- ],
- ports: [
- { port: 443, protocol: 'TCP' },
- { port: 80, protocol: 'TCP' },
- ],
- },
- ],
- },
- }
-
await applyNetworkPolicy(
this.networkingApi,
name,
server.namespace,
- policy,
+ this.buildPublicWebEgressPolicy(server, name),
'[NetPol]',
isCurrent
)
continue
}
- const protocol = binding.protocol ?? 'TCP'
if (
binding.port === undefined ||
!Number.isInteger(binding.port) ||
@@ -1279,37 +1402,11 @@ export class NetworkPolicyReconciler {
}
desiredPolicyNames.add(name)
-
- const policy: k8s.V1NetworkPolicy = {
- apiVersion: 'networking.k8s.io/v1',
- kind: 'NetworkPolicy',
- metadata: {
- name,
- namespace: server.namespace,
- labels: {
- [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
- [POLICY_TYPE_LABEL]: EXTERNAL_EGRESS_POLICY_TYPE,
- [MCPSERVER_LABEL]: server.name,
- [EGRESS_CLASS_LABEL]: egressClass,
- },
- },
- spec: {
- podSelector: {
- matchLabels: { [MCPSERVER_LABEL]: server.name },
- },
- policyTypes: ['Egress'],
- egress: cidrs.map(cidr => ({
- to: [{ ipBlock: { cidr } }],
- ports: [{ port: binding.port, protocol }],
- })),
- },
- }
-
await applyNetworkPolicy(
this.networkingApi,
name,
server.namespace,
- policy,
+ this.buildExactHostEgressPolicy(server, name, binding, cidrs),
'[NetPol]',
isCurrent
)
@@ -1744,18 +1841,13 @@ export class NetworkPolicyReconciler {
// ─── RPC-Proxy Egress (L2) ──────────────────────────────────────────
- /**
- * Create or update an egress policy in the rpc-proxy namespace allowing
- * rpc-proxy pods to reach a specific MCP server on a given port.
- */
- private async ensureRpcProxyEgress(
+ private buildRpcProxyEgressPolicy(
contextId: string,
serverName: string,
- port: number,
- isCurrent?: () => boolean
- ): Promise<void> {
+ port: number
+ ): k8s.V1NetworkPolicy {
const name = `rpc-egress-${contextId}-${serverName}`
- const policy: k8s.V1NetworkPolicy = {
+ return {
apiVersion: 'networking.k8s.io/v1',
kind: 'NetworkPolicy',
metadata: {
@@ -1786,14 +1878,6 @@ export class NetworkPolicyReconciler {
],
},
}
- await applyNetworkPolicy(
- this.networkingApi,
- name,
- config.rpcProxyNamespace,
- policy,
- '[NetPol]',
- isCurrent
- )
}
/** Delete all rpc-proxy egress policies for a given context. */
diff --git a/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts b/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts
index a93e20eed..7abd63ab8 100644
--- a/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts
+++ b/host-context-controller/test/networkPolicyReconciler.rpcEgress.test.ts
@@ -145,6 +145,10 @@ describe('NetworkPolicyReconciler rpc-proxy egress', () => {
// First reconcile with both servers
const ctx1 = makeContext('ctx-delta', ['mongodb-mcp', 'airtable-mcp'])
await reconciler.reconcileContext(ctx1)
+ const existingRpcProxyPolicies = mockApply.mock.calls
+ .filter(call => call[2] === 'rpc-proxy')
+ .map(call => call[3] as k8s.V1NetworkPolicy)
+ expect(existingRpcProxyPolicies).toHaveLength(2)
vi.clearAllMocks()
mockNetApi.listNamespacedNetworkPolicy.mockImplementation(
@@ -154,10 +158,7 @@ describe('NetworkPolicyReconciler rpc-proxy egress', () => {
String(labelSelector).includes('clerum.io/context=ctx-delta')
) {
return {
- items: [
- { metadata: { name: 'rpc-egress-ctx-delta-mongodb-mcp' } },
- { metadata: { name: 'rpc-egress-ctx-delta-airtable-mcp' } },
- ],
+ items: existingRpcProxyPolicies,
}
}
return { items: [] }
diff --git a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
index 74f440cbc..9ac3ecd06 100755
--- a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
+++ b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
@@ -4,12 +4,13 @@
#
# The gate runs only on an exact-HEAD, branch-owned Minikube profile. It routes
# HCC DNS through an isolated in-cluster proxy that forwards every query except
-# one fixture hostname. Holding that single A query blocks real initial
-# McpServer external-egress reconciliation without a production test hook.
-# While the query is held, the gate proves readiness and discovery, applies a
-# real Context watch update, and requires that Context's three NetworkPolicies
-# to converge independently of the blocked McpServer entity. It then releases
-# DNS and proves eventual McpServer runtime convergence.
+# one fixture hostname. The gate first lets HCC create a real external-egress
+# policy, then changes that same DNS binding's protocol while HCC is stopped.
+# Holding the next A query proves HCC removes the now-unprovable old allow
+# before it reports Ready. While the query is held, the gate also applies a
+# real Context watch update and requires that Context's three NetworkPolicies
+# converge independently. It then releases DNS and proves eventual McpServer
+# runtime convergence.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@@ -66,6 +67,8 @@ POLICY_TYPE_LABEL="clerum.io/policy-type"
CONTEXT_LABEL="clerum.io/context"
EXTERNAL_EGRESS_CIDR="93.184.216.34/32"
EXTERNAL_EGRESS_PORT=443
+INITIAL_EXTERNAL_EGRESS_PROTOCOL=TCP
+EXTERNAL_EGRESS_PROTOCOL=UDP
ORIGINAL_REPLICAS=""
ORIGINAL_DNS_POLICY=""
ORIGINAL_DNS_CONFIG=""
@@ -201,8 +204,7 @@ resource_absent() {
fixture_mcp_runtime_absent() {
local external_egress_policies
- resource_absent deployment "$MCP_NAME" "$MCP_NS" &&
- resource_absent service "$MCP_NAME" "$MCP_NS" || return 1
+ fixture_runtime_absent || return 1
external_egress_policies="$(
kctl get networkpolicy -n "$MCP_NS" \
-l "${MCP_SERVER_LABEL}=${MCP_NAME},${POLICY_TYPE_LABEL}=external-egress" \
@@ -211,11 +213,20 @@ fixture_mcp_runtime_absent() {
[ -z "$external_egress_policies" ]
}
+fixture_runtime_absent() {
+ resource_absent deployment "$MCP_NAME" "$MCP_NS" &&
+ resource_absent service "$MCP_NAME" "$MCP_NS"
+}
+
fixture_mcp_convergence_absent() {
fixture_mcp_runtime_absent &&
kctl get mcpserver "$MCP_NAME" -n "$MCP_NS" -o json 2>/dev/null |
jq -e '
- any(.status.conditions[]?; .type == "Ready" and .status == "True") | not
+ any(
+ .status.conditions[]?;
+ .type == "Ready" and .status == "True" and
+ (.observedGeneration // -1) == .metadata.generation
+ ) | not
' >/dev/null
}
@@ -314,7 +325,8 @@ context_policies_converged() {
' >/dev/null
}
-external_egress_policy_converged() {
+external_egress_policy_converged_with_protocol() {
+ local protocol=$1
kctl get networkpolicy -n "$MCP_NS" \
-l "${MCP_SERVER_LABEL}=${MCP_NAME},${POLICY_TYPE_LABEL}=external-egress" \
-o json |
@@ -325,6 +337,7 @@ external_egress_policy_converged() {
--arg managedByValue "$MANAGED_BY_VALUE" \
--arg serverLabel "$MCP_SERVER_LABEL" \
--arg policyTypeLabel "$POLICY_TYPE_LABEL" \
+ --arg protocol "$protocol" \
--argjson port "$EXTERNAL_EGRESS_PORT" '
(.items | length) == 1 and
.items[0].metadata.labels[$managedByLabel] == $managedByValue and
@@ -333,12 +346,16 @@ external_egress_policy_converged() {
.items[0].spec.podSelector.matchLabels[$serverLabel] == $server and
.items[0].spec.policyTypes == ["Egress"] and
(.items[0].spec.egress | length) == 1 and
- .items[0].spec.egress[0].ports == [{port: $port, protocol: "TCP"}] and
+ .items[0].spec.egress[0].ports == [{port: $port, protocol: $protocol}] and
(.items[0].spec.egress[0].to | length) == 1 and
.items[0].spec.egress[0].to[0].ipBlock == {cidr: $cidr}
' >/dev/null
}
+external_egress_policy_converged() {
+ external_egress_policy_converged_with_protocol "$EXTERNAL_EGRESS_PROTOCOL"
+}
+
fixture_resources_absent() {
fixture_mcp_runtime_absent && context_policies_absent
}
@@ -359,6 +376,13 @@ context_watch_has_latest_spec() {
jq -e --arg server "$MCP_NAME" '.spec.mcpServers == [$server]' >/dev/null
}
+mcp_egress_binding_is_udp() {
+ kctl get mcpserver "$MCP_NAME" -n "$MCP_NS" -o json |
+ jq -e --arg dns "$TARGET_DNS" '
+ .spec.egressBindings == [{dns: $dns, port: 443, protocol: "UDP"}]
+ ' >/dev/null
+}
+
fixture_converged() {
local desired available
desired="$(kctl get deployment "$MCP_NAME" -n "$MCP_NS" \
@@ -528,6 +552,37 @@ NODE
node -e "$release_script"
}
+hold_dns_blocker() {
+ local hold_script
+ hold_script="$(cat <<'NODE'
+const http = require('http');
+const request = http.request(
+ {host: '127.0.0.1', port: 8090, path: '/hold', method: 'POST'},
+ response => {
+ response.resume();
+ response.on('end', () => process.exit(response.statusCode === 200 ? 0 : 2));
+ }
+);
+request.setTimeout(5000, () => request.destroy(new Error('timeout')));
+request.once('error', error => { console.error(error.message); process.exit(3); });
+request.end();
+NODE
+)"
+ kctl exec "deployment/${DNS_BLOCKER_NAME}" -n "$HCC_NS" -c dns-blocker -- \
+ node -e "$hold_script"
+}
+
+delete_fixture_runtime_preserving_external_policy() {
+ local failed=0
+ kctl delete deployment "$MCP_NAME" -n "$MCP_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete service "$MCP_NAME" -n "$MCP_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete configmap "${MCP_NAME}-nginx-conf" -n "$MCP_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ [ "$failed" = 0 ] && fixture_runtime_absent
+}
+
delete_dns_blocker_fixture() {
local failed=0
kctl delete networkpolicy "$HCC_DNS_POLICY" "$DNS_BLOCKER_POLICY" -n "$HCC_NS" \
@@ -755,7 +810,7 @@ spec:
const dgram=require('node:dgram'),http=require('node:http'),
net=require('node:net');
const target=process.env.TARGET_DNS,upstream=process.env.UPSTREAM_DNS;
- const udp=dgram.createSocket('udp4');let released=false;const held=[];
+ const udp=dgram.createSocket('udp4');let released=process.env.START_RELEASED==='1';const held=[];
function question(message){let offset=12,labels=[];while(offset<message.length){
const length=message[offset++];if(length===0)break;if(offset+length>message.length)
return null;labels.push(message.subarray(offset,offset+length).toString('ascii'));
@@ -805,11 +860,14 @@ spec:
});tcp.listen(8053,'0.0.0.0',listening);
http.createServer((request,response)=>{if(request.method==='POST'&&
request.url==='/release'){released=true;while(held.length)respond(held.shift());
- response.writeHead(200);response.end('released');return;}response.writeHead(404);
- response.end();}).listen(8090,'127.0.0.1');
+ response.writeHead(200);response.end('released');return;}if(request.method==='POST'&&
+ request.url==='/hold'){released=false;response.writeHead(200);response.end('holding');return;}
+ response.writeHead(404);response.end();}).listen(8090,'127.0.0.1');
env:
- name: TARGET_DNS
value: ${TARGET_DNS}
+ - name: START_RELEASED
+ value: "1"
- name: UPSTREAM_DNS
value: ${UPSTREAM_DNS_IP}
resources:
@@ -915,9 +973,25 @@ DNS_BLOCKER_IP="$(kctl get service "$DNS_BLOCKER_NAME" -n "$HCC_NS" \
ok "isolated DNS hold proxy is ready and forwards non-fixture UDP/TCP queries to CoreDNS"
HCC_MUTATED=1
-kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=0 >/dev/null
-wait_until 120 "existing HCC pods to stop" hcc_pods_absent ||
- die "existing HCC pod did not stop"
+dns_patch="$(jq -cn --arg nameserver "$DNS_BLOCKER_IP" '
+ {spec:{template:{spec:{
+ dnsPolicy:"None",
+ dnsConfig:{
+ nameservers:[$nameserver],
+ options:[
+ {name:"ndots",value:"1"},
+ {name:"timeout",value:"30"},
+ {name:"attempts",value:"20"}
+ ]
+ }
+ }}}}
+')"
+kctl patch deployment "$HCC_DEPLOY" -n "$HCC_NS" --type=strategic \
+ -p "$dns_patch" >/dev/null
+kctl rollout status deployment "$HCC_DEPLOY" -n "$HCC_NS" --timeout=180s >/dev/null ||
+ die "HCC did not become Ready with the deterministic DNS proxy"
+wait_until 60 "HCC /ready endpoint with the released DNS proxy" probe_hcc_ready_pod ||
+ die "HCC readiness was unavailable before the stale-policy fixture"
CONTEXT_CREATED=1
kctl apply -f - >/dev/null <<EOF
@@ -957,24 +1031,31 @@ spec:
egressBindings:
- dns: ${TARGET_DNS}
port: 443
- protocol: TCP
+ protocol: ${INITIAL_EXTERNAL_EGRESS_PROTOCOL}
EOF
-dns_patch="$(jq -cn --arg nameserver "$DNS_BLOCKER_IP" '
- {spec:{template:{spec:{
- dnsPolicy:"None",
- dnsConfig:{
- nameservers:[$nameserver],
- options:[
- {name:"ndots",value:"1"},
- {name:"timeout",value:"30"},
- {name:"attempts",value:"20"}
- ]
- }
- }}}}
-')"
-kctl patch deployment "$HCC_DEPLOY" -n "$HCC_NS" --type=strategic \
- -p "$dns_patch" >/dev/null
+wait_until 180 "HCC to create the real initial TCP external-egress policy" \
+ external_egress_policy_converged_with_protocol "$INITIAL_EXTERNAL_EGRESS_PROTOCOL" ||
+ die "HCC never created the initial external-egress policy for the stale-policy fixture"
+ok "HCC created a real TCP external-egress policy before the revision"
+
+kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=0 >/dev/null
+wait_until 120 "existing HCC pods to stop" hcc_pods_absent ||
+ die "existing HCC pod did not stop"
+delete_fixture_runtime_preserving_external_policy ||
+ die "could not remove the initial MCP runtime while retaining its external-egress policy"
+external_egress_policy_converged_with_protocol "$INITIAL_EXTERNAL_EGRESS_PROTOCOL" ||
+ die "the actual initial external-egress policy disappeared before the revision"
+
+hold_dns_blocker || die "could not hold the next fixture DNS query"
+egress_patch="$(jq -cn --arg dns "$TARGET_DNS" \
+ '{spec:{egressBindings:[{dns:$dns,port:443,protocol:"UDP"}]}}')"
+kctl patch mcpserver "$MCP_NAME" -n "$MCP_NS" --type=merge \
+ -p "$egress_patch" >/dev/null
+wait_until 60 "McpServer API to expose the revised UDP external-egress binding" \
+ mcp_egress_binding_is_udp ||
+ die "McpServer external-egress revision did not persist"
+
kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=1 >/dev/null
capture_hcc() {
@@ -1003,6 +1084,8 @@ dns_log_contains "holding DNS A ${TARGET_DNS}" ||
if dns_log_contains "released DNS A ${TARGET_DNS}"; then
die "DNS blocker released the McpServer query before Kubernetes reported HCC Ready"
fi
+fixture_mcp_runtime_absent ||
+ die "the stale same-name external-egress policy or fixture runtime survived before HCC reported Ready"
fixture_mcp_convergence_absent ||
die "fixture runtime, policy, or Ready status appeared before Kubernetes reported HCC Ready"
blocked_probe="$(probe_hcc_during_block)" ||
@@ -1021,7 +1104,7 @@ baseline_policies_exist ||
hcc_identity_is_stable ||
die "HCC restarted while the MCP external-egress query was held"
ok "/ready is 200 and discovery contains the exact McpServer while its real initial convergence is blocked"
-ok "baseline NetworkPolicies exist and no fixture runtime/policy was created prematurely"
+ok "baseline NetworkPolicies exist and the stale same-name external-egress policy was revoked before Ready"
initial_empty_context_log="[NetPol] Reconciling context \"${CONTEXT_ID}\" — allowed servers: []"
wait_until 120 "initial NetworkPolicy pass to reconcile the fixture's empty Context snapshot" \