Skip to content

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

TypeScript

fix(egress): resolve closing-review findings for #299 sliding window

Alfredo Lopezb9abfae22f74
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index c2ceb5798..b53cae8f9 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.165",
+ "version": "0.1.166",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.165",
+ "version": "0.1.166",
"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 c418f74fe..4e8406104 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.165",
+ "version": "0.1.166",
"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/config.externalEgressResync.test.ts b/host-context-controller/src/config.externalEgressResync.test.ts
index 671e85245..63a01fd9e 100644
--- a/host-context-controller/src/config.externalEgressResync.test.ts
+++ b/host-context-controller/src/config.externalEgressResync.test.ts
@@ -62,6 +62,25 @@ describe('external egress sliding-window config (issue #299)', () => {
).rejects.toThrow(/floor/i)
})
+ it('fails loud when the interval exceeds HALF the overlap (audit L2 — grace weakening)', async () => {
+ // interval 200 with overlap 300: 200 <= 300 (old rule) but 200 > 150 (overlap/2)
+ // → the persisted window can lapse between refreshes.
+ await expect(
+ loadConfig({
+ HCC_EXTERNAL_EGRESS_RESYNC_SEC: '200',
+ HCC_EXTERNAL_EGRESS_OVERLAP_SEC: '300',
+ })
+ ).rejects.toThrow(/half the overlap/i)
+ })
+
+ it('accepts interval == overlap/2 exactly', async () => {
+ const { config } = await loadConfig({
+ HCC_EXTERNAL_EGRESS_RESYNC_SEC: '150',
+ HCC_EXTERNAL_EGRESS_OVERLAP_SEC: '300',
+ })
+ expect(config.externalEgressResyncIntervalSec).toBe(150)
+ })
+
it('allows interval 0 (periodic resync disabled) without tripping the invariant', async () => {
const { config } = await loadConfig({ HCC_EXTERNAL_EGRESS_RESYNC_SEC: '0' })
expect(config.externalEgressResyncIntervalSec).toBe(0)
diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.ts
index 156532ce1..10030d05f 100644
--- a/host-context-controller/src/config.ts
+++ b/host-context-controller/src/config.ts
@@ -428,10 +428,14 @@ export function validateExternalEgressResyncInvariant(cfg: {
`HCC_EXTERNAL_EGRESS_RESYNC_SEC (${interval}) must be >= the refresh floor (${floor})`
)
}
- if (interval >= overlap) {
+ // Audit L2: the renewal-write window is only overlap/2 wide, so the interval
+ // must be <= overlap/2 (not just < overlap) — otherwise the persisted window
+ // can lapse between refreshes and a rotated-away IP is pruned with grace ~=
+ // interval instead of TTL+overlap.
+ if (interval * 2 > overlap) {
throw new Error(
- `HCC_EXTERNAL_EGRESS_RESYNC_SEC (${interval}) must be below the overlap window ` +
- `(${overlap}) so accumulated egress IPs never expire between refreshes (issue #299)`
+ `HCC_EXTERNAL_EGRESS_RESYNC_SEC (${interval}) must be <= half the overlap window ` +
+ `(${overlap}/2 = ${overlap / 2}) so the persisted window never lapses between refreshes (issue #299)`
)
}
}
diff --git a/host-context-controller/src/egressSignature.test.ts b/host-context-controller/src/egressSignature.test.ts
new file mode 100644
index 000000000..f31ce3600
--- /dev/null
+++ b/host-context-controller/src/egressSignature.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest'
+import type * as k8s from '@kubernetes/client-node'
+import { egressSignature } from './networkPolicyReconciler'
+
+function policy(egress: unknown[]): k8s.V1NetworkPolicy {
+ return { spec: { podSelector: {}, policyTypes: ['Egress'], egress } } as k8s.V1NetworkPolicy
+}
+
+describe('egressSignature (issue #299 audit H1/R2-1)', () => {
+ it('is INSENSITIVE to key order (R2-1)', () => {
+ const a = policy([
+ { to: [{ ipBlock: { cidr: '1.2.3.4/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },
+ ])
+ const b = policy([
+ { ports: [{ port: 443, protocol: 'TCP' }], to: [{ ipBlock: { cidr: '1.2.3.4/32' } }] },
+ ])
+ expect(egressSignature(a)).toBe(egressSignature(b))
+ })
+
+ it('DETECTS an ipBlock cidr change (no-op only for identical content)', () => {
+ const a = policy([
+ { to: [{ ipBlock: { cidr: '1.1.1.1/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },
+ ])
+ const b = policy([
+ { to: [{ ipBlock: { cidr: '2.2.2.2/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },
+ ])
+ expect(egressSignature(a)).not.toBe(egressSignature(b))
+ })
+
+ it('DETECTS a selector-based `to` change (H1 — canonical captures full rule)', () => {
+ const a = policy([
+ { to: [{ podSelector: { matchLabels: { app: 'a' } } }], ports: [{ port: 8080 }] },
+ ])
+ const b = policy([
+ { to: [{ podSelector: { matchLabels: { app: 'b' } } }], ports: [{ port: 8080 }] },
+ ])
+ expect(egressSignature(a)).not.toBe(egressSignature(b))
+ })
+})
diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.ts
index d78a9e4eb..8f3d3f3e1 100644
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@ -921,6 +921,189 @@ describe('NetworkPolicyReconciler', () => {
expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
+ it('WRITES on resync when the persisted window is AGING even though the IP set is unchanged (issue #299 M1 renewalDue wiring)', async () => {
+ const server: McpServerCRD = {
+ name: 'renew-mcp',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'dev',
+ image: 'renew:latest',
+ transport: { type: 'streamableHttp', url: 'http://renew:3000', port: 3000 },
+ egressBindings: [{ dns: 'api.example.com', port: 443 }],
+ },
+ }
+ await reconciler.reconcileExternalEgress(server)
+ const written = (
+ mockApi.createNamespacedNetworkPolicy.mock.calls[0][0] as { body: k8s.V1NetworkPolicy }
+ ).body
+
+ // Age the persisted window: rewrite each entry's expiresAt to just above now
+ // (well within overlap/2) so renewalDue fires while the IP set is unchanged.
+ const annotations = { ...(written.metadata?.annotations ?? {}) }
+ const state = JSON.parse(annotations['clerum.io/egress-fqdn-state']) as Array<{
+ expiresAt: number
+ }>
+ for (const e of state) e.expiresAt = Date.now() + 1000
+ annotations['clerum.io/egress-fqdn-state'] = JSON.stringify(state)
+
+ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({
+ items: [
+ {
+ metadata: {
+ name: written.metadata?.name,
+ labels: written.metadata?.labels,
+ annotations,
+ },
+ spec: written.spec,
+ },
+ ],
+ })
+ mockApi.createNamespacedNetworkPolicy.mockClear()
+ mockApi.replaceNamespacedNetworkPolicy.mockClear()
+
+ // Same DNS → set unchanged (changed=false) but window aging → renewalDue=true
+ // → the policy MUST be re-persisted (deleting `|| egressRenewalDue` breaks this,
+ // reintroducing the M1 overlap-grace loss).
+ await reconciler.reconcileExternalEgress(server)
+ const wrote =
+ mockApi.createNamespacedNetworkPolicy.mock.calls.length +
+ mockApi.replaceNamespacedNetworkPolicy.mock.calls.length
+ expect(wrote).toBeGreaterThan(0)
+ })
+
+ it('DROPS a blocked/private IP rehydrated from a tampered annotation (issue #299 M3 defense-in-depth)', async () => {
+ const server: McpServerCRD = {
+ name: 'tamper-mcp',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'dev',
+ image: 'tamper:latest',
+ transport: { type: 'streamableHttp', url: 'http://tamper:3000', port: 3000 },
+ egressBindings: [{ dns: 'api.example.com', port: 443 }],
+ },
+ }
+ await reconciler.reconcileExternalEgress(server)
+ const written = (
+ mockApi.createNamespacedNetworkPolicy.mock.calls[0][0] as { body: k8s.V1NetworkPolicy }
+ ).body
+
+ // Simulate a tampered live policy: a private IP injected into BOTH the state
+ // annotation (so it rehydrates) and the spec egress (so a write is needed).
+ const future = Date.now() + 3_600_000
+ const state = [
+ {
+ ip: '1.2.3.4',
+ port: 443,
+ protocol: 'TCP',
+ fqdn: 'api.example.com',
+ expiresAt: future,
+ lastObservedAt: Date.now(),
+ },
+ {
+ ip: '5.6.7.8',
+ port: 443,
+ protocol: 'TCP',
+ fqdn: 'api.example.com',
+ expiresAt: future,
+ lastObservedAt: Date.now(),
+ },
+ {
+ ip: '10.0.0.5',
+ port: 443,
+ protocol: 'TCP',
+ fqdn: 'api.example.com',
+ expiresAt: future,
+ lastObservedAt: Date.now(),
+ },
+ ]
+ const tampered: k8s.V1NetworkPolicy = {
+ metadata: {
+ name: written.metadata?.name,
+ labels: written.metadata?.labels,
+ annotations: { 'clerum.io/egress-fqdn-state': JSON.stringify(state) },
+ },
+ spec: {
+ ...written.spec!,
+ egress: [
+ { to: [{ ipBlock: { cidr: '1.2.3.4/32' } }], ports: [{ port: 443, protocol: 'TCP' }] },
+ { to: [{ ipBlock: { cidr: '5.6.7.8/32' } }], ports: [{ port: 443, protocol: 'TCP' }] },
+ { to: [{ ipBlock: { cidr: '10.0.0.5/32' } }], ports: [{ port: 443, protocol: 'TCP' }] },
+ ],
+ },
+ }
+ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({ items: [tampered] })
+ mockApi.createNamespacedNetworkPolicy.mockClear()
+ mockApi.replaceNamespacedNetworkPolicy.mockClear()
+
+ await reconciler.reconcileExternalEgress(server)
+ // The reconcile must rewrite the policy WITHOUT the private IP.
+ const call =
+ mockApi.replaceNamespacedNetworkPolicy.mock.calls[0]?.[0] ??
+ mockApi.createNamespacedNetworkPolicy.mock.calls[0]?.[0]
+ const cidrs = JSON.stringify(
+ (call as { body: k8s.V1NetworkPolicy })?.body?.spec?.egress ?? []
+ )
+ expect(call).toBeTruthy()
+ expect(cidrs).not.toContain('10.0.0.5')
+ expect(cidrs).toContain('1.2.3.4')
+ })
+
+ it('updates the observed min-TTL from a resolution (issue #299 M4 — feeds the TTL-aware resync)', async () => {
+ resolve4Mock.mockResolvedValueOnce([{ address: '1.2.3.4', ttl: 15 }]) // ttl 15s
+ const server: McpServerCRD = {
+ name: 'ttl-mcp',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'dev',
+ image: 'ttl:latest',
+ transport: { type: 'streamableHttp', url: 'http://ttl:3000', port: 3000 },
+ egressBindings: [{ dns: 'api.example.com', port: 443 }],
+ },
+ }
+ await reconciler.reconcileExternalEgress(server)
+ // The min observed TTL (ms) must reflect the 15s answer — deleting the
+ // Math.min update leaves it Infinity and the resync degrades to the fixed
+ // interval (the #299 under-sampling failure mode).
+ expect(reconciler.externalEgressRefreshMinTtlMs).toBe(15_000)
+ })
+
+ it('accumulates the UNION across a real A->B rotation via rehydration (issue #299 M4 — wiring not vacuous)', async () => {
+ const server: McpServerCRD = {
+ name: 'rot-mcp',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'dev',
+ image: 'rot:latest',
+ transport: { type: 'streamableHttp', url: 'http://rot:3000', port: 3000 },
+ egressBindings: [{ dns: 'api.example.com', port: 443 }],
+ },
+ }
+ // Round 1: DNS serves A only.
+ resolve4Mock.mockResolvedValueOnce([{ address: '140.82.112.3', ttl: 15 }])
+ await reconciler.reconcileExternalEgress(server)
+ const written = (
+ mockApi.createNamespacedNetworkPolicy.mock.calls[0][0] as { body: k8s.V1NetworkPolicy }
+ ).body
+ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({
+ items: [{ metadata: written.metadata, spec: written.spec }],
+ })
+ mockApi.createNamespacedNetworkPolicy.mockClear()
+ mockApi.replaceNamespacedNetworkPolicy.mockClear()
+
+ // Round 2: DNS rotates to B. The written policy must be the UNION {A, B} —
+ // this only holds if previousAnnotations rehydration is actually wired in.
+ resolve4Mock.mockResolvedValueOnce([{ address: '140.82.112.4', ttl: 15 }])
+ await reconciler.reconcileExternalEgress(server)
+ const call =
+ mockApi.replaceNamespacedNetworkPolicy.mock.calls[0]?.[0] ??
+ mockApi.createNamespacedNetworkPolicy.mock.calls[0]?.[0]
+ const egress = JSON.stringify(
+ (call as { body: k8s.V1NetworkPolicy })?.body?.spec?.egress ?? []
+ )
+ expect(egress).toContain('140.82.112.3') // A retained (overlap)
+ expect(egress).toContain('140.82.112.4') // B added
+ })
+
it('is a NO-OP on resync for an unchanged STATIC cidr binding (issue #299 F2 — no static churn)', async () => {
const server: McpServerCRD = {
name: 'cidr-mcp',
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index 130176273..e8cb7865e 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -111,26 +111,32 @@ function isAllowedExternalEgressCidr(cidr: string): boolean {
}
/**
- * A representation-independent signature of a policy's egress: the sorted set of
- * (cidr | except | port/protocol) allow-tuples. Used to decide whether a write is
- * needed WITHOUT the key-ordering fragility of JSON.stringify (audit R2-1): the
- * apiserver/client deserializes rule objects with keys in a different order than
- * the builders emit them, so a raw string compare is always unequal on a live
- * cluster and would defeat the no-churn gate. Comparing this semantic signature
- * is order- and shape-insensitive. Mirrors WRC's `egressSignature`.
+ * Recursively canonicalize a value: sort every object's keys while preserving
+ * array order. Used to compare policy egress without JSON.stringify key-order
+ * fragility.
*/
-function egressSignature(policy: k8s.V1NetworkPolicy): string {
- const tuples: string[] = []
- for (const rule of policy.spec?.egress ?? []) {
- const ports = (rule.ports ?? []).map(p => `${p.protocol ?? 'TCP'}:${p.port ?? '*'}`).sort()
- const portList = ports.length > 0 ? ports : ['*']
- for (const to of rule.to ?? []) {
- const cidr = to.ipBlock?.cidr ?? ''
- const except = (to.ipBlock?.except ?? []).slice().sort().join('+')
- for (const port of portList) tuples.push(`${cidr}|${except}|${port}`)
- }
+function canonicalize(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(canonicalize)
+ if (value && typeof value === 'object') {
+ const src = value as Record<string, unknown>
+ const out: Record<string, unknown> = {}
+ for (const k of Object.keys(src).sort()) out[k] = canonicalize(src[k])
+ return out
}
- return tuples.sort().join(',')
+ return value
+}
+
+/**
+ * A representation-independent signature of a policy's egress: a canonical
+ * (deep key-sorted) JSON of `spec.egress`. Decides whether a write is needed
+ * WITHOUT the key-ordering fragility of a raw JSON.stringify (audit R2-1). Unlike
+ * the earlier tuple-only signature (ipBlock cidr/port), this captures the FULL
+ * rule including selector-based `to` entries (audit H1). HCC external-egress
+ * policies are ipBlock-only today, so H1 does not bite here, but this keeps the
+ * gate correct and mirrors WRC's `egressSignature`.
+ */
+export function egressSignature(policy: k8s.V1NetworkPolicy): string {
+ return JSON.stringify(canonicalize(policy.spec?.egress ?? []))
}
function isPublicDnsHostname(host: string): boolean {
@@ -1010,7 +1016,11 @@ export class NetworkPolicyReconciler {
now,
config: coreConfig,
})
- cidrs = accumulated.cidrs
+ // Defense-in-depth (audit M3): rehydrated IPs (from the policy's own
+ // annotations) bypass the fresh-snapshot CIDR gate, so a tampered/corrupt
+ // state annotation could union a blocked/private IP. Re-validate the
+ // effective set against the blocked ranges before rendering.
+ cidrs = accumulated.cidrs.filter(c => isAllowedExternalEgressCidr(c))
stateAnnotations = accumulated.annotations
egressRenewalDue = accumulated.renewalDue
resolvedEgressIPs.push({
@@ -1042,7 +1052,11 @@ export class NetworkPolicyReconciler {
failures.push(`failed to resolve hostname "${binding.dns}": ${this.errorMessage(err)}`)
continue
}
- cidrs = accumulated.cidrs
+ // Defense-in-depth (audit M3): rehydrated IPs (from the policy's own
+ // annotations) bypass the fresh-snapshot CIDR gate, so a tampered/corrupt
+ // state annotation could union a blocked/private IP. Re-validate the
+ // effective set against the blocked ranges before rendering.
+ cidrs = accumulated.cidrs.filter(c => isAllowedExternalEgressCidr(c))
stateAnnotations = accumulated.annotations
// A freeze keeps the SAME set as the live policy → changed=false → no
// write (no churn while DNS is failing); a genuine change still writes.
diff --git a/packages/network-policy-core/index.cjs b/packages/network-policy-core/index.cjs
index ebbf5d711..fe944bcaf 100644
Binary files a/packages/network-policy-core/index.cjs and b/packages/network-policy-core/index.cjs differ
diff --git a/packages/network-policy-core/index.test.cjs b/packages/network-policy-core/index.test.cjs
index 30b2468a9..48a432909 100644
--- a/packages/network-policy-core/index.test.cjs
+++ b/packages/network-policy-core/index.test.cjs
@@ -261,6 +261,33 @@ test('F3 rehydration hardening: legacy targets with a malformed ip are dropped',
assert.deepEqual(back.entries.map(e => e.ip), ['140.82.112.3'])
})
+// Audit M2: a hostile/misconfigured authoritative TTL must be clamped so an
+// entry cannot be pinned for years.
+test('M2 TTL clamp: an absurd TTL is bounded to 24h + overlap', () => {
+ const day = 24 * 60 * 60 * 1000
+ const out = core.reconcileEgressState(
+ core.emptyState(),
+ [{ fqdn: 'gh', port: 443, protocol: 'TCP', kind: 'ok', ips: ['1.2.3.4'], ttlMs: 2 ** 31 * 1000 }],
+ 1000,
+ CFG
+ )
+ assert.equal(out.entries[0].expiresAt, 1000 + day + CFG.overlapMs, 'TTL clamped to 24h')
+})
+
+// Audit L1: F3 hardening extended to port/expiresAt — a tampered annotation with
+// an out-of-range port or non-finite expiry must be dropped, not rendered as an
+// invalid ipBlock (apiserver 422 loop).
+test('L1 rehydration hardening: entries with an out-of-range port or bad expiry are dropped', () => {
+ const raw = JSON.stringify([
+ { ip: '1.1.1.1', port: 443, protocol: 'TCP', fqdn: 'ok', expiresAt: 9e12, lastObservedAt: 1000 },
+ { ip: '2.2.2.2', port: 1000000000, protocol: 'TCP', fqdn: 'bigport', expiresAt: 9e12, lastObservedAt: 1000 },
+ { ip: '3.3.3.3', port: 0, protocol: 'TCP', fqdn: 'zeroport', expiresAt: 9e12, lastObservedAt: 1000 },
+ { ip: '4.4.4.4', port: 443, protocol: 'TCP', fqdn: 'nanexp', expiresAt: NaN, lastObservedAt: 1000 },
+ ])
+ const back = core.parseState({ [core.STATE_ANNOTATION]: raw }, 2000, CFG)
+ assert.deepEqual(back.entries.map(e => e.ip), ['1.1.1.1'], 'only the valid entry survives')
+})
+
test('H5 rehydration: legacy egress-fqdn-targets is NOT blanked (bounded grace)', () => {
const legacy = { [core.TARGETS_ANNOTATION]: 'gh=140.82.112.3/32,gh=140.82.112.4/32' }
const back = core.parseState(legacy, 1000, CFG)
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index a84aedde4..97d4c06c6 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.282",
+ "version": "0.1.283",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.282",
+ "version": "0.1.283",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index 84fb0aa40..fb6c2bd50 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.282",
+ "version": "0.1.283",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/config.ts b/workflow-recipes/src/config.ts
index 5098aa8e5..6d54f01ec 100644
--- a/workflow-recipes/src/config.ts
+++ b/workflow-recipes/src/config.ts
@@ -134,7 +134,10 @@ export const MIN_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = 1
export const MAX_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = 60 * 60
export const DEFAULT_EXTERNAL_EGRESS_MAX_ENTRIES = 128
export const MIN_EXTERNAL_EGRESS_MAX_ENTRIES = 8
-export const MAX_EXTERNAL_EGRESS_MAX_ENTRIES = 4096
+// Audit L2: at ~150 B/entry across the state + targets annotations, the cap must
+// stay well under Kubernetes' 256KB total-annotation limit or the write fails
+// permanently with a 422. 1300 entries ~= 195KB, a safe ceiling (default is 128).
+export const MAX_EXTERNAL_EGRESS_MAX_ENTRIES = 1300
function getEnvBool(key: string, defaultValue: boolean): boolean {
const value = process.env[key]
@@ -327,18 +330,19 @@ export function loadConfig(): OperatorConfig {
MIN_EXTERNAL_EGRESS_MAX_ENTRIES,
MAX_EXTERNAL_EGRESS_MAX_ENTRIES
)
- // Startup invariant (plan §5): floor <= interval < overlap. A requeue that is
- // not strictly below the overlap lets an entry expire before it is refreshed
- // (reopening the drift window); a floor above the interval is incoherent.
- // Fail loud rather than run with an unsafe window.
+ // Startup invariant (plan §5 + audit L2): floor <= interval <= overlap/2. The
+ // renewal-write window is only overlap/2 wide, so an interval above overlap/2
+ // lets the persisted window lapse before it is refreshed (reopening the drift
+ // window); a floor above the interval is incoherent. Fail loud rather than run
+ // with an unsafe window.
if (
!(
externalEgressRefreshFloorSeconds <= externalEgressRefreshIntervalSeconds &&
- externalEgressRefreshIntervalSeconds < externalEgressOverlapSeconds
+ externalEgressRefreshIntervalSeconds * 2 <= externalEgressOverlapSeconds
)
) {
throw new Error(
- 'Invalid external egress accumulator configuration: require floor <= interval < overlap ' +
+ 'Invalid external egress accumulator configuration: require floor <= interval <= overlap/2 ' +
`(got floor=${externalEgressRefreshFloorSeconds}s, interval=${externalEgressRefreshIntervalSeconds}s, ` +
`overlap=${externalEgressOverlapSeconds}s). Set WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS, ` +
'WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS, and WRC_EXTERNAL_EGRESS_OVERLAP_SECONDS accordingly.'
diff --git a/workflow-recipes/src/reconciler/egressSignature.test.ts b/workflow-recipes/src/reconciler/egressSignature.test.ts
new file mode 100644
index 000000000..a8ce8e4bd
--- /dev/null
+++ b/workflow-recipes/src/reconciler/egressSignature.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest'
+import type * as k8s from '@kubernetes/client-node'
+import { egressSignature } from './workflowRecipeReconciler'
+
+function policy(egress: unknown[]): k8s.V1NetworkPolicy {
+ return { spec: { podSelector: {}, policyTypes: ['Egress'], egress } } as k8s.V1NetworkPolicy
+}
+
+describe('egressSignature (issue #299 audit H1/R2-1)', () => {
+ it('is INSENSITIVE to key order (R2-1): {to,ports} == {ports,to}, ipBlock key order', () => {
+ const a = policy([
+ { to: [{ ipBlock: { cidr: '1.2.3.4/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },
+ ])
+ const b = policy([
+ { ports: [{ port: 443, protocol: 'TCP' }], to: [{ ipBlock: { cidr: '1.2.3.4/32' } }] },
+ ])
+ expect(egressSignature(a)).toBe(egressSignature(b))
+ })
+
+ it('DETECTS a change in a selector-based `to` rule (H1 regression: internal egress must not be blind)', () => {
+ // Same external ipBlock + port; only the internal podSelector target changes.
+ const backendA = policy([
+ { to: [{ ipBlock: { cidr: '140.82.112.3/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },
+ {
+ to: [{ podSelector: { matchLabels: { app: 'backend-a' } } }],
+ ports: [{ protocol: 'TCP', port: 8080 }],
+ },
+ ])
+ const backendB = policy([
+ { to: [{ ipBlock: { cidr: '140.82.112.3/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },
+ {
+ to: [{ podSelector: { matchLabels: { app: 'backend-b' } } }],
+ ports: [{ protocol: 'TCP', port: 8080 }],
+ },
+ ])
+ // The old tuple signature collapsed both selector rules to "||TCP:8080" → equal (the bug).
+ expect(egressSignature(backendA)).not.toBe(egressSignature(backendB))
+ })
+
+ it('DETECTS a namespaceSelector change', () => {
+ const a = policy([
+ { to: [{ namespaceSelector: { matchLabels: { ns: 'a' } } }], ports: [{ port: 80 }] },
+ ])
+ const b = policy([
+ { to: [{ namespaceSelector: { matchLabels: { ns: 'b' } } }], ports: [{ port: 80 }] },
+ ])
+ expect(egressSignature(a)).not.toBe(egressSignature(b))
+ })
+
+ it('DETECTS an ipBlock cidr change and is a no-op for identical content', () => {
+ const a = policy([
+ { to: [{ ipBlock: { cidr: '1.1.1.1/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },
+ ])
+ const b = policy([
+ { to: [{ ipBlock: { cidr: '2.2.2.2/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },
+ ])
+ expect(egressSignature(a)).not.toBe(egressSignature(b))
+ expect(egressSignature(a)).toBe(
+ egressSignature(
+ policy([
+ { to: [{ ipBlock: { cidr: '1.1.1.1/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },
+ ])
+ )
+ )
+ })
+
+ it('handles empty/absent egress deterministically', () => {
+ expect(egressSignature(policy([]))).toBe(
+ egressSignature({ spec: { podSelector: {}, policyTypes: ['Egress'] } } as k8s.V1NetworkPolicy)
+ )
+ })
+})
diff --git a/workflow-recipes/src/reconciler/fqdnResolver.ts b/workflow-recipes/src/reconciler/fqdnResolver.ts
index 7f74ddb8b..aed344d44 100644
--- a/workflow-recipes/src/reconciler/fqdnResolver.ts
+++ b/workflow-recipes/src/reconciler/fqdnResolver.ts
@@ -58,7 +58,7 @@ function cidrOverlaps(left: string, right: string): boolean {
return a.start <= b.end && b.start <= a.end
}
-function isBlockedExternalIPv4(ip: string): boolean {
+export function isBlockedExternalIPv4(ip: string): boolean {
if (ipv4ToNumber(ip) === undefined) return true
return BLOCKED_EGRESS_CIDRS.some(blocked => cidrOverlaps(`${ip}/32`, blocked))
}
diff --git a/workflow-recipes/src/reconciler/resourceBuilder.ts b/workflow-recipes/src/reconciler/resourceBuilder.ts
index 4fd9dfe32..7b7dc447b 100644
--- a/workflow-recipes/src/reconciler/resourceBuilder.ts
+++ b/workflow-recipes/src/reconciler/resourceBuilder.ts
@@ -1,5 +1,6 @@
import * as k8s from '@kubernetes/client-node'
import { createHash, randomBytes } from 'node:crypto'
+import { RESOLVED_AT_ANNOTATION, TARGETS_ANNOTATION } from '@clerum/network-policy-core'
import {
EVENFIRE_REGISTRY_PULL_SECRET_NAME,
isPlatformRegistryImage,
@@ -1540,8 +1541,8 @@ function buildEgressProvenanceAnnotations(
if (resolved.length === 0) return undefined
const targets = resolved.map(r => `${r.source.fqdn}=${r.cidr}`).join(',')
return {
- 'clerum.io/egress-fqdn-resolved-at': new Date().toISOString(),
- 'clerum.io/egress-fqdn-targets': targets,
+ [RESOLVED_AT_ANNOTATION]: new Date().toISOString(),
+ [TARGETS_ANNOTATION]: targets,
}
}
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index faae6105c..f8f9cf79d 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -56,7 +56,12 @@ import { evaluateComputedValues } from './computedValuesEvaluator'
import { CRD_GROUP, CRD_VERSION, WORKFLOWRECIPE_PLURAL } from './crdConstants'
import { sort as sortDependencies } from './dependencyGraph'
import { type AccumulateOutput, accumulateExternalEgress } from './externalEgressAccumulator'
-import { type FqdnLookup, defaultFqdnLookup, resolveExternalEgress } from './fqdnResolver'
+import {
+ type FqdnLookup,
+ defaultFqdnLookup,
+ isBlockedExternalIPv4,
+ resolveExternalEgress,
+} from './fqdnResolver'
import { filterByIncludeWhen } from './includeWhenFilter'
import { resolve as resolveInputs } from './inputResolver'
import {
@@ -630,25 +635,36 @@ export class RuntimeScopeResolutionPendingError extends Error {
}
/**
- * A representation-independent signature of a policy's egress: the sorted set of
- * (cidr | except | port/protocol) allow-tuples. Decides whether a write is needed
- * WITHOUT the key-ordering fragility of JSON.stringify (audit R2-1): the
- * apiserver/client deserializes rule objects with keys ordered differently than
- * the builder emits them, so a raw string compare is always unequal on a live
- * cluster and would defeat the no-churn gate. Mirrors HCC's `egressSignature`.
+ * Recursively canonicalize a value: sort every object's keys (order-insensitive
+ * for objects) while PRESERVING array order (egress/to/ports arrays are emitted
+ * in a deterministic order and the apiserver preserves it). Used to compare
+ * policy egress without the key-ordering fragility of a raw JSON.stringify.
*/
-function egressSignature(policy: k8s.V1NetworkPolicy): string {
- const tuples: string[] = []
- for (const rule of policy.spec?.egress ?? []) {
- const ports = (rule.ports ?? []).map(p => `${p.protocol ?? 'TCP'}:${p.port ?? '*'}`).sort()
- const portList = ports.length > 0 ? ports : ['*']
- for (const to of rule.to ?? []) {
- const cidr = to.ipBlock?.cidr ?? ''
- const except = (to.ipBlock?.except ?? []).slice().sort().join('+')
- for (const port of portList) tuples.push(`${cidr}|${except}|${port}`)
- }
+function canonicalize(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(canonicalize)
+ if (value && typeof value === 'object') {
+ const src = value as Record<string, unknown>
+ const out: Record<string, unknown> = {}
+ for (const k of Object.keys(src).sort()) out[k] = canonicalize(src[k])
+ return out
}
- return tuples.sort().join(',')
+ return value
+}
+
+/**
+ * A representation-independent signature of a policy's egress: a canonical
+ * (deep key-sorted) JSON of `spec.egress`. Decides whether a write is needed
+ * WITHOUT the key-ordering fragility of a raw JSON.stringify (audit R2-1): the
+ * apiserver/client deserializes rule objects with keys ordered differently than
+ * the builder emits them, so a raw compare is always unequal on a live cluster
+ * and would defeat the no-churn gate. Unlike the earlier tuple-only signature,
+ * this captures the FULL rule — including `namespaceSelector`/`podSelector` `to`
+ * entries for internal/cluster-local egress (audit H1): a tuple signature over
+ * ipBlock only was blind to selector changes, stranding a stale policy. Mirrors
+ * HCC's `egressSignature`.
+ */
+export function egressSignature(policy: k8s.V1NetworkPolicy): string {
+ return JSON.stringify(canonicalize(policy.spec?.egress ?? []))
}
export class WorkflowRecipeReconciler {
@@ -3973,8 +3989,22 @@ export class WorkflowRecipeReconciler {
failures
)
}
+ // Audit L3: a transient failure of a newly-added FQDN (with resolving
+ // siblings) does not throw and freezes nothing — surface it so the missing
+ // egress until the next refresh is not silent.
+ if (failures.length > 0) {
+ console.warn(
+ `[WR-Reconciler] ${policyName}: ${failures.length} external egress FQDN(s) failed to resolve this round; policy written without them until the next refresh converges: ${failures
+ .map(f => `${f.fqdn} (${f.retryable ? 'transient' : 'permanent'})`)
+ .join(', ')}`
+ )
+ }
this.warnEgressAccumulator(policyName, acc)
- effectiveResolved = acc.resolved
+ // Defense-in-depth (audit M3): rehydrated IPs bypass the fresh CIDR gate,
+ // so re-validate the effective set against blocked ranges before rendering.
+ effectiveResolved = acc.resolved.filter(
+ r => !isBlockedExternalIPv4(r.cidr.replace(/\/\d+$/, ''))
+ )
stateAnnotations = acc.annotations
egressRenewalDue = acc.renewalDue
@@ -4410,7 +4440,10 @@ export class WorkflowRecipeReconciler {
)
}
this.warnEgressAccumulator(wlPolicyName, acc)
- effectiveExternal = acc.resolved
+ // Defense-in-depth (audit M3): re-validate rehydrated IPs vs blocked ranges.
+ effectiveExternal = acc.resolved.filter(
+ r => !isBlockedExternalIPv4(r.cidr.replace(/\/\d+$/, ''))
+ )
wlStateAnnotations = acc.annotations
wlEgressRenewalDue = acc.renewalDue