Skip to content

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

TypeScript

fix(hcc): guard baseline policy ownership

Alfredo Lopeza70f289cbc0a
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 441afbfd3..d2f941fe9 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.178",
+ "version": "0.1.179",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.178",
+ "version": "0.1.179",
"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 2bbb79f5c..219f71637 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.178",
+ "version": "0.1.179",
"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 9cb78ca20..e9b94067e 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -2173,8 +2173,10 @@ describe('McpServerWatcher startup', () => {
})
await (watcher as any).startContextWatch('live-context-rv')
- const firstResync = (watcher as any).runExternalEgressResync() as Promise<void>
- const overlappingResync = (watcher as any).runExternalEgressResync() as Promise<void>
+ const firstResync = (watcher as any).externalEgressCoordinator.runResync() as Promise<void>
+ const overlappingResync = (
+ watcher as any
+ ).externalEgressCoordinator.runResync() as Promise<void>
expect(overlappingResync).toBe(firstResync)
await resyncStarted.promise
@@ -2233,7 +2235,7 @@ describe('McpServerWatcher startup', () => {
)
vi.spyOn(Math, 'random').mockReturnValue(0)
- const periodic = (watcher as any).runExternalEgressResync() as Promise<void>
+ const periodic = (watcher as any).externalEgressCoordinator.runResync() as Promise<void>
await mutationStarted.promise
expect(oldLease?.()).toBe(true)
@@ -2277,7 +2279,7 @@ describe('McpServerWatcher startup', () => {
;(watcher as any).servers.set(staleServer.name, staleServer)
const netPol = (watcher as any).netPolReconciler
- const periodic = (watcher as any).runExternalEgressResync() as Promise<void>
+ const periodic = (watcher as any).externalEgressCoordinator.runResync() as Promise<void>
await flushMicrotasks()
await (watcher as any).getMcpServerWatchCallback()('MODIFIED', currentServer)
await vi.advanceTimersByTimeAsync(2500)
@@ -3949,7 +3951,7 @@ describe('McpServerWatcher external egress retries', () => {
expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(1)
expect(reconciler.reconcile).toHaveBeenCalledTimes(1)
- await (watcher as any).runExternalEgressResync()
+ await (watcher as any).externalEgressCoordinator.runResync()
expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(2)
expect(reconciler.reconcile).toHaveBeenCalledTimes(2)
@@ -4443,7 +4445,7 @@ describe('McpServerWatcher external egress retries', () => {
})
vi.spyOn(Math, 'random').mockReturnValue(0.5)
- const resync = (watcher as any).runExternalEgressResync()
+ const resync = (watcher as any).externalEgressCoordinator.runResync()
await flushMicrotasks()
await watcher.stop()
await vi.advanceTimersByTimeAsync(2500)
@@ -4464,7 +4466,7 @@ describe('McpServerWatcher external egress retries', () => {
spec: serverObject.spec,
})
- await (watcher as any).runExternalEgressResync()
+ await (watcher as any).externalEgressCoordinator.runResync()
expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(1)
@@ -4490,7 +4492,7 @@ describe('McpServerWatcher external egress retries', () => {
const active = (watcher as any).runExternalEgressOnce('MODIFIED', server)
await mutationStarted.promise
- await (watcher as any).runExternalEgressResync()
+ await (watcher as any).externalEgressCoordinator.runResync()
expect(netPol.reconcileExternalEgress).toHaveBeenCalledOnce()
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index 174b8fb13..b924107bf 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -3222,10 +3222,6 @@ export class McpServerWatcher implements McpServerProvider {
}
}
- private runExternalEgressResync(): Promise<void> {
- return this.externalEgressCoordinator.runResync()
- }
-
/**
* Start watching McpServer CRDs.
*/
diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.ts
index aa08532fd..885b1e7ee 100644
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@ -61,7 +61,15 @@ vi.mock('./metrics', () => ({
function makeMockNetworkingApi() {
return {
createNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
- readNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ metadata: { resourceVersion: '1' } }),
+ readNamespacedNetworkPolicy: vi.fn().mockImplementation(async ({ name }) => {
+ if (
+ name === 'allow-desktop-egress-rpc-proxy' ||
+ name === 'allow-rpc-proxy-to-managed-mcp-servers'
+ ) {
+ throw Object.assign(new Error('not found'), { code: 404 })
+ }
+ return { metadata: { resourceVersion: '1' } }
+ }),
replaceNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
listNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ items: [] }),
deleteNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
@@ -317,6 +325,50 @@ describe('NetworkPolicyReconciler', () => {
// ─── L1: Infrastructure Policies ───────────────────────────────────
describe('L1 — ensureInfrastructurePolicies', () => {
+ it.each([
+ ['deny-all-mcp-server', 'default-deny'],
+ ['allow-dns-egress-mcp-server', 'infrastructure'],
+ ['allow-hcc-api-egress-mcp-server', 'infrastructure'],
+ ['allow-k8s-api-egress-mcp-server', 'infrastructure'],
+ ])(
+ 'refuses to adopt a foreign policy that collides with %s',
+ async (targetName, policyType) => {
+ mockApi.createNamespacedNetworkPolicy.mockImplementation(
+ async ({ body }: { body: k8s.V1NetworkPolicy }) => {
+ if (body.metadata?.name === targetName) {
+ throw Object.assign(new Error('already exists'), { code: 409 })
+ }
+ return {}
+ }
+ )
+ mockApi.readNamespacedNetworkPolicy.mockImplementation(async ({ name, namespace }) => {
+ if (
+ name === 'allow-desktop-egress-rpc-proxy' ||
+ name === 'allow-rpc-proxy-to-managed-mcp-servers'
+ ) {
+ throw Object.assign(new Error('not found'), { code: 404 })
+ }
+ return {
+ metadata: {
+ name,
+ namespace,
+ uid: 'foreign-baseline-uid',
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'foreign-controller',
+ 'clerum.io/policy-type': policyType,
+ },
+ },
+ }
+ })
+
+ await expect(reconciler.ensureDefaultPolicies()).rejects.toThrow(/ownership/i)
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalledWith(
+ expect.objectContaining({ name: targetName })
+ )
+ }
+ )
+
it('creates DNS egress policies in every runtime namespace', async () => {
await reconciler.ensureDefaultPolicies()
@@ -475,33 +527,100 @@ describe('NetworkPolicyReconciler', () => {
})
it('removes legacy static policies now replaced by generated scoped policies', async () => {
+ mockApi.readNamespacedNetworkPolicy.mockImplementation(async ({ name, namespace }) => ({
+ metadata: {
+ name,
+ namespace,
+ uid: `${name}-uid`,
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ }))
+
await reconciler.ensureDefaultPolicies()
- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(
- expect.objectContaining({
- namespace: 'rpc-proxy',
- name: 'allow-desktop-egress-rpc-proxy',
- })
- )
- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(
- expect.objectContaining({
- namespace: 'mcp-server',
- name: 'allow-rpc-proxy-to-managed-mcp-servers',
- })
- )
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ namespace: 'rpc-proxy',
+ name: 'allow-desktop-egress-rpc-proxy',
+ body: {
+ preconditions: {
+ uid: 'allow-desktop-egress-rpc-proxy-uid',
+ resourceVersion: '7',
+ },
+ },
+ })
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ namespace: 'mcp-server',
+ name: 'allow-rpc-proxy-to-managed-mcp-servers',
+ body: {
+ preconditions: {
+ uid: 'allow-rpc-proxy-to-managed-mcp-servers-uid',
+ resourceVersion: '7',
+ },
+ },
+ })
})
- it('fails closed when legacy static policy cleanup fails', async () => {
- const cleanupError = Object.assign(new Error('rbac denied'), { code: 403 })
- mockApi.deleteNamespacedNetworkPolicy.mockImplementation(async ({ name }) => {
- if (name === 'allow-rpc-proxy-to-managed-mcp-servers') {
- throw cleanupError
+ it.each([
+ ['rpc-proxy', 'allow-desktop-egress-rpc-proxy'],
+ ['mcp-server', 'allow-rpc-proxy-to-managed-mcp-servers'],
+ ])('refuses to delete a foreign legacy policy %s/%s', async (targetNamespace, targetName) => {
+ mockApi.readNamespacedNetworkPolicy.mockImplementation(async ({ name, namespace }) => {
+ if (name !== targetName) {
+ throw Object.assign(new Error('not found'), { code: 404 })
+ }
+ return {
+ metadata: {
+ name,
+ namespace,
+ uid: 'foreign-legacy-uid',
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'foreign-controller',
+ },
+ },
}
- return {}
})
- await expect(reconciler.ensureDefaultPolicies()).rejects.toBe(cleanupError)
+ await expect(reconciler.ensureDefaultPolicies()).rejects.toThrow(/ownership/i)
+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith(
+ expect.objectContaining({ namespace: targetNamespace, name: targetName })
+ )
})
+
+ it.each([
+ ['rpc-proxy', 'allow-desktop-egress-rpc-proxy'],
+ ['mcp-server', 'allow-rpc-proxy-to-managed-mcp-servers'],
+ ])(
+ 'propagates an identity conflict deleting legacy policy %s/%s',
+ async (targetNamespace, targetName) => {
+ mockApi.readNamespacedNetworkPolicy.mockImplementation(async ({ name, namespace }) => {
+ if (name !== targetName) {
+ throw Object.assign(new Error('not found'), { code: 404 })
+ }
+ return {
+ metadata: {
+ name,
+ namespace,
+ uid: 'legacy-policy-uid',
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ }
+ })
+ const conflict = Object.assign(new Error('identity changed'), { code: 409 })
+ mockApi.deleteNamespacedNetworkPolicy.mockImplementation(async ({ name, namespace }) => {
+ if (name === targetName && namespace === targetNamespace) throw conflict
+ return {}
+ })
+
+ await expect(reconciler.ensureDefaultPolicies()).rejects.toBe(conflict)
+ }
+ )
})
// ─── L1: Allow API ─────────────────────────────────────────────────
@@ -564,6 +683,48 @@ describe('NetworkPolicyReconciler', () => {
expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
+ it('revalidates allow-api ownership after a replace conflict', async () => {
+ mockApi.createNamespacedNetworkPolicy.mockImplementation(
+ async ({ body }: { body: k8s.V1NetworkPolicy }) => {
+ if (body.metadata?.name === 'allow-host-context-controller-api') {
+ throw Object.assign(new Error('already exists'), { code: 409 })
+ }
+ return {}
+ }
+ )
+ mockApi.readNamespacedNetworkPolicy
+ .mockResolvedValueOnce({
+ metadata: {
+ name: 'allow-host-context-controller-api',
+ namespace: 'mcp-server',
+ uid: 'owned-uid',
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'host-context-controller',
+ 'clerum.io/policy-type': 'allow-api',
+ },
+ },
+ })
+ .mockResolvedValueOnce({
+ metadata: {
+ name: 'allow-host-context-controller-api',
+ namespace: 'mcp-server',
+ uid: 'foreign-uid',
+ resourceVersion: '8',
+ labels: {
+ 'clerum.io/managed-by': 'foreign-controller',
+ 'clerum.io/policy-type': 'allow-api',
+ },
+ },
+ })
+ mockApi.replaceNamespacedNetworkPolicy.mockRejectedValueOnce(
+ Object.assign(new Error('conflict'), { code: 409 })
+ )
+
+ await expect(reconciler.ensureDefaultPolicies()).rejects.toThrow(/ownership/i)
+ expect(mockApi.replaceNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ })
+
it('creates allow-api ingress policy using _from (K8s client convention)', async () => {
await reconciler.ensureDefaultPolicies()
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index f3086d3c8..0235c306c 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -411,7 +411,7 @@ export class NetworkPolicyReconciler {
},
}
- await applyNetworkPolicy(this.networkingApi, name, ns, policy, '[NetPol]')
+ await this.applyFixedPolicy(name, ns, policy, 'default-deny')
}
}
@@ -485,7 +485,7 @@ export class NetworkPolicyReconciler {
egress,
},
}
- await applyNetworkPolicy(this.networkingApi, name, namespace, policy, '[NetPol]')
+ await this.applyFixedPolicy(name, namespace, policy, INFRA_POLICY_TYPE)
}
/** Allow egress to host-context-controller API gateway in control-plane namespace. */
@@ -522,7 +522,7 @@ export class NetworkPolicyReconciler {
],
},
}
- await applyNetworkPolicy(this.networkingApi, name, namespace, policy, '[NetPol]')
+ await this.applyFixedPolicy(name, namespace, policy, INFRA_POLICY_TYPE)
}
/**
@@ -567,7 +567,7 @@ export class NetworkPolicyReconciler {
],
},
}
- await applyNetworkPolicy(this.networkingApi, name, namespace, policy, '[NetPol]')
+ await this.applyFixedPolicy(name, namespace, policy, INFRA_POLICY_TYPE)
}
/**
@@ -610,21 +610,7 @@ export class NetworkPolicyReconciler {
},
}
- await applyNetworkPolicy(
- this.networkingApi,
- name,
- config.namespace,
- policy,
- '[NetPol]',
- undefined,
- existing => {
- if (!hasExpectedPolicyOwnership(existing, 'allow-api')) {
- throw new Error(
- `NetworkPolicy "${name}" has conflicting ownership for the allow-api lane`
- )
- }
- }
- )
+ await this.applyFixedPolicy(name, config.namespace, policy, 'allow-api')
}
// ─── Context-Based Policies ──────────────────────────────────────────
@@ -2291,6 +2277,30 @@ export class NetworkPolicyReconciler {
}
/** Create or update a NetworkPolicy. */
+ private async applyFixedPolicy(
+ name: string,
+ namespace: string,
+ policy: k8s.V1NetworkPolicy,
+ policyType: string
+ ): Promise<void> {
+ await applyNetworkPolicy(
+ this.networkingApi,
+ name,
+ namespace,
+ policy,
+ '[NetPol]',
+ undefined,
+ existing => {
+ if (!hasExpectedPolicyOwnership(existing, policyType)) {
+ throw new Error(
+ `NetworkPolicy "${name}" has conflicting ownership for the ${policyType} lane`
+ )
+ }
+ }
+ )
+ }
+
+ /** Create or update a Context ingress NetworkPolicy. */
private async applyContextIngressPolicy(
name: string,
policy: k8s.V1NetworkPolicy,
@@ -2552,17 +2562,17 @@ export class NetworkPolicyReconciler {
/** Delete a formerly static NetworkPolicy that is now generated dynamically. */
private async deleteLegacyStaticPolicy(namespace: string, name: string): Promise<void> {
+ let existing: k8s.V1NetworkPolicy
try {
- await this.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace })
- console.log(`[NetPol] Deleted legacy static policy "${name}" in "${namespace}"`)
+ existing = await this.networkingApi.readNamespacedNetworkPolicy({ name, namespace })
} catch (error: unknown) {
- if (getErrorCode(error) !== 404) {
- console.error(
- `[NetPol] Failed to delete legacy static policy "${name}" in "${namespace}":`,
- error
- )
- throw error
- }
+ if (getErrorCode(error) === 404) return
+ throw error
+ }
+ if (existing.metadata?.labels?.[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) {
+ throw new Error(`NetworkPolicy "${name}" has conflicting ownership for legacy cleanup`)
}
+ await this.deleteSafetyPolicySnapshot(namespace, existing)
+ console.log(`[NetPol] Deleted legacy static policy "${name}" in "${namespace}"`)
}
}
diff --git a/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts b/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts
index a06465eeb..f8696e57e 100644
--- a/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts
+++ b/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts
@@ -34,9 +34,12 @@ describe('ensureK8sApiEgress', () => {
mockApply.mockClear()
// ensureDefaultPolicies() also prunes legacy static policies via the
// networking API directly (not applyNetworkPolicy), so the mocked client
- // must expose deleteNamespacedNetworkPolicy.
+ // must expose the read-before-delete legacy cleanup path.
const mockKc = {
makeApiClient: () => ({
+ readNamespacedNetworkPolicy: vi
+ .fn()
+ .mockRejectedValue(Object.assign(new Error('not found'), { code: 404 })),
deleteNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
}),
} as unknown as k8s.KubeConfig
diff --git a/host-context-controller/test/networkPolicyReconciler.minimalInfra.test.ts b/host-context-controller/test/networkPolicyReconciler.minimalInfra.test.ts
index 6a89edc00..04e7b3b33 100644
--- a/host-context-controller/test/networkPolicyReconciler.minimalInfra.test.ts
+++ b/host-context-controller/test/networkPolicyReconciler.minimalInfra.test.ts
@@ -26,7 +26,9 @@ const mockApply = vi.mocked(applyNetworkPolicy)
function createMockNetworkingApi() {
return {
createNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
- readNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ metadata: {} }),
+ readNamespacedNetworkPolicy: vi
+ .fn()
+ .mockRejectedValue(Object.assign(new Error('not found'), { code: 404 })),
replaceNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
deleteNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
listNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ items: [] }),
diff --git a/host-context-controller/test/networkPolicyReconciler.nodeLocalDns.test.ts b/host-context-controller/test/networkPolicyReconciler.nodeLocalDns.test.ts
index ae59d2dbd..9d0db5860 100644
--- a/host-context-controller/test/networkPolicyReconciler.nodeLocalDns.test.ts
+++ b/host-context-controller/test/networkPolicyReconciler.nodeLocalDns.test.ts
@@ -32,7 +32,9 @@ const mockApply = vi.mocked(applyNetworkPolicy)
function createMockNetworkingApi() {
return {
createNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
- readNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ metadata: {} }),
+ readNamespacedNetworkPolicy: vi
+ .fn()
+ .mockRejectedValue(Object.assign(new Error('not found'), { code: 404 })),
replaceNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
deleteNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
listNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ items: [] }),
diff --git a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
index 8675d0341..7d610e72f 100755
--- a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
+++ b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
@@ -101,6 +101,7 @@ HCC_GATE_LOCK_UID=""
# shellcheck disable=SC2034
HCC_GATE_FINALIZATION_FAILURE=""
HCC_READY_PROBE_DIAGNOSTIC=""
+BASELINE_POLICY_SNAPSHOT=""
[[ "$MCP_FLEET_SIZE" =~ ^[0-9]+$ ]] && [ "$MCP_FLEET_SIZE" -gt 10 ] &&
[ "$MCP_FLEET_SIZE" -le 24 ] || {
@@ -478,7 +479,10 @@ fixture_runtime_converged_with_protocol() {
}
fixture_resources_absent() {
- fixture_mcp_runtime_absent && context_policies_absent && peer_fleet_runtime_absent
+ fixture_mcp_runtime_absent &&
+ context_policies_absent &&
+ peer_fleet_runtime_absent &&
+ peer_fleet_policies_absent
}
fixture_inputs_absent() {
@@ -503,6 +507,24 @@ peer_fleet_runtime_absent() {
done
}
+peer_fleet_policies_absent() {
+ local index server context context_policy external_policies
+ for ((index = 1; index < ${#MCP_FLEET_NAMES[@]}; index++)); do
+ server="${MCP_FLEET_NAMES[index]}"
+ context="${CONTEXT_FLEET_NAMES[index]}"
+ context_policy="ctx-${context}-${server}"
+ resource_absent networkpolicy "$context_policy" "$MCP_NS" || return 1
+ resource_absent networkpolicy "${context_policy}-egress" "$HOST_NS" || return 1
+ resource_absent networkpolicy "rpc-egress-${context}-${server}" "$RPC_PROXY_NS" || return 1
+ external_policies="$(
+ kctl get networkpolicy -n "$MCP_NS" \
+ -l "${MCP_SERVER_LABEL}=${server},${POLICY_TYPE_LABEL}=external-egress" \
+ -o name 2>/dev/null
+ )" || return 1
+ [ -z "$external_policies" ] || return 1
+ done
+}
+
peer_fleet_converged() {
local index server context desired available
for ((index = 1; index < ${#MCP_FLEET_NAMES[@]}; index++)); do
@@ -517,10 +539,37 @@ peer_fleet_converged() {
done
}
-baseline_policies_exist() {
- kctl get networkpolicy "deny-all-${MCP_NS}" -n "$MCP_NS" >/dev/null 2>&1 &&
- kctl get networkpolicy "allow-dns-egress-${MCP_NS}" -n "$MCP_NS" >/dev/null 2>&1 &&
- kctl get networkpolicy allow-host-context-controller-api -n "$MCP_NS" >/dev/null 2>&1
+baseline_policy_snapshot() {
+ kctl get \
+ "networkpolicy/deny-all-${MCP_NS}" \
+ "networkpolicy/allow-dns-egress-${MCP_NS}" \
+ networkpolicy/allow-host-context-controller-api \
+ -n "$MCP_NS" -o json 2>/dev/null |
+ jq -ceS \
+ --arg managedBy "$MANAGED_BY_VALUE" \
+ --arg deny "deny-all-${MCP_NS}" \
+ --arg dns "allow-dns-egress-${MCP_NS}" '
+ [.items[] | {
+ name: .metadata.name,
+ managedBy: .metadata.labels["clerum.io/managed-by"],
+ policyType: .metadata.labels["clerum.io/policy-type"],
+ spec
+ }]
+ | sort_by(.name)
+ | select(length == 3)
+ | select(all(.[];
+ .managedBy == $managedBy and
+ ((.name == $deny and .policyType == "default-deny") or
+ (.name == $dns and .policyType == "infrastructure") or
+ (.name == "allow-host-context-controller-api" and .policyType == "allow-api"))))
+ '
+}
+
+baseline_policies_unchanged() {
+ local current
+ [ -n "$BASELINE_POLICY_SNAPSHOT" ] || return 1
+ current="$(baseline_policy_snapshot)" || return 1
+ [ "$current" = "$BASELINE_POLICY_SNAPSHOT" ]
}
context_watch_has_latest_spec() {
@@ -843,9 +892,11 @@ delete_residual_fixture_runtime() {
}
delete_peer_fleet_runtime() {
- local index server failed=0
+ local index server context context_policy failed=0
for ((index = 1; index < ${#MCP_FLEET_NAMES[@]}; index++)); do
server="${MCP_FLEET_NAMES[index]}"
+ context="${CONTEXT_FLEET_NAMES[index]}"
+ context_policy="ctx-${context}-${server}"
kctl delete deployment "$server" -n "$MCP_NS" --ignore-not-found --wait=true --timeout=60s \
>/dev/null 2>&1 || failed=1
kctl delete service "$server" -n "$MCP_NS" --ignore-not-found --wait=true --timeout=60s \
@@ -854,6 +905,10 @@ delete_peer_fleet_runtime() {
>/dev/null 2>&1 || failed=1
kctl delete networkpolicy -n "$MCP_NS" -l "${MCP_SERVER_LABEL}=${server}" \
--ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete networkpolicy "${context_policy}-egress" -n "$HOST_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete networkpolicy "rpc-egress-${context}-${server}" -n "$RPC_PROXY_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
done
[ "$failed" = 0 ]
}
@@ -1303,6 +1358,8 @@ 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 initial TCP external-egress policy"
+BASELINE_POLICY_SNAPSHOT="$(baseline_policy_snapshot)" ||
+ die "could not capture canonical baseline NetworkPolicy ownership and specs"
# Same-intent safety phase: restart with the exact same desired binding. The
# safety pass must revoke the DNS-derived policy without resolving DNS, certify
@@ -1418,8 +1475,8 @@ external_egress_policy_absent ||
die "a divergent external-egress policy survived the fail-closed revocation"
context_policies_absent ||
die "Context policy existed before the Context watch update"
-baseline_policies_exist ||
- die "baseline safety NetworkPolicies are absent during safety convergence"
+baseline_policies_unchanged ||
+ die "baseline safety NetworkPolicy ownership or specs changed during safety convergence"
hcc_identity_is_stable ||
die "HCC restarted while the MCP external-egress query was held"
ok "/ready is 200 while the divergent stale policy and affected runtime remain absent"
@@ -1495,6 +1552,8 @@ echo "$final_probe" | jq -e \
.fixture == $fixture and .fixtureReady == true and .contextRef == $context
' >/dev/null ||
die "HCC final probe returned an invalid result: ${final_probe}"
+baseline_policies_unchanged ||
+ die "baseline safety NetworkPolicy ownership or specs changed before final convergence"
ok "DNS release created the current UDP policy and affected runtime without gating HCC readiness"
ok "the full worker-width-crossing peer fleet converged after releasing the held primary egress"
ok "Context ingress, mcp-host egress, and rpc-proxy egress policies reflect the latest watch state"
diff --git a/scripts/tests/test-hcc-watch-recovery-gate.sh b/scripts/tests/test-hcc-watch-recovery-gate.sh
index a7baf4043..44d0519f7 100755
--- a/scripts/tests/test-hcc-watch-recovery-gate.sh
+++ b/scripts/tests/test-hcc-watch-recovery-gate.sh
@@ -702,6 +702,74 @@ else
fail "divergent hold evidence can pass without HCC readiness"
fi
+baseline_policy_snapshot_function="$(
+ sed -n '/^baseline_policy_snapshot() {$/,/^}$/p' "$MCP_READINESS_GATE"
+)"
+baseline_policies_unchanged_function="$(
+ sed -n '/^baseline_policies_unchanged() {$/,/^}$/p' "$MCP_READINESS_GATE"
+)"
+valid_baseline_policies='{"items":[
+ {"metadata":{"name":"deny-all-mcp-server","labels":{"clerum.io/managed-by":"host-context-controller","clerum.io/policy-type":"default-deny"}},"spec":{"podSelector":{},"policyTypes":["Ingress","Egress"]}},
+ {"metadata":{"name":"allow-dns-egress-mcp-server","labels":{"clerum.io/managed-by":"host-context-controller","clerum.io/policy-type":"infrastructure"}},"spec":{"podSelector":{},"policyTypes":["Egress"],"egress":[{"ports":[{"port":53,"protocol":"UDP"},{"port":53,"protocol":"TCP"}]}]}},
+ {"metadata":{"name":"allow-host-context-controller-api","labels":{"clerum.io/managed-by":"host-context-controller","clerum.io/policy-type":"allow-api"}},"spec":{"podSelector":{"matchLabels":{"app":"host-context-controller"}},"policyTypes":["Ingress"]}}
+]}'
+if (
+ MCP_NS=mcp-server
+ MANAGED_BY_VALUE=host-context-controller
+ MOCK_POLICY_JSON="$valid_baseline_policies"
+ kctl() { printf '%s\n' "$MOCK_POLICY_JSON"; }
+ eval "$baseline_policy_snapshot_function"
+ eval "$baseline_policies_unchanged_function"
+ BASELINE_POLICY_SNAPSHOT="$(baseline_policy_snapshot)"
+ baseline_policies_unchanged &&
+ MOCK_POLICY_JSON="$(jq -c '
+ .items[0].metadata.labels["clerum.io/managed-by"] = "foreign-controller"
+ ' <<<"$valid_baseline_policies")" &&
+ ! baseline_policies_unchanged &&
+ MOCK_POLICY_JSON="$(jq -c '.items[1].spec.egress[0].ports[0].port = 5353' \
+ <<<"$valid_baseline_policies")" &&
+ ! baseline_policies_unchanged
+); then
+ pass "baseline safety proof rejects ownership and spec drift under stable policy names"
+else
+ fail "baseline safety proof can pass after ownership or spec drift"
+fi
+
+peer_fleet_policies_absent_function="$(
+ sed -n '/^peer_fleet_policies_absent() {$/,/^}$/p' "$MCP_READINESS_GATE"
+)"
+fixture_resources_absent_function="$(
+ sed -n '/^fixture_resources_absent() {$/,/^}$/p' "$MCP_READINESS_GATE"
+)"
+delete_peer_fleet_runtime_function="$(
+ sed -n '/^delete_peer_fleet_runtime() {$/,/^}$/p' "$MCP_READINESS_GATE"
+)"
+if (
+ MCP_NS=mcp-server
+ HOST_NS=mcp-host
+ RPC_PROXY_NS=rpc-proxy
+ MCP_SERVER_LABEL=clerum.io/mcpserver
+ POLICY_TYPE_LABEL=clerum.io/policy-type
+ MCP_FLEET_NAMES=(primary peer)
+ CONTEXT_FLEET_NAMES=(primary-context peer-context)
+ SURVIVOR_NS=""
+ resource_absent() { [ "$3" != "$SURVIVOR_NS" ]; }
+ kctl() { return 0; }
+ eval "$peer_fleet_policies_absent_function"
+ peer_fleet_policies_absent &&
+ SURVIVOR_NS=mcp-host &&
+ ! peer_fleet_policies_absent &&
+ SURVIVOR_NS=rpc-proxy &&
+ ! peer_fleet_policies_absent
+) &&
+ [[ "$fixture_resources_absent_function" == *'peer_fleet_policies_absent'* ]] &&
+ [[ "$delete_peer_fleet_runtime_function" == *'"${context_policy}-egress"'* ]] &&
+ [[ "$delete_peer_fleet_runtime_function" == *'"rpc-egress-${context}-${server}"'* ]]; then
+ pass "peer fleet cleanup rejects surviving mcp-host or rpc-proxy policies"
+else
+ fail "peer fleet cleanup can release ownership with residual derived policies"
+fi
+
# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-logs.sh
source "$LOG_HELPER"
HCC_LOG_BUFFER="$MOCK_LOG_FILE"