Skip to content

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

TypeScript

fix(hcc): skip no-op NetworkPolicy replaces on the shared helper (#460)

Alfredo Lopezb0c3559aa457
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 19660ea9d..14e65ae26 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.243",
+ "version": "0.1.244",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.243",
+ "version": "0.1.244",
"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 678d01aaf..188c7577e 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.243",
+ "version": "0.1.244",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --git a/host-context-controller/src/__tests__/applyNetworkPolicyNoopGate.test.ts b/host-context-controller/src/__tests__/applyNetworkPolicyNoopGate.test.ts
new file mode 100644
index 000000000..be11e37b6
--- /dev/null
+++ b/host-context-controller/src/__tests__/applyNetworkPolicyNoopGate.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi } from 'vitest'
+import type * as k8s from '@kubernetes/client-node'
+import { applyNetworkPolicy } from '../utils'
+import { asApiserverNetworkPolicy, updatedPolicyLogs } from './asApiserverNetworkPolicy'
+
+function desiredPolicy(): k8s.V1NetworkPolicy {
+ return {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: { name: 'np', namespace: 'ns', labels: { app: 'np' } },
+ spec: {
+ podSelector: { matchLabels: { app: 'np' } },
+ ingress: [
+ {
+ _from: [{ podSelector: { matchLabels: { app: 'peer' } } }],
+ ports: [{ port: 8080 }],
+ },
+ ],
+ },
+ }
+}
+
+function fakeNetworkingApi() {
+ return {
+ createNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
+ readNamespacedNetworkPolicy: vi.fn(),
+ replaceNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
+ }
+}
+
+describe('applyNetworkPolicy no-op gate', () => {
+ it('CREATE-NP-1: successful create never reads or replaces', async () => {
+ const api = fakeNetworkingApi()
+ await applyNetworkPolicy(api as unknown as k8s.NetworkingV1Api, 'np', 'ns', desiredPolicy())
+ expect(api.createNamespacedNetworkPolicy).toHaveBeenCalledOnce()
+ expect(api.readNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(api.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('NOOP-NP-1 / LOG-NP-1: equivalent recorded existing skips replace and Updated logs', async () => {
+ const desired = desiredPolicy()
+ const existing = asApiserverNetworkPolicy(desired)
+ expect(existing.spec).toBeDefined()
+ const api = fakeNetworkingApi()
+ api.createNamespacedNetworkPolicy.mockRejectedValue({ code: 409 })
+ api.readNamespacedNetworkPolicy.mockResolvedValue(existing)
+ const log = vi.spyOn(console, 'log')
+ try {
+ await applyNetworkPolicy(api as unknown as k8s.NetworkingV1Api, 'np', 'ns', desired)
+ expect(api.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(updatedPolicyLogs(log, 'policy "np" in ns')).toEqual([])
+ } finally {
+ log.mockRestore()
+ }
+ })
+
+ it('NOOP-NP-2 / LOG-NP-2: drift replaces once and logs once', async () => {
+ const desired = desiredPolicy()
+ const api = fakeNetworkingApi()
+ api.createNamespacedNetworkPolicy.mockRejectedValue({ code: 409 })
+ api.readNamespacedNetworkPolicy.mockResolvedValue(
+ asApiserverNetworkPolicy(desired, { port: 9090 })
+ )
+ const log = vi.spyOn(console, 'log')
+ try {
+ await applyNetworkPolicy(api as unknown as k8s.NetworkingV1Api, 'np', 'ns', desired)
+ expect(api.replaceNamespacedNetworkPolicy).toHaveBeenCalledOnce()
+ expect(updatedPolicyLogs(log, 'policy "np" in ns')).toEqual([
+ '[NetPol] Updated policy "np" in ns',
+ ])
+ } finally {
+ log.mockRestore()
+ }
+ })
+
+ it('ORDER-NP-1: validateExisting throws before isUpToDate; replace is not called', async () => {
+ const desired = desiredPolicy()
+ const api = fakeNetworkingApi()
+ api.createNamespacedNetworkPolicy.mockRejectedValue({ code: 409 })
+ api.readNamespacedNetworkPolicy.mockResolvedValue(asApiserverNetworkPolicy(desired))
+ const validateExisting = vi.fn(() => {
+ throw new Error('NetworkPolicy "np" has conflicting ownership for the context-ingress lane')
+ })
+
+ await expect(
+ applyNetworkPolicy(
+ api as unknown as k8s.NetworkingV1Api,
+ 'np',
+ 'ns',
+ desired,
+ '[NetPol]',
+ undefined,
+ validateExisting
+ )
+ ).rejects.toThrow(/ownership/)
+
+ expect(validateExisting).toHaveBeenCalledOnce()
+ expect(api.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('GATE-NP-1: mutationAllowed false after create-409 skips replace on drift', async () => {
+ const desired = desiredPolicy()
+ const api = fakeNetworkingApi()
+ api.createNamespacedNetworkPolicy.mockRejectedValue({ code: 409 })
+ api.readNamespacedNetworkPolicy.mockResolvedValue(
+ asApiserverNetworkPolicy(desired, { port: 9090 })
+ )
+ const mutationAllowed = vi.fn().mockReturnValueOnce(true).mockReturnValueOnce(false)
+
+ await applyNetworkPolicy(
+ api as unknown as k8s.NetworkingV1Api,
+ 'np',
+ 'ns',
+ desired,
+ '[NetPol]',
+ mutationAllowed
+ )
+
+ expect(api.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+})
diff --git a/host-context-controller/src/__tests__/asApiserverNetworkPolicy.ts b/host-context-controller/src/__tests__/asApiserverNetworkPolicy.ts
new file mode 100644
index 000000000..4864d38ef
--- /dev/null
+++ b/host-context-controller/src/__tests__/asApiserverNetworkPolicy.ts
@@ -0,0 +1,97 @@
+import { vi } from 'vitest'
+import type * as k8s from '@kubernetes/client-node'
+
+/**
+ * Recorded kube-apiserver GET of a NetworkPolicy after client-node decode
+ * (`from` → `_from`), not a field list copied from the comparator.
+ * Stamp controller-owned name/labels/podSelector/rules via
+ * `asApiserverNetworkPolicy`. When a newer apiserver default-fills a field,
+ * refresh this blob so the suite goes red until the comparator learns it.
+ */
+export const RECORDED_NETWORKPOLICY: k8s.V1NetworkPolicy = {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: {
+ annotations: {
+ 'kubectl.kubernetes.io/last-applied-configuration': '{}',
+ },
+ creationTimestamp: new Date('2026-04-01T00:00:00.000Z'),
+ generation: 1,
+ managedFields: [
+ {
+ apiVersion: 'networking.k8s.io/v1',
+ fieldsType: 'FieldsV1',
+ fieldsV1: { 'f:spec': { 'f:podSelector': {} } },
+ manager: 'kube-apiserver',
+ operation: 'Update',
+ time: new Date('2026-04-01T00:00:00.000Z'),
+ },
+ ],
+ name: 'recorded-np',
+ namespace: 'recorded-ns',
+ resourceVersion: '1783417',
+ uid: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
+ selfLink: '/apis/networking.k8s.io/v1/namespaces/recorded-ns/networkpolicies/recorded-np',
+ },
+ spec: {
+ podSelector: { matchLabels: { app: 'recorded' } },
+ policyTypes: ['Ingress'],
+ ingress: [
+ {
+ _from: [{ podSelector: { matchLabels: { app: 'peer' } } }],
+ ports: [{ port: 8080, protocol: 'TCP' }],
+ },
+ ],
+ },
+}
+
+function stampPorts(
+ rules: k8s.V1NetworkPolicyIngressRule[] | k8s.V1NetworkPolicyEgressRule[] | undefined,
+ driftPort?: number
+): typeof rules {
+ if (!rules) return rules
+ return rules.map((rule, ruleIndex) => ({
+ ...rule,
+ ports: (rule.ports ?? []).map((port, portIndex) => ({
+ ...port,
+ protocol: port.protocol ?? 'TCP',
+ port: ruleIndex === 0 && portIndex === 0 && driftPort !== undefined ? driftPort : port.port,
+ })),
+ }))
+}
+
+export function asApiserverNetworkPolicy(
+ desired: k8s.V1NetworkPolicy,
+ drift?: { port?: number }
+): k8s.V1NetworkPolicy {
+ const recorded = structuredClone(RECORDED_NETWORKPOLICY)
+ const hasEgress = (desired.spec?.egress?.length ?? 0) > 0
+ const policyTypes = desired.spec?.policyTypes ?? (hasEgress ? ['Ingress', 'Egress'] : ['Ingress'])
+ return {
+ ...recorded,
+ metadata: {
+ ...recorded.metadata,
+ name: desired.metadata?.name,
+ namespace: desired.metadata?.namespace,
+ labels: desired.metadata?.labels,
+ // Do not merge recorded last-applied: the shared helper has no
+ // mergeExisting, so an extra live annotation is a real write.
+ annotations: desired.metadata?.annotations,
+ ownerReferences: desired.metadata?.ownerReferences,
+ selfLink: `/apis/networking.k8s.io/v1/namespaces/${desired.metadata?.namespace}/networkpolicies/${desired.metadata?.name}`,
+ },
+ spec: {
+ ...recorded.spec,
+ podSelector: desired.spec?.podSelector ?? {},
+ policyTypes,
+ ingress: stampPorts(desired.spec?.ingress, drift?.port),
+ egress: stampPorts(desired.spec?.egress, desired.spec?.ingress ? undefined : drift?.port),
+ },
+ }
+}
+
+export function updatedPolicyLogs(log: ReturnType<typeof vi.spyOn>, needle: string): string[] {
+ return log.mock.calls
+ .map((call: unknown[]) => String(call[0]))
+ .filter((line: string) => line.includes('Updated') && line.includes(needle))
+}
diff --git a/host-context-controller/src/__tests__/hostNetworkPolicyNoopGate.test.ts b/host-context-controller/src/__tests__/hostNetworkPolicyNoopGate.test.ts
new file mode 100644
index 000000000..654ecbdb4
--- /dev/null
+++ b/host-context-controller/src/__tests__/hostNetworkPolicyNoopGate.test.ts
@@ -0,0 +1,76 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type * as k8s from '@kubernetes/client-node'
+import {
+ type MockNetworkingApi,
+ asAppsApi,
+ asCoreApi,
+ asCustomApi,
+ asNetworkingApi,
+ asRbacApi,
+ createMockAppsApi,
+ createMockCoreApi,
+ createMockCustomApi,
+ createMockNetworkingApi,
+ createMockRbacApi,
+} from '../../test/__fixtures__/testMocks'
+import { HostReconciler } from '../hostReconciler'
+import type { HostCRD } from '../types'
+import { asApiserverNetworkPolicy } from './asApiserverNetworkPolicy'
+
+function makeStubKc(): k8s.KubeConfig {
+ const stub = new Proxy({}, { get: () => vi.fn() })
+ return { makeApiClient: () => stub } as unknown as k8s.KubeConfig
+}
+
+function makeHost(): HostCRD {
+ return {
+ name: 'chatllm',
+ namespace: 'mcp-host',
+ uid: 'chatllm-uid',
+ spec: {
+ host: 'chatllm',
+ contextRef: 'ctx',
+ secretRef: 'secret',
+ },
+ }
+}
+
+describe('Host ensureMcpHostIngressNetworkPolicy inherits applyNetworkPolicy gate', () => {
+ let networkingApi: MockNetworkingApi
+ let reconciler: HostReconciler
+ const host = makeHost()
+
+ beforeEach(() => {
+ networkingApi = createMockNetworkingApi()
+ reconciler = new HostReconciler(makeStubKc(), {
+ coreApi: asCoreApi(createMockCoreApi()),
+ appsApi: asAppsApi(createMockAppsApi()),
+ networkingApi: asNetworkingApi(networkingApi),
+ rbacApi: asRbacApi(createMockRbacApi()),
+ customApi: asCustomApi(createMockCustomApi()),
+ })
+ })
+
+ it('INHERIT-NP-1: equivalent recorded policy skips replace; drift replaces once', async () => {
+ let captured: k8s.V1NetworkPolicy | undefined
+ networkingApi.createNamespacedNetworkPolicy.mockImplementation(async ({ body }) => {
+ captured = body as k8s.V1NetworkPolicy
+ throw Object.assign(new Error('already exists'), { code: 409 })
+ })
+ networkingApi.readNamespacedNetworkPolicy.mockImplementation(async () => {
+ if (!captured?.spec) throw new Error('create did not capture a spec')
+ return asApiserverNetworkPolicy(captured)
+ })
+
+ await (reconciler as any).ensureMcpHostIngressNetworkPolicy(host)
+ expect(networkingApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+
+ networkingApi.replaceNamespacedNetworkPolicy.mockClear()
+ networkingApi.readNamespacedNetworkPolicy.mockImplementation(async () => {
+ if (!captured?.spec) throw new Error('create did not capture a spec')
+ return asApiserverNetworkPolicy(captured, { port: 9090 })
+ })
+ await (reconciler as any).ensureMcpHostIngressNetworkPolicy(host)
+ expect(networkingApi.replaceNamespacedNetworkPolicy).toHaveBeenCalledOnce()
+ })
+})
diff --git a/host-context-controller/src/__tests__/networkPolicyMatchesDesired.test.ts b/host-context-controller/src/__tests__/networkPolicyMatchesDesired.test.ts
new file mode 100644
index 000000000..fc152ede7
--- /dev/null
+++ b/host-context-controller/src/__tests__/networkPolicyMatchesDesired.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it } from 'vitest'
+import type * as k8s from '@kubernetes/client-node'
+import { networkPolicyMatchesDesired } from '../utils'
+import { asApiserverNetworkPolicy } from './asApiserverNetworkPolicy'
+
+function desiredPolicy(overrides: Partial<k8s.V1NetworkPolicy> = {}): k8s.V1NetworkPolicy {
+ return {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: { name: 'np', namespace: 'ns', labels: { app: 'np' } },
+ spec: {
+ podSelector: { matchLabels: { app: 'np' } },
+ ingress: [
+ {
+ _from: [{ podSelector: { matchLabels: { app: 'peer' } } }],
+ ports: [{ port: 8080 }],
+ },
+ ],
+ },
+ ...overrides,
+ }
+}
+
+describe('networkPolicyMatchesDesired', () => {
+ it('CMP-NP-1: recorded apiserver blob equivalent to desired is true', () => {
+ const desired = desiredPolicy()
+ const existing = asApiserverNetworkPolicy(desired)
+ expect(existing.spec).toBeDefined()
+ expect(existing.spec?.ingress?.[0]?.ports?.[0]?.protocol).toBe('TCP')
+ expect(existing.spec?.policyTypes).toEqual(['Ingress'])
+ expect(existing.metadata?.resourceVersion).toBe('1783417')
+ expect(networkPolicyMatchesDesired(desired, existing)).toBe(true)
+ })
+
+ it('CMP-NP-2: port or rule drift is not equivalent', () => {
+ const desired = desiredPolicy()
+ expect(
+ networkPolicyMatchesDesired(desired, asApiserverNetworkPolicy(desired, { port: 9090 }))
+ ).toBe(false)
+
+ const ruleDrift = desiredPolicy({
+ spec: {
+ podSelector: { matchLabels: { app: 'np' } },
+ ingress: [
+ {
+ _from: [{ podSelector: { matchLabels: { app: 'other' } } }],
+ ports: [{ port: 8080 }],
+ },
+ ],
+ },
+ })
+ expect(networkPolicyMatchesDesired(ruleDrift, asApiserverNetworkPolicy(desired))).toBe(false)
+ })
+
+ it('CMP-NP-3: label drift is not equivalent', () => {
+ const desired = desiredPolicy()
+ const labeled = desiredPolicy({
+ metadata: { name: 'np', namespace: 'ns', labels: { app: 'other' } },
+ })
+ expect(networkPolicyMatchesDesired(labeled, asApiserverNetworkPolicy(desired))).toBe(false)
+ })
+
+ it('CMP-NP-4: extra annotation on existing is not equivalent', () => {
+ const desired = desiredPolicy()
+ const existing = asApiserverNetworkPolicy(desired)
+ existing.metadata = {
+ ...existing.metadata,
+ annotations: { 'clerum.io/note': 'live-only' },
+ }
+ expect(networkPolicyMatchesDesired(desired, existing)).toBe(false)
+ })
+
+ it('CMP-NP-5: missing spec or undefined shapes fail open to write', () => {
+ const desired = desiredPolicy()
+ expect(networkPolicyMatchesDesired(desired, { metadata: { name: 'np' } })).toBe(false)
+ expect(
+ networkPolicyMatchesDesired(desired, { spec: null } as unknown as k8s.V1NetworkPolicy)
+ ).toBe(false)
+ expect(networkPolicyMatchesDesired(desired, undefined as unknown as k8s.V1NetworkPolicy)).toBe(
+ false
+ )
+ })
+
+ it('CMP-NP-6: key-order permutation is equal; rule-array reorder is not', () => {
+ const desired: k8s.V1NetworkPolicy = {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: { name: 'np', namespace: 'ns', labels: { b: '2', a: '1' } },
+ spec: {
+ policyTypes: ['Ingress'],
+ podSelector: { matchLabels: { app: 'np' } },
+ ingress: [{ ports: [{ port: 80 }] }, { ports: [{ port: 443 }] }],
+ },
+ }
+ const keyPermuted: k8s.V1NetworkPolicy = {
+ kind: 'NetworkPolicy',
+ apiVersion: 'networking.k8s.io/v1',
+ spec: {
+ ingress: [{ ports: [{ port: 80 }] }, { ports: [{ port: 443 }] }],
+ podSelector: { matchLabels: { app: 'np' } },
+ policyTypes: ['Ingress'],
+ },
+ metadata: { labels: { a: '1', b: '2' }, namespace: 'ns', name: 'np' },
+ }
+ expect(networkPolicyMatchesDesired(desired, keyPermuted)).toBe(true)
+
+ const arrayReordered: k8s.V1NetworkPolicy = {
+ ...desired,
+ spec: {
+ ...desired.spec,
+ ingress: [{ ports: [{ port: 443 }] }, { ports: [{ port: 80 }] }],
+ },
+ }
+ expect(networkPolicyMatchesDesired(desired, arrayReordered)).toBe(false)
+ })
+})
diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.ts
index 57a0e0f13..203db6304 100644
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@ -4,6 +4,7 @@ import type { RecordWithTtl } from 'node:dns'
import * as dns from 'node:dns/promises'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
+import { asApiserverNetworkPolicy } from './__tests__/asApiserverNetworkPolicy'
import { confirmAuthoritativeMcpServerAbsence } from './mcpServerSafety'
import {
networkPolicySafetyPassDurationSeconds,
@@ -5618,6 +5619,27 @@ describe('NetworkPolicyReconciler', () => {
).reconcileExternalEgressSafety(server, [stalePredecessor], () => true)
}
+ it('BYPASS-NP-1: equivalent HCC-owned recorded policy skips replace', async () => {
+ const binding = server.spec.egressBindings![0]
+ const desired = (
+ reconciler as unknown as {
+ buildExactHostEgressPolicy: (
+ server: McpServerCRD,
+ name: string,
+ binding: { cidr?: string; port?: number; protocol?: string },
+ cidrs: string[]
+ ) => k8s.V1NetworkPolicy
+ }
+ ).buildExactHostEgressPolicy(server, desiredName, binding, ['104.18.0.0/16'])
+ mockApi.createNamespacedNetworkPolicy.mockRejectedValueOnce(
+ Object.assign(new Error('already exists'), { code: 409 })
+ )
+ mockApi.readNamespacedNetworkPolicy.mockResolvedValueOnce(asApiserverNetworkPolicy(desired))
+
+ expect(await reconcileExternalEgressSafety()).toBe(true)
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
it('converges an HCC-owned same-name policy instead of aborting the pass', async () => {
mockApi.createNamespacedNetworkPolicy.mockRejectedValueOnce(
Object.assign(new Error('already exists'), { code: 409 })
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index b34625f5d..b23a76c91 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -43,7 +43,12 @@ import {
McpServerCrdStatus,
McpServerResolvedEgressIP,
} from './types'
-import { applyNetworkPolicy, getErrorCode, replaceWithConflictRetry } from './utils'
+import {
+ applyNetworkPolicy,
+ getErrorCode,
+ networkPolicyMatchesDesired,
+ replaceWithConflictRetry,
+} from './utils'
type JsonPatchOperation = {
op: 'add' | 'replace' | 'remove' | 'test'
@@ -2827,7 +2832,8 @@ export class NetworkPolicyReconciler {
// create's catch would issue a second create. Delegating from the top is
// not an option either — the desired-state fence below needs the object
// this request created, which applyNetworkPolicy does not return. The
- // wiring below is kept identical to it on purpose.
+ // wiring below is kept identical to applyNetworkPolicy on purpose,
+ // including isUpToDate: networkPolicyMatchesDesired.
await replaceWithConflictRetry<k8s.V1NetworkPolicy>({
description: `policy "${name}" in ${namespace}`,
logPrefix: '[NetPol]',
@@ -2837,6 +2843,7 @@ export class NetworkPolicyReconciler {
this.networkingApi.replaceNamespacedNetworkPolicy({ name, namespace, body }),
mutationAllowed: isCurrent,
validateExisting: existing => this.assertPolicyOwnership(name, existing, desired, lane),
+ isUpToDate: networkPolicyMatchesDesired,
})
return isCurrent()
}
diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.ts
index ae65abb73..cebfb7a9d 100644
--- a/host-context-controller/src/utils.ts
+++ b/host-context-controller/src/utils.ts
@@ -235,6 +235,58 @@ function isServiceObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
+/**
+ * True when the desired NetworkPolicy is equivalent to the live object, so a
+ * replace would be a no-op. Canonicalize first: the apiserver default-fills
+ * policyTypes and ports[].protocol=TCP, and key order is not stable (#307).
+ * Arrays stay in author order (#214). Doubt or a malformed object returns
+ * false (fail-open-to-write).
+ */
+export function networkPolicyMatchesDesired(
+ desired: k8s.V1NetworkPolicy | undefined,
+ existing: k8s.V1NetworkPolicy | undefined
+): boolean {
+ try {
+ if (!desired?.spec || !existing?.spec) return false
+ return (
+ JSON.stringify(normalizeNetworkPolicyForComparison(desired)) ===
+ JSON.stringify(normalizeNetworkPolicyForComparison(existing))
+ )
+ } catch {
+ return false
+ }
+}
+
+function normalizeNetworkPolicyForComparison(policy: k8s.V1NetworkPolicy): unknown {
+ const normalized = structuredClone(policy) as k8s.V1NetworkPolicy & { status?: unknown }
+ delete normalized.status
+ delete normalized.metadata?.resourceVersion
+ delete normalized.metadata?.uid
+ delete normalized.metadata?.generation
+ delete normalized.metadata?.creationTimestamp
+ delete normalized.metadata?.managedFields
+ delete normalized.metadata?.selfLink
+
+ const spec = normalized.spec
+ if (spec) {
+ if (!spec.policyTypes) {
+ spec.policyTypes = (spec.egress?.length ?? 0) > 0 ? ['Ingress', 'Egress'] : ['Ingress']
+ }
+ for (const rule of spec.ingress ?? []) {
+ for (const port of rule.ports ?? []) {
+ if (port.protocol === 'TCP') delete port.protocol
+ }
+ }
+ for (const rule of spec.egress ?? []) {
+ for (const port of rule.ports ?? []) {
+ if (port.protocol === 'TCP') delete port.protocol
+ }
+ }
+ }
+
+ return normalizeServiceValue(normalized)
+}
+
/** Create-or-replace a NetworkPolicy (409 catch → conflict-retry replace). */
export async function applyNetworkPolicy(
api: k8s.NetworkingV1Api,
@@ -263,6 +315,7 @@ export async function applyNetworkPolicy(
replace: body => api.replaceNamespacedNetworkPolicy({ name, namespace, body }),
mutationAllowed,
validateExisting,
+ isUpToDate: networkPolicyMatchesDesired,
})
}