Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(egress): sliding-window FQDN egress accumulation to fix stale /32 drift (#299)
Alfredo Lopez1ac02114664b
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex c672234da..7ed85b211 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.163",+ "version": "0.1.164","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.163",+ "version": "0.1.164","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.jsonindex 85b46b7c4..03e7a31dd 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.163",+ "version": "0.1.164","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {@@ -24,6 +24,7 @@"dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",+ "@clerum/network-policy-core": "file:../packages/network-policy-core","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy","@kubernetes/client-node": "^1.0.0","prom-client": "^15.1.3"diff --git a/host-context-controller/src/config.externalEgressResync.test.ts b/host-context-controller/src/config.externalEgressResync.test.tsnew file mode 100644index 000000000..671e85245--- /dev/null+++ b/host-context-controller/src/config.externalEgressResync.test.ts@@ -0,0 +1,76 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++const originalEnv = process.env++const KNOBS = [+ 'HCC_EXTERNAL_EGRESS_RESYNC_SEC',+ 'HCC_EXTERNAL_EGRESS_OVERLAP_SEC',+ 'HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC',+ 'HCC_EXTERNAL_EGRESS_MAX_ENTRIES',+] as const++async function loadConfig(overrides: Partial<Record<(typeof KNOBS)[number], string>>) {+ vi.resetModules()+ process.env = { ...originalEnv }+ for (const k of KNOBS) delete process.env[k]+ for (const [k, v] of Object.entries(overrides)) process.env[k] = v+ return import('./config')+}++afterEach(() => {+ process.env = originalEnv+ vi.resetModules()+})++describe('external egress sliding-window config (issue #299)', () => {+ it('applies plan defaults: interval below overlap, floor 5, cap 128', async () => {+ const { config } = await loadConfig({})+ // Default resync MUST sit below the overlap so entries never expire between+ // refreshes (the #299 gap). It is lowered from the legacy 300 to 60.+ expect(config.externalEgressResyncIntervalSec).toBe(60)+ expect(config.externalEgressOverlapSec).toBe(300)+ expect(config.externalEgressRefreshFloorSec).toBe(5)+ expect(config.externalEgressMaxEntries).toBe(128)+ })++ it('accepts a valid floor <= interval < overlap triple', async () => {+ const { config } = await loadConfig({+ HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC: '10',+ HCC_EXTERNAL_EGRESS_RESYNC_SEC: '30',+ HCC_EXTERNAL_EGRESS_OVERLAP_SEC: '120',+ })+ expect(config.externalEgressRefreshFloorSec).toBe(10)+ expect(config.externalEgressResyncIntervalSec).toBe(30)+ expect(config.externalEgressOverlapSec).toBe(120)+ })++ it('fails loud when the refresh interval is NOT below the overlap', async () => {+ await expect(+ loadConfig({+ HCC_EXTERNAL_EGRESS_RESYNC_SEC: '300',+ HCC_EXTERNAL_EGRESS_OVERLAP_SEC: '300',+ })+ ).rejects.toThrow(/overlap/i)+ })++ it('fails loud when the floor exceeds the interval', async () => {+ await expect(+ loadConfig({+ HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC: '100',+ HCC_EXTERNAL_EGRESS_RESYNC_SEC: '60',+ })+ ).rejects.toThrow(/floor/i)+ })++ 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)+ })++ it('fails loud on a NEGATIVE interval instead of silently disabling resync (audit F4)', async () => {+ // A typo like -60 would silently reinstate the #299 drift bug (resync off).+ await expect(loadConfig({ HCC_EXTERNAL_EGRESS_RESYNC_SEC: '-60' })).rejects.toThrow(+ /HCC_EXTERNAL_EGRESS_RESYNC_SEC/+ )+ })+})diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.tsindex fb5c805ea..156532ce1 100644--- a/host-context-controller/src/config.ts+++ b/host-context-controller/src/config.ts@@ -193,9 +193,25 @@ export interface Config {// Periodic external-egress DNS resync interval (seconds). Re-resolves// McpServer.spec.egressBindings so DNS changes and failures converge without- // requiring a watch event. 0 disables.+ // requiring a watch event. 0 disables. Must sit below externalEgressOverlapSec+ // so accumulated IPs never expire between refreshes (issue #299).externalEgressResyncIntervalSec: number+ // Grace kept after a DNS TTL before an accumulated /32 may expire (seconds).+ // The sliding window that fixes #299: entries live for TTL + overlap, so a+ // provider that rotates a single A record still resolves through the union of+ // recently-live IPs. Set via HCC_EXTERNAL_EGRESS_OVERLAP_SEC.+ externalEgressOverlapSec: number++ // Minimum sane refresh interval (seconds); guards against a hot-loop resync.+ // Set via HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC.+ externalEgressRefreshFloorSec: number++ // Per-FQDN accumulated-entry cap. On overflow the core evicts the+ // least-recently-observed IP (never rejects the policy). Set via+ // HCC_EXTERNAL_EGRESS_MAX_ENTRIES.+ externalEgressMaxEntries: number+// Plugin image-host allowlist (Phase 2.3). Trusted raw-image prefixes for// local-mode McpServer images. Audit mode (default) logs would-be denials// without blocking; enforce mode blocks the workload build.@@ -366,6 +382,61 @@ validateRemovedStatelessCommunicationChannelPolicy(getEnv('CLERUM_STATELESS_COMMUNICATION_CHANNEL_POLICY'))+/**+ * Enforce the external-egress sliding-window invariant (issue #299):+ * refreshFloor >= 1, overlap > 0, maxEntries >= 1, and when the periodic+ * resync is enabled (interval > 0): floor <= interval < overlap.+ * The interval MUST stay below the overlap so an accumulated /32 is refreshed+ * before it can expire; otherwise a gap reopens and the pod loses egress on the+ * next rotation. Fails loud at startup rather than degrading silently.+ */+export function validateExternalEgressResyncInvariant(cfg: {+ externalEgressResyncIntervalSec: number+ externalEgressOverlapSec: number+ externalEgressRefreshFloorSec: number+ externalEgressMaxEntries: number+}): void {+ const interval = cfg.externalEgressResyncIntervalSec+ const overlap = cfg.externalEgressOverlapSec+ const floor = cfg.externalEgressRefreshFloorSec+ const max = cfg.externalEgressMaxEntries++ if (!Number.isInteger(overlap) || overlap <= 0) {+ throw new Error(+ `HCC_EXTERNAL_EGRESS_OVERLAP_SEC must be a positive integer (seconds), got '${overlap}'`+ )+ }+ if (!Number.isInteger(floor) || floor < 1) {+ throw new Error(+ `HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC must be an integer >= 1 (seconds), got '${floor}'`+ )+ }+ if (!Number.isInteger(max) || max < 1) {+ throw new Error(`HCC_EXTERNAL_EGRESS_MAX_ENTRIES must be an integer >= 1, got '${max}'`)+ }+ // A negative interval is a typo, not "disabled" — reject it loudly so it can't+ // silently reinstate the #299 drift bug (audit F4). 0 = explicitly disabled.+ if (!Number.isInteger(interval) || interval < 0) {+ throw new Error(+ `HCC_EXTERNAL_EGRESS_RESYNC_SEC must be an integer >= 0 (0 disables), got '${interval}'`+ )+ }+ // interval 0 disables periodic resync; only enforce ordering when enabled.+ if (interval > 0) {+ if (interval < floor) {+ throw new Error(+ `HCC_EXTERNAL_EGRESS_RESYNC_SEC (${interval}) must be >= the refresh floor (${floor})`+ )+ }+ if (interval >= 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)`+ )+ }+ }+}+export const config: Config = {devMode,@@ -594,8 +665,14 @@ export const config: Config = {// the ClerumConfig interface above.runtimeTokenRotateBeforeSec: getEnvInt('CONTEXT_MAPPER_RUNTIME_TOKEN_ROTATE_BEFORE_S', 86_400),- // Periodic external-egress DNS resync (default 5 min). 0 disables.- externalEgressResyncIntervalSec: getEnvInt('HCC_EXTERNAL_EGRESS_RESYNC_SEC', 300),+ // Periodic external-egress DNS resync. Lowered from the legacy 5 min to 60s so+ // it sits below the 300s overlap window: accumulated IPs are refreshed before+ // they expire, closing the #299 rotation gap. 0 disables (reintroduces the+ // stale-snapshot risk; only for operators who explicitly opt out).+ externalEgressResyncIntervalSec: getEnvInt('HCC_EXTERNAL_EGRESS_RESYNC_SEC', 60),+ externalEgressOverlapSec: getEnvInt('HCC_EXTERNAL_EGRESS_OVERLAP_SEC', 300),+ externalEgressRefreshFloorSec: getEnvInt('HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC', 5),+ externalEgressMaxEntries: getEnvInt('HCC_EXTERNAL_EGRESS_MAX_ENTRIES', 128),// Plugin image-host allowlist (Phase 2.3). Permissive default = current// fleet hosts + registry.evenfire.ai; enforce defaults to false (audit mode).@@ -615,3 +692,7 @@ export const config: Config = {statelessMaxUptimeHours: getEnvInt('CONTEXT_MAPPER_STATELESS_MAX_UPTIME_HOURS', 72),heartbeatPollMs: parseHeartbeatPollMs(getEnv('CONTEXT_MAPPER_HEARTBEAT_POLL_MS')),}++// Fail loud at import time if the external-egress sliding-window knobs are+// inconsistent (issue #299) — a silent misconfig would reopen the rotation gap.+validateExternalEgressResyncInvariant(config)diff --git a/host-context-controller/src/externalEgressAccumulator.test.ts b/host-context-controller/src/externalEgressAccumulator.test.tsnew file mode 100644index 000000000..63419c553--- /dev/null+++ b/host-context-controller/src/externalEgressAccumulator.test.ts@@ -0,0 +1,156 @@+import { describe, expect, it } from 'vitest'+import {+ RESOLVED_AT_ANNOTATION,+ STATE_ANNOTATION,+ TARGETS_ANNOTATION,+} from '@clerum/network-policy-core'+import {+ type AccumulateHostEgressInput,+ accumulateHostExactHostEgress,+} from './externalEgressAccumulator'++const CONFIG = { overlapMs: 300_000, maxEntries: 128 }+const T0 = 1_000_000_000_000 // fixed epoch ms; clock is injected, never Date.now()++function ok(ips: string[], ttlSeconds: number) {+ return { kind: 'ok' as const, ips, ttlSeconds }+}++function baseInput(+ overrides: Partial<AccumulateHostEgressInput> & Pick<AccumulateHostEgressInput, 'resolution'>+): AccumulateHostEgressInput {+ return {+ fqdn: 'api.github.com',+ port: 443,+ protocol: 'TCP',+ previousAnnotations: undefined,+ now: T0,+ config: CONFIG,+ ...overrides,+ }+}++describe('accumulateHostExactHostEgress — issue #299 sliding window (HCC)', () => {+ it('accumulates the UNION of rotating single-IP responses across rounds', () => {+ // Round 1: GitHub serves one A record.+ const r1 = accumulateHostExactHostEgress(baseInput({ resolution: ok(['140.82.112.3'], 15) }))+ expect(r1.cidrs).toEqual(['140.82.112.3/32'])+ expect(r1.changed).toBe(true)++ // Round 2 (TTL later): a DIFFERENT single A record. The effective set must be+ // the UNION, not a replacement — this is the whole fix for #299.+ const r2 = accumulateHostExactHostEgress(+ baseInput({+ resolution: ok(['140.82.112.4'], 15),+ previousAnnotations: r1.annotations,+ now: T0 + 20_000, // within the previous entry's TTL+overlap window+ })+ )+ expect(r2.cidrs).toEqual(['140.82.112.3/32', '140.82.112.4/32'])+ expect(r2.changed).toBe(true)+ })++ it('is a NO-OP (changed=false) when the same IP is re-observed (H4)', () => {+ const r1 = accumulateHostExactHostEgress(baseInput({ resolution: ok(['140.82.112.3'], 15) }))+ const r2 = accumulateHostExactHostEgress(+ baseInput({+ resolution: ok(['140.82.112.3'], 15),+ previousAnnotations: r1.annotations,+ now: T0 + 5_000, // only the timestamp advanced+ })+ )+ expect(r2.cidrs).toEqual(['140.82.112.3/32'])+ expect(r2.changed).toBe(false)+ })++ it('FREEZES the prior set on a transient failure and flags frozen (H1 fail-static)', () => {+ const r1 = accumulateHostExactHostEgress(+ baseInput({ resolution: ok(['140.82.112.3', '140.82.112.4'], 15) })+ )+ const r2 = accumulateHostExactHostEgress(+ baseInput({+ resolution: { kind: 'transient' },+ previousAnnotations: r1.annotations,+ now: T0 + 400_000, // past TTL+overlap: a naive expiry would drop these+ })+ )+ // Fail-static: transient must NOT prune — the pod keeps reaching GitHub.+ expect(r2.cidrs).toEqual(['140.82.112.3/32', '140.82.112.4/32'])+ expect(r2.frozen).toBe(true)+ expect(r2.changed).toBe(false)+ })++ it('returns an EMPTY set on a bootstrap transient (no prior) so the caller can fail loud', () => {+ const r = accumulateHostExactHostEgress(baseInput({ resolution: { kind: 'transient' } }))+ expect(r.cidrs).toEqual([])+ // No prior entries to freeze → nothing frozen; caller treats empty-bootstrap as failure.+ expect(r.frozen).toBe(false)+ })++ it('PRUNES expired entries on a permanent (genuine no-records) result', () => {+ const r1 = accumulateHostExactHostEgress(baseInput({ resolution: ok(['140.82.112.3'], 15) }))+ const r2 = accumulateHostExactHostEgress(+ baseInput({+ resolution: { kind: 'permanent' },+ previousAnnotations: r1.annotations,+ now: T0 + 400_000, // past TTL+overlap; permanent = subject to expiry+ })+ )+ expect(r2.cidrs).toEqual([])+ })++ it('rehydrates the legacy host=ip/32 targets annotation and freezes it on transient (H5)', () => {+ const legacy = { [TARGETS_ANNOTATION]: 'api.github.com=140.82.112.9/32' }+ const r = accumulateHostExactHostEgress(+ baseInput({ resolution: { kind: 'transient' }, previousAnnotations: legacy })+ )+ // Legacy set must NOT be blanked — it is rehydrated and frozen under transient.+ expect(r.cidrs).toEqual(['140.82.112.9/32'])+ expect(r.frozen).toBe(true)+ })++ it('evicts down to the cap (H3) instead of rejecting, and flags overCap', () => {+ const r = accumulateHostExactHostEgress(+ baseInput({+ resolution: ok(['1.1.1.1', '2.2.2.2', '3.3.3.3'], 15),+ config: { overlapMs: 300_000, maxEntries: 2 },+ })+ )+ expect(r.cidrs).toHaveLength(2)+ expect(r.overCap).toBe(true)+ expect(r.evicted).toBe(1)+ })++ it('flags renewalDue (set unchanged) when the persisted window is within overlap/2 of lapsing (M1)', () => {+ const r1 = accumulateHostExactHostEgress(baseInput({ resolution: ok(['140.82.112.3'], 15) }))+ // expiresAt = T0 + 15000 + 300000; overlap/2 = 150000 → due once now-T0 > 165000.+ const r2 = accumulateHostExactHostEgress(+ baseInput({+ resolution: ok(['140.82.112.3'], 15),+ previousAnnotations: r1.annotations,+ now: T0 + 200_000,+ })+ )+ expect(r2.changed).toBe(false)+ expect(r2.renewalDue).toBe(true)+ })++ it('does NOT flag renewalDue right after a write (window fresh)', () => {+ const r1 = accumulateHostExactHostEgress(baseInput({ resolution: ok(['140.82.112.3'], 15) }))+ const r2 = accumulateHostExactHostEgress(+ baseInput({+ resolution: ok(['140.82.112.3'], 15),+ previousAnnotations: r1.annotations,+ now: T0 + 1000,+ })+ )+ expect(r2.changed).toBe(false)+ expect(r2.renewalDue).toBe(false)+ })++ it('stamps both the state and resolved-at annotations for the caller to persist', () => {+ const r = accumulateHostExactHostEgress(baseInput({ resolution: ok(['140.82.112.3'], 15) }))+ expect(r.annotations[STATE_ANNOTATION]).toBeTruthy()+ expect(r.annotations[RESOLVED_AT_ANNOTATION]).toBe(new Date(T0).toISOString())+ })+})diff --git a/host-context-controller/src/externalEgressAccumulator.ts b/host-context-controller/src/externalEgressAccumulator.tsnew file mode 100644index 000000000..4e22ad9fa--- /dev/null+++ b/host-context-controller/src/externalEgressAccumulator.ts@@ -0,0 +1,117 @@+/**+ * externalEgressAccumulator (HCC) — the host-context-controller adapter between+ * `dns.resolve4` and the pure sliding-window core (`@clerum/network-policy-core`),+ * for issue #299.+ *+ * HCC's `reconcileExternalEgress` materializes a single-generation DNS snapshot+ * per McpServer egress binding (`dns.resolve4(binding.dns)` → one /32 per A+ * record). A provider that serves ONE rotating A record (GitHub's api.github.com,+ * TTL ~15s over 140.82.112.0/20) makes that snapshot pin one IP of ~16, so the+ * pod's next resolution lands on an un-pinned IP and the NetworkPolicy drops it.+ *+ * This adapter folds each per-binding snapshot into the accumulated set persisted+ * on THAT policy's annotations, so the effective egress set is the union of+ * recently-live IPs rather than a single photo. Each policy holds the state for a+ * single FQDN (HCC builds one NetworkPolicy per binding), so the cap and window+ * apply per-FQDN.+ *+ * It is a PURE function (clock injected as `now`, previous state read from the+ * caller-supplied annotations). All Kubernetes and DNS I/O stays in the reconciler.+ *+ * Guarantees delegated to the core (see plan §0/§3/§5): H1 fail-static (a+ * `transient` resolver failure freezes the FQDN's entries), H3 eviction (evict,+ * never reject), H4 no-op (change hash over ip/port/protocol only), H5 rehydration+ * (legacy `egress-fqdn-targets` is not blanked).+ */+import {+ type EgressCoreConfig,+ type Observation,+ RESOLVED_AT_ANNOTATION,+ emptyState,+ parseState,+ reconcileEgressState,+ serializeState,+} from '@clerum/network-policy-core'++/** This round's DNS outcome for one binding, normalized for the core. */+export type HostEgressResolution =+ | { kind: 'ok'; ips: string[]; ttlSeconds: number }+ | { kind: 'transient' }+ | { kind: 'permanent' }++export interface AccumulateHostEgressInput {+ /** The binding's exact-host FQDN. */+ fqdn: string+ /** The binding's destination port. */+ port: number+ /** The binding's protocol (TCP/UDP). */+ protocol: string+ /** This round's resolution outcome. */+ resolution: HostEgressResolution+ /** Annotations of the existing NetworkPolicy for this binding, or undefined on bootstrap. */+ previousAnnotations: Record<string, string> | undefined+ /** Injected clock (epoch ms). */+ now: number+ config: EgressCoreConfig+}++export interface AccumulateHostEgressOutput {+ /** The effective accumulated /32 set to render as ipBlocks (sorted, deduped). */+ cidrs: string[]+ /** Annotations to stamp on the policy: serialized state + resolved-at. */+ annotations: Record<string, string>+ /** True iff the (ip,port,protocol) set changed vs the previous state. */+ changed: boolean+ /** True iff the persisted window is aging and must be re-persisted (audit M1). */+ renewalDue: boolean+ /** True iff this FQDN was frozen this round (transient failure with a prior set). */+ frozen: boolean+ /** Number of entries removed by the cap this round (for a Warning event / metric). */+ evicted: number+ /** True iff the cap was hit and eviction happened. */+ overCap: boolean+}++/**+ * Fold one binding's DNS resolution into the accumulated egress set persisted on+ * its policy's annotations, applying the sliding window, fail-static expiry, and+ * eviction from `@clerum/network-policy-core`.+ */+export function accumulateHostExactHostEgress(+ input: AccumulateHostEgressInput+): AccumulateHostEgressOutput {+ const { fqdn, port, protocol, resolution, previousAnnotations, now, config } = input++ const previous = previousAnnotations ? parseState(previousAnnotations, now, config) : emptyState()++ let observation: Observation+ if (resolution.kind === 'ok') {+ observation = {+ fqdn,+ port,+ protocol,+ kind: 'ok',+ ips: resolution.ips,+ ttlMs: resolution.ttlSeconds * 1000,+ }+ } else if (resolution.kind === 'transient') {+ observation = { fqdn, port, protocol, kind: 'transient' }+ } else {+ observation = { fqdn, port, protocol, kind: 'permanent' }+ }++ const out = reconcileEgressState(previous, [observation], now, config)++ return {+ cidrs: out.entries.map(entry => `${entry.ip}/32`),+ annotations: {+ ...serializeState(out.state),+ [RESOLVED_AT_ANNOTATION]: new Date(now).toISOString(),+ },+ changed: out.changed,+ renewalDue: out.renewalDue,+ frozen: out.frozenFqdns.includes(fqdn),+ evicted: out.evicted.length,+ overCap: out.overCap,+ }+}diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 375a37333..3e38c9c94 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -1,7 +1,12 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { HostFleetReconcileError } from './hostReconciler'import { HostK8sRequestTimeoutError } from './k8s/hostK8sApiClient'-import { McpServerWatcher, listAllCommunicationChannels, listAllHosts } from './k8sClient'+import {+ McpServerWatcher,+ externalEgressResyncDelayMs,+ listAllCommunicationChannels,+ listAllHosts,+} from './k8sClient'import type { HostCRD } from './types'function deferred<T = void>(): {@@ -3843,3 +3848,26 @@ describe('McpServerWatcher.startCommunicationChannelWatch — channel-reader reverrorSpy.mockRestore()})})++describe('externalEgressResyncDelayMs (issue #299 H2)', () => {+ it('returns the configured interval (ms) when no TTL has been observed', () => {+ expect(externalEgressResyncDelayMs(60, 5)).toBe(60_000)+ expect(externalEgressResyncDelayMs(60, 5, Infinity)).toBe(60_000)+ })++ it('advances to TTL/2 when the observed TTL is faster than the interval', () => {+ expect(externalEgressResyncDelayMs(60, 5, 15_000)).toBe(7_500)+ })++ it('never drops below the floor even for a tiny TTL', () => {+ expect(externalEgressResyncDelayMs(60, 5, 6_000)).toBe(5_000)+ })++ it('keeps the configured interval when the observed TTL is large', () => {+ expect(externalEgressResyncDelayMs(60, 5, 600_000)).toBe(60_000)+ })++ it('clamps a below-floor configured interval up to the floor', () => {+ expect(externalEgressResyncDelayMs(3, 5)).toBe(5_000)+ })+})diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex ea754b7b5..7fe7ceaec 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -86,6 +86,25 @@ const PLURAL_COMMUNICATIONCHANNELS = 'communicationchannels'const EXTERNAL_EGRESS_RETRY_DELAYS_MS = [5000, 15000, 30000]const EXTERNAL_EGRESS_RESYNC_MAX_CONCURRENCY = 10const EXTERNAL_EGRESS_RESYNC_JITTER_MS = 5000++/**+ * External-egress resync delay (ms), H2 (issue #299). The configured interval is+ * the backstop; a finite observed DNS TTL advances the delay to <= TTL/2 so a+ * rotating low-TTL host is sampled every rotation. The floor is the hard lower+ * bound to avoid a hot-loop. Pure and unit-testable.+ */+export function externalEgressResyncDelayMs(+ intervalSec: number,+ floorSec: number,+ minObservedTtlMs = Infinity+): number {+ const floorMs = floorSec * 1000+ const configuredMs = intervalSec * 1000+ const ttlAwareMs = Number.isFinite(minObservedTtlMs)+ ? Math.min(configuredMs, minObservedTtlMs / 2)+ : configuredMs+ return Math.max(ttlAwareMs, floorMs)+}const COMMUNICATION_CHANNEL_CACHE_RECOVERY_RETRY_MS = 5000const COMMUNICATION_CHANNEL_FLEET_RETRY_DELAYS_MS = [5000, 15000, 30000, 60000, 300000]const HOST_CACHE_RECOVERY_RETRY_MS = 5000@@ -607,7 +626,7 @@ export class McpServerWatcher implements McpServerProvider {// rotation eventually catches up even after a missed MODIFIED event.// Disabled when interval <= 0 (tests).private resyncTimer: ReturnType<typeof setInterval> | null = null- private externalEgressResyncTimer: ReturnType<typeof setInterval> | null = null+ private externalEgressResyncTimer: ReturnType<typeof setTimeout> | null = null// Periodic SharedFileSystem resync (#592): the SFS watch fires only on SFS CRD// changes, not on PVC binding / wfc pod readiness, so a SharedFileSystem that// reported Initializing/Degraded needs a periodic re-reconcile to converge to a@@ -1828,11 +1847,33 @@ export class McpServerWatcher implements McpServerProvider {const externalEgressResyncSec = config.externalEgressResyncIntervalSecif (externalEgressResyncSec > 0) {- this.externalEgressResyncTimer = setInterval(() => {- void this.runExternalEgressResync()- }, externalEgressResyncSec * 1000)+ // Self-rescheduling (not a fixed setInterval) so the delay can advance to+ // <= observed TTL/2 (H2, issue #299) and rescheduling AFTER each pass+ // completes guarantees no overlapping resyncs.+ const scheduleNext = (): void => {+ if (this.stopped) return+ const delayMs = externalEgressResyncDelayMs(+ externalEgressResyncSec,+ config.externalEgressRefreshFloorSec,+ this.netPolReconciler.externalEgressRefreshMinTtlMs+ )+ this.externalEgressResyncTimer = setTimeout(() => {+ void this.runExternalEgressResync().finally(() => scheduleNext())+ }, delayMs)+ this.externalEgressResyncTimer.unref?.()+ }+ // Idempotency guard (audit F5): never arm a second self-rescheduling chain+ // if one is already live (start() runs once today, but a future restart+ // path must not double the cadence).+ if (!this.externalEgressResyncTimer) scheduleNext()console.log(- `[K8s] External egress periodic DNS resync enabled (every ${externalEgressResyncSec}s)`+ `[K8s] External egress periodic DNS resync enabled (every ${externalEgressResyncSec}s, advancing to <= TTL/2)`+ )+ } else {+ console.warn(+ '[K8s] External egress periodic DNS resync DISABLED (HCC_EXTERNAL_EGRESS_RESYNC_SEC=0); ' ++ 'exact-host FQDN egress will NOT converge on DNS rotation between McpServer events — ' ++ 'accumulated IPs can go stale and block workloads (issue #299). Enable it unless you have a specific reason.')}}@@ -2714,7 +2755,7 @@ export class McpServerWatcher implements McpServerProvider {this.gfsResyncTimer = null}if (this.externalEgressResyncTimer) {- clearInterval(this.externalEgressResyncTimer)+ clearTimeout(this.externalEgressResyncTimer)this.externalEgressResyncTimer = null}for (const timer of this.externalEgressRetryTimers.values()) {diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.tsindex 359b03746..d78a9e4eb 100644--- a/host-context-controller/src/networkPolicyReconciler.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.test.ts@@ -1,11 +1,17 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { type Mock, beforeEach, describe, expect, it, vi } from 'vitest'import * as k8s from '@kubernetes/client-node'+import type { RecordWithTtl } from 'node:dns'import * as dns from 'node:dns/promises'import { readFileSync } from 'node:fs'import { join } from 'node:path'import { NetworkPolicyReconciler, PUBLIC_EGRESS_EXCEPT_CIDRS } from './networkPolicyReconciler'import { ContextCRD, McpServerCRD } from './types'+// resolve4({ ttl: true }) returns RecordWithTtl[]; `rec` builds that shape and+// `resolve4Mock` sidesteps the string[]/RecordWithTtl[] overload inference.+const rec = (...ips: string[]): RecordWithTtl[] => ips.map(address => ({ address, ttl: 300 }))+const resolve4Mock = vi.mocked(dns.resolve4) as unknown as Mock+// Mock configvi.mock('./config', () => ({config: {@@ -16,12 +22,21 @@ vi.mock('./config', () => ({port: 8081,runtimeNamespaces: ['mcp-server', 'mcp-host', 'sandbox-recipes', 'rpc-proxy'],k8sApiCidrs: [],+ // #299 sliding-window knobs read by reconcileExternalEgress.+ externalEgressOverlapSec: 300,+ externalEgressMaxEntries: 128,},}))-// Mock dns+// Mock dns. Production now calls resolve4(host, { ttl: true }) for the #299+// sliding window, so the resolver returns RecordWithTtl[] ({ address, ttl }),+// not string[]. `rec()` builds that shape; `resolve4Mock` is the loosely-typed+// mock accessor (resolve4's overloads otherwise infer the string[] return).vi.mock('node:dns/promises', () => ({- resolve4: vi.fn().mockResolvedValue(['1.2.3.4', '5.6.7.8']),+ resolve4: vi.fn().mockResolvedValue([+ { address: '1.2.3.4', ttl: 300 },+ { address: '5.6.7.8', ttl: 300 },+ ]),}))function makeMockNetworkingApi() {@@ -70,7 +85,7 @@ describe('NetworkPolicyReconciler', () => {mockCustomApi = makeMockCustomApi()reconciler = makeReconciler(mockApi, undefined, mockCustomApi)vi.clearAllMocks()- vi.mocked(dns.resolve4).mockResolvedValue(['1.2.3.4', '5.6.7.8'])+ resolve4Mock.mockResolvedValue(rec('1.2.3.4', '5.6.7.8'))})describe('public egress blocklist parity', () => {@@ -830,9 +845,9 @@ describe('NetworkPolicyReconciler', () => {})it('writes resolved egress IP status in stable DNS order', async () => {- vi.mocked(dns.resolve4).mockImplementation(async hostname => {- if (hostname === 'b.example.com') return ['5.6.7.8']- if (hostname === 'a.example.com') return ['1.2.3.4']+ resolve4Mock.mockImplementation(async (hostname: string) => {+ if (hostname === 'b.example.com') return rec('5.6.7.8')+ if (hostname === 'a.example.com') return rec('1.2.3.4')return []})const server: McpServerCRD = {@@ -861,6 +876,153 @@ describe('NetworkPolicyReconciler', () => {])})+ it('is a NO-OP on the next resync when DNS answers are unchanged (issue #299 F2 anti-churn)', async () => {+ const server: McpServerCRD = {+ name: 'noop-mcp',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'dev',+ image: 'noop:latest',+ transport: { type: 'streamableHttp', url: 'http://noop:3000', port: 3000 },+ egressBindings: [{ dns: 'api.example.com', port: 443 }],+ },+ }++ // First reconcile bootstraps and writes the external-egress policy.+ await reconciler.reconcileExternalEgress(server)+ const created = mockApi.createNamespacedNetworkPolicy.mock.calls[0][0] as {+ body: k8s.V1NetworkPolicy+ }+ const written = created.body+ expect(written.metadata?.annotations?.['clerum.io/egress-fqdn-state']).toBeTruthy()++ // The policy is now live with its accumulated state annotation. Feed it back+ // as the existing policy for the next resync tick.+ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({+ items: [+ {+ metadata: {+ name: written.metadata?.name,+ labels: written.metadata?.labels,+ annotations: written.metadata?.annotations,+ },+ spec: written.spec,+ },+ ],+ })+ mockApi.createNamespacedNetworkPolicy.mockClear()+ mockApi.replaceNamespacedNetworkPolicy.mockClear()++ // Second resync: same DNS answers → same IP set → must NOT rewrite the+ // policy (a timestamp-only refresh is a no-op). This is the churn the audit+ // caught: before the fix, RESOLVED_AT + renewed expiry forced a write here.+ await reconciler.reconcileExternalEgress(server)+ expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ 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',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'dev',+ image: 'cidr:latest',+ transport: { type: 'streamableHttp', url: 'http://cidr:3000', port: 3000 },+ egressBindings: [{ cidr: '93.184.216.0/24', port: 443 }],+ },+ }+ await reconciler.reconcileExternalEgress(server)+ const created = mockApi.createNamespacedNetworkPolicy.mock.calls[0][0] as {+ body: k8s.V1NetworkPolicy+ }+ const written = created.body+ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({+ items: [{ metadata: written.metadata, spec: written.spec }],+ })+ mockApi.createNamespacedNetworkPolicy.mockClear()+ mockApi.replaceNamespacedNetworkPolicy.mockClear()++ await reconciler.reconcileExternalEgress(server)+ expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ it('is a NO-OP when the live policy has identical egress but different KEY ORDER (issue #299 R2-1)', async () => {+ // The apiserver/client deserializes egress rules with keys ordered+ // {ports, to} while the builder emits {to, ports}. A raw JSON.stringify+ // compare would see them as different and rewrite every tick (write-storm).+ // The semantic signature must treat them as equal → no-op.+ const server: McpServerCRD = {+ name: 'keyorder-mcp',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'dev',+ image: 'keyorder:latest',+ transport: { type: 'streamableHttp', url: 'http://keyorder:3000', port: 3000 },+ egressBindings: [{ cidr: '93.184.216.0/24', port: 443 }],+ },+ }+ await reconciler.reconcileExternalEgress(server)+ const created = mockApi.createNamespacedNetworkPolicy.mock.calls[0][0] as {+ body: k8s.V1NetworkPolicy+ }+ const written = created.body+ // Rebuild egress rules with keys in apiserver order {ports, to}.+ const reordered: k8s.V1NetworkPolicy = {+ metadata: written.metadata,+ spec: {+ ...written.spec!,+ egress: (written.spec!.egress ?? []).map(r => ({ ports: r.ports, to: r.to })),+ },+ }+ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({ items: [reordered] })+ mockApi.createNamespacedNetworkPolicy.mockClear()+ mockApi.replaceNamespacedNetworkPolicy.mockClear()++ await reconciler.reconcileExternalEgress(server)+ expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ it('self-heals an external-egress policy whose live spec.egress drifted out-of-band (issue #299 L1)', async () => {+ const server: McpServerCRD = {+ name: 'drift-mcp',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'dev',+ image: 'drift:latest',+ transport: { type: 'streamableHttp', url: 'http://drift:3000', port: 3000 },+ egressBindings: [{ cidr: '93.184.216.0/24', port: 443 }],+ },+ }+ await reconciler.reconcileExternalEgress(server)+ const created = mockApi.createNamespacedNetworkPolicy.mock.calls[0][0] as {+ body: k8s.V1NetworkPolicy+ }+ const written = created.body+ // Simulate out-of-band tampering: the live policy's egress was widened.+ const drifted: k8s.V1NetworkPolicy = {+ metadata: written.metadata,+ spec: {+ ...written.spec!,+ egress: [+ { to: [{ ipBlock: { cidr: '0.0.0.0/0' } }], ports: [{ port: 443, protocol: 'TCP' }] },+ ],+ },+ }+ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({ items: [drifted] })+ mockApi.createNamespacedNetworkPolicy.mockClear()+ mockApi.replaceNamespacedNetworkPolicy.mockClear()++ await reconciler.reconcileExternalEgress(server)+ // The reconciler must rewrite the policy back to the declared CIDR.+ const wrote =+ mockApi.createNamespacedNetworkPolicy.mock.calls.length ++ mockApi.replaceNamespacedNetworkPolicy.mock.calls.length+ expect(wrote).toBeGreaterThan(0)+ })+it('rejects private or special-use CIDR bindings fail-closed', async () => {for (const cidr of ['10.0.0.0/8', '169.254.169.254/32', '192.168.1.0/24']) {const server: McpServerCRD = {@@ -883,7 +1045,7 @@ describe('NetworkPolicyReconciler', () => {})it('rejects mixed public/private DNS results for the whole hostname', async () => {- vi.mocked(dns.resolve4).mockResolvedValueOnce(['10.0.0.5', '1.2.3.4'])+ resolve4Mock.mockResolvedValueOnce(rec('10.0.0.5', '1.2.3.4'))const server: McpServerCRD = {name: 'mixed-mcp',namespace: 'mcp-server',@@ -939,7 +1101,7 @@ describe('NetworkPolicyReconciler', () => {})it('does not create an external egress policy when DNS only resolves private IPs', async () => {- vi.mocked(dns.resolve4).mockResolvedValueOnce(['10.0.0.5', '192.168.1.10'])+ resolve4Mock.mockResolvedValueOnce(rec('10.0.0.5', '192.168.1.10'))const server: McpServerCRD = {name: 'private-dns-mcp',namespace: 'mcp-server',diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.tsindex aa19d54ca..130176273 100644--- a/host-context-controller/src/networkPolicyReconciler.ts+++ b/host-context-controller/src/networkPolicyReconciler.ts@@ -16,6 +16,7 @@import * as k8s from '@kubernetes/client-node'import * as dns from 'node:dns/promises'import { isIP } from 'node:net'+import { STATE_ANNOTATION, classifyDnsError } from '@clerum/network-policy-core'import { config } from './config'import {EXTERNAL_EGRESS_POLICY_TYPE,@@ -25,6 +26,7 @@ import {MCPSERVER_LABEL,POLICY_TYPE_LABEL,} from './constants'+import { accumulateHostExactHostEgress } from './externalEgressAccumulator'import {ContextCRD,EgressBinding,@@ -108,6 +110,29 @@ function isAllowedExternalEgressCidr(cidr: string): boolean {return !PUBLIC_EGRESS_EXCEPT_CIDRS.some(blocked => cidrOverlaps(cidr, blocked))}+/**+ * 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`.+ */+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}`)+ }+ }+ return tuples.sort().join(',')+}+function isPublicDnsHostname(host: string): boolean {if (host !== host.trim()) return falseif (host !== host.toLowerCase()) return false@@ -163,12 +188,49 @@ export class NetworkPolicyReconciler {/** Reference to the MCP server cache so we can look up ports. */private serverCache: Map<string, McpServerCRD>+ // H2 (issue #299): smallest DNS TTL (ms) observed across external-egress+ // resolutions. The resync loop advances to <= this/2 so a rotating low-TTL host+ // is sampled every rotation. Ratchets down and never recovers until restart —+ // over-resyncing is cheap (writes are no-ops via the F2 gate) and the safe+ // direction; under-resyncing would reopen #299.+ private externalEgressMinObservedTtlMs = Infinity+constructor(kc: k8s.KubeConfig, serverCache: Map<string, McpServerCRD>) {this.networkingApi = kc.makeApiClient(k8s.NetworkingV1Api)this.customApi = kc.makeApiClient(k8s.CustomObjectsApi)this.serverCache = serverCache}+ /**+ * The smallest DNS TTL (ms) observed so far across external-egress+ * resolutions, or Infinity if none. The resync loop reads this to advance to+ * <= TTL/2 (H2, issue #299).+ */+ get externalEgressRefreshMinTtlMs(): number {+ return this.externalEgressMinObservedTtlMs+ }++ /**+ * Whether an external-egress policy actually needs a write (audit F2/L1):+ * write when it is new, when the ENFORCED spec.egress differs from the live+ * policy (covers ip-set changes AND out-of-band drift self-heal), or once to+ * migrate a legacy policy to the new-format state annotation. A pure+ * timestamp-only refresh (spec identical, annotation already present) is a+ * no-op — no apiserver/CNI churn. The DNS branch additionally forces a write+ * on renewalDue (audit M1), handled at the call site.+ */+ private externalEgressWriteNeeded(+ existing: k8s.V1NetworkPolicy | null,+ desired: k8s.V1NetworkPolicy+ ): boolean {+ if (!existing) return true+ if (egressSignature(existing) !== egressSignature(desired)) {+ return true+ }+ const desiredState = desired.metadata?.annotations?.[STATE_ANNOTATION]+ return Boolean(desiredState) && !existing.metadata?.annotations?.[STATE_ANNOTATION]+ }+private externalEgressPolicyName(serverName: string, binding: EgressBinding): string | null {if (binding.egressClass === 'public-web') {return `ext-egress-${serverName}-public-web`.slice(0, 253)@@ -788,11 +850,23 @@ export class NetworkPolicyReconciler {}let cidrs: string[]+ // Sliding-window state annotations to persist on the policy (issue #299).+ // Only the DNS branch sets this; CIDR/public-web bindings leave it undefined.+ let stateAnnotations: Record<string, string> | undefined+ // The DNS branch sets this when the accumulator's persisted window is aging+ // (audit M1): we must re-persist even if the ip-set is unchanged so a+ // stable-then-rotated IP keeps its overlap grace.+ let egressRenewalDue = falseconst name = this.externalEgressPolicyName(server.name, binding)if (!name) {failures.push('exact-host external egress bindings must declare dns or cidr')continue}+ // Look up the live policy once: used to rehydrate the window (DNS branch)+ // AND to decide whether a write is actually needed (audit F2/L1) — the+ // write is gated on the ENFORCED spec.egress, so identical static policies+ // never churn and out-of-band drift self-heals, for every egress class.+ const existingPolicy = existingPolicies.find(p => p.metadata?.name === name) ?? nullif (egressClass === 'public-web') {if (@@ -846,7 +920,11 @@ export class NetworkPolicyReconciler {},}- await applyNetworkPolicy(this.networkingApi, name, server.namespace, policy, '[NetPol]')+ // public-web is a static policy — write only when new/changed/drifted so+ // the TTL-accelerated resync does not rewrite it every tick (audit F2).+ if (this.externalEgressWriteNeeded(existingPolicy, policy)) {+ await applyNetworkPolicy(this.networkingApi, name, server.namespace, policy, '[NetPol]')+ }continue}@@ -878,9 +956,23 @@ export class NetworkPolicyReconciler {)continue}+ // Sliding-window accumulation (issue #299): a single-generation snapshot+ // pins one rotating IP of a provider that serves 1 A record/response, so+ // the pod's next resolution lands on an un-pinned IP and egress drops.+ // We fold each snapshot into the set persisted on THIS policy's+ // annotations and render the union of recently-live IPs. On a transient+ // resolver failure we fail-static: keep serving the accumulated set+ // rather than deleting the policy (the pre-#299 catch dropped egress on+ // any DNS hiccup).+ const previousAnnotations = existingPolicy?.metadata?.annotations+ const now = Date.parse(resolvedAt)+ const coreConfig = {+ overlapMs: config.externalEgressOverlapSec * 1000,+ maxEntries: config.externalEgressMaxEntries,+ }try {- const ips = await dns.resolve4(binding.dns)- const uniqueIps = [...new Set(ips)].sort()+ const records = await dns.resolve4(binding.dns, { ttl: true })+ const uniqueIps = [...new Set(records.map(r => r.address))].sort()if (uniqueIps.length === 0) {failures.push(`hostname "${binding.dns}" resolved to no IPv4 addresses`)continue@@ -892,19 +984,77 @@ export class NetworkPolicyReconciler {)continue}- cidrs = uniqueIps.map(ip => `${ip}/32`)- const disallowedCidrs = cidrs.filter(cidr => !isAllowedExternalEgressCidr(cidr))+ const freshCidrs = uniqueIps.map(ip => `${ip}/32`)+ const disallowedCidrs = freshCidrs.filter(cidr => !isAllowedExternalEgressCidr(cidr))if (disallowedCidrs.length > 0) {failures.push(`hostname "${binding.dns}" resolved disallowed address(es): ${disallowedCidrs.join(', ')}`)continue}- resolvedEgressIPs.push({ dns: binding.dns, ips: uniqueIps, resolvedAt })+ // Security gates above ran on the FRESH snapshot; only validated IPs+ // enter the accumulator, so the union can never contain a blocked IP.+ const ttlSeconds = records.length > 0 ? Math.min(...records.map(r => r.ttl)) : 0+ if (ttlSeconds > 0) {+ this.externalEgressMinObservedTtlMs = Math.min(+ this.externalEgressMinObservedTtlMs,+ ttlSeconds * 1000+ )+ }+ const accumulated = accumulateHostExactHostEgress({+ fqdn: binding.dns,+ port: binding.port,+ protocol,+ resolution: { kind: 'ok', ips: uniqueIps, ttlSeconds },+ previousAnnotations,+ now,+ config: coreConfig,+ })+ cidrs = accumulated.cidrs+ stateAnnotations = accumulated.annotations+ egressRenewalDue = accumulated.renewalDue+ resolvedEgressIPs.push({+ dns: binding.dns,+ ips: cidrs.map(cidr => cidr.replace(/\/32$/, '')),+ resolvedAt,+ })+ if (accumulated.overCap) {+ console.warn(+ `[NetPol] "${binding.dns}" egress set hit the cap (${config.externalEgressMaxEntries}); evicted ${accumulated.evicted} least-recently-observed IP(s)`+ )+ }console.log(`[NetPol] Resolved ${binding.dns} → [${cidrs.join(', ')}]`)} catch (err) {- failures.push(`failed to resolve hostname "${binding.dns}": ${this.errorMessage(err)}`)- continue+ // Fail-static (H1): freeze the accumulated set on a transient resolver+ // failure; fail loud when there is nothing to serve (bootstrap, or a+ // permanent no-records answer).+ const kind = classifyDnsError(err)+ const accumulated = accumulateHostExactHostEgress({+ fqdn: binding.dns,+ port: binding.port,+ protocol,+ resolution: { kind },+ previousAnnotations,+ now,+ config: coreConfig,+ })+ if (accumulated.cidrs.length === 0) {+ failures.push(`failed to resolve hostname "${binding.dns}": ${this.errorMessage(err)}`)+ continue+ }+ cidrs = accumulated.cidrs+ 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.+ egressRenewalDue = accumulated.renewalDue+ resolvedEgressIPs.push({+ dns: binding.dns,+ ips: cidrs.map(cidr => cidr.replace(/\/32$/, '')),+ resolvedAt,+ })+ console.warn(+ `[NetPol] ${kind} DNS failure for "${binding.dns}"; serving ${cidrs.length} accumulated IP(s) (fail-static, issue #299): ${this.errorMessage(err)}`+ )}} else {continue@@ -924,6 +1074,9 @@ export class NetworkPolicyReconciler {[MCPSERVER_LABEL]: server.name,[EGRESS_CLASS_LABEL]: egressClass,},+ // Persist the sliding-window state so the next reconcile rehydrates the+ // accumulated set instead of collapsing to a single snapshot (#299).+ ...(stateAnnotations ? { annotations: stateAnnotations } : {}),},spec: {podSelector: {@@ -937,7 +1090,14 @@ export class NetworkPolicyReconciler {},}- await applyNetworkPolicy(this.networkingApi, name, server.namespace, policy, '[NetPol]')+ // Write only when the enforced rules changed / the policy is new / drifted+ // (audit F2 no-churn + L1 self-heal), OR when the DNS window is aging and+ // must be re-persisted (audit M1). A pure timestamp refresh is a no-op.+ if (this.externalEgressWriteNeeded(existingPolicy, policy) || egressRenewalDue) {+ await applyNetworkPolicy(this.networkingApi, name, server.namespace, policy, '[NetPol]')+ } else {+ console.log(`[NetPol] External egress "${name}" unchanged — no-op (issue #299 no-churn)`)+ }}try {diff --git a/packages/network-policy-core/index.cjs b/packages/network-policy-core/index.cjsnew file mode 100644index 000000000..ebbf5d711Binary files /dev/null and b/packages/network-policy-core/index.cjs differdiff --git a/packages/network-policy-core/index.d.ts b/packages/network-policy-core/index.d.tsnew file mode 100644index 000000000..d0a99cb03--- /dev/null+++ b/packages/network-policy-core/index.d.ts@@ -0,0 +1,135 @@+/**+ * @clerum/network-policy-core — shared sliding-window egress IP accumulation+ * for FQDN NetworkPolicies (issue #299).+ *+ * Pure module: no Kubernetes and no DNS dependency. The caller (WRC/HCC+ * resolver) does the DNS resolution and passes normalized Observations; the+ * clock is injected as `now` (epoch ms) so the sliding window is deterministic+ * and unit-testable without fake timers.+ *+ * Design guarantees (see plan §0/§3/§5):+ * - Monotonically permissive vs the single snapshot: the latest OK response is+ * always in the set.+ * - H1 fail-static: a DECLARED FQDN whose DNS is transiently failing (an explicit+ * `transient` observation) is FROZEN — its entries never expire while the+ * resolver is failing. A DECLARED FQDN with an `ok`/`permanent` observation+ * expires normally. An FQDN with NO observation this round is no longer+ * declared (removed from the spec) and is REVOKED immediately, never frozen+ * (audit F1: freezing an undeclared FQDN keeps a removed host's egress+ * forever — worse than the original snapshot).+ * - H3 eviction: on overflow, evict the LEAST-RECENTLY-OBSERVED first (tiebreak+ * soonest-expiry, then key), NEVER reject/truncate the policy.+ * - H4 no-op: the change hash is over (fqdn,ip,port,protocol) only, NOT expiry,+ * so a refresh that only renews timestamps writes nothing.+ * - H5 rehydration: parse the previous state from annotations; an old/invalid+ * format is NOT turned into an empty set (the caller keeps the live policy).+ */++export interface EgressEntry {+ ip: string+ port: number+ protocol: string+ fqdn: string+ /** absolute epoch ms; entry is live while now < expiresAt (window) */+ expiresAt: number+ /**+ * epoch ms of the last OK observation of this IP. Eviction (H3) removes the+ * least-recently-OBSERVED first — a faithful LRU that, unlike expiresAt, does+ * not misrank when a host serves a variable TTL. A stable IP re-observed every+ * tick is never evicted.+ */+ lastObservedAt: number+}++export interface EgressState {+ entries: EgressEntry[]+}++export interface EgressCoreConfig {+ /** grace/overlap kept after the DNS TTL, in ms (plan default 300000) */+ overlapMs: number+ /** alarm cap; on overflow we evict, never reject (plan default >=128) */+ maxEntries: number+}++/**+ * A normalized DNS observation for one (fqdn,port,protocol) produced by the+ * resolver this round:+ * - ok: records resolved; `ips` is the A-record set, `ttlMs` the TTL.+ * - transient: resolver/upstream failure (SERVFAIL/timeout) — fail-static (H1).+ * - permanent: the name genuinely has no records — entries expire normally.+ */+export type Observation =+ | { fqdn: string; port: number; protocol?: string; kind: 'ok'; ips: string[]; ttlMs: number }+ | { fqdn: string; port: number; protocol?: string; kind: 'transient' }+ | { fqdn: string; port: number; protocol?: string; kind: 'permanent' }++export interface ReconcileOutput {+ /** next state to persist in annotations */+ state: EgressState+ /** live effective entries to render as ipBlocks (== state.entries) */+ entries: EgressEntry[]+ /** true iff the (ip,port,protocol) set changed vs previous — else NO-OP write */+ changed: boolean+ /**+ * true iff a SURVIVING entry's persisted window is within overlap/2 of lapsing+ * (audit M1). The caller should write even when `changed` is false, to+ * re-persist the renewed window and preserve the overlap grace on the next+ * rotation. Bounded to ~one write per overlap/2 for a stable set.+ */+ renewalDue: boolean+ /** entries removed by the cap this round (for Warning event / metric) */+ evicted: EgressEntry[]+ /** true iff the cap was hit and eviction happened (alarm) */+ overCap: boolean+ /** FQDNs frozen this round because their observation was transient (staleness alarm) */+ frozenFqdns: string[]+}++/** Empty state (bootstrap). */+export declare function emptyState(): EgressState++/**+ * Fold this round's observations into the previous state using the sliding+ * window, fail-static expiry (H1), and eviction (H3). Pure; `now` is injected.+ */+export declare function reconcileEgressState(+ previous: EgressState,+ observations: Observation[],+ now: number,+ config: EgressCoreConfig+): ReconcileOutput++/** Stable change hash over (ip,port,protocol) only — excludes expiresAt (H4). */+export declare function stateHash(entries: EgressEntry[]): string++/** Deterministic, ordered annotation map for the policy (new format + human view). */+export declare function serializeState(state: EgressState): Record<string, string>++/**+ * Rehydrate state from a policy's annotations (H5). Understands the new state+ * format and, as a safe migration, the legacy `egress-fqdn-targets` host=ip/32+ * view (rehydrated with a bounded grace = now + overlapMs since TTL is unknown).+ * Returns an empty state only when nothing parses — the caller then keeps the+ * existing live policy rather than blanking egress.+ */+export declare function parseState(+ annotations: Record<string, string>,+ now: number,+ config: EgressCoreConfig+): EgressState++export declare const STATE_ANNOTATION: string+export declare const TARGETS_ANNOTATION: string+export declare const RESOLVED_AT_ANNOTATION: string++/**+ * Classify a DNS failure as 'transient' (resolver/upstream temporarily+ * unavailable → fail-static freeze, H1) or 'permanent' (genuine no-records →+ * entries expire normally). Accepts a raw code string or an Error with `.code`.+ * Unknown/missing codes default to 'permanent'. Shared source of truth for WRC+ * and HCC so fail-static behaves identically platform-wide (issue #299).+ */+export declare function classifyDnsError(+ errOrCode: unknown+): 'transient' | 'permanent'diff --git a/packages/network-policy-core/index.test.cjs b/packages/network-policy-core/index.test.cjsnew file mode 100644index 000000000..30b2468a9--- /dev/null+++ b/packages/network-policy-core/index.test.cjs@@ -0,0 +1,308 @@+'use strict'++const assert = require('node:assert/strict')+const fs = require('node:fs')+const path = require('node:path')+const test = require('node:test')+const core = require('./index.cjs')++const CFG = { overlapMs: 300_000, maxEntries: 128 }+const TTL = 15_000++const obsOk = (fqdn, ips, ttlMs = TTL, port = 443, protocol = 'TCP') => ({+ fqdn,+ port,+ protocol,+ kind: 'ok',+ ips,+ ttlMs,+})+const obsTransient = (fqdn, port = 443, protocol = 'TCP') => ({ fqdn, port, protocol, kind: 'transient' })+const obsPermanent = (fqdn, port = 443, protocol = 'TCP') => ({ fqdn, port, protocol, kind: 'permanent' })++const ipsOf = out => out.entries.map(e => e.ip).sort()++test('runtime exports stay aligned with the declaration file', () => {+ const declarations = fs.readFileSync(path.join(__dirname, 'index.d.ts'), 'utf8')+ const declared = Array.from(+ declarations.matchAll(/export declare (?:const|function)\s+([A-Za-z0-9_]+)/g),+ m => m[1]+ ).sort()+ assert.deepEqual(Object.keys(core).sort(), declared)+})++test('bootstrap: empty state has no entries', () => {+ assert.deepEqual(core.emptyState().entries, [])+})++test('accumulation: an ok observation adds each IP with expiresAt = now + ttl + overlap', () => {+ const out = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['1.1.1.1'])], 1000, CFG)+ assert.deepEqual(ipsOf(out), ['1.1.1.1'])+ assert.equal(out.entries[0].expiresAt, 1000 + TTL + CFG.overlapMs)+ assert.equal(out.changed, true)+})++test('sliding window: a rotated-away IP is kept until it expires (overlap), new IP added', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['A'])], 1000, CFG).state+ // t within overlap: gh now serves B; A must remain, B added+ const out = core.reconcileEgressState(s, [obsOk('gh', ['B'])], 20_000, CFG)+ assert.deepEqual(ipsOf(out), ['A', 'B'])+})++test('sliding window: re-observing an IP RENEWS its expiry (stable host stays forever)', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('st', ['S'], 60_000)], 1000, CFG).state+ const firstExpiry = s.entries[0].expiresAt+ // long after the first expiry would have been, but re-observed every round+ let now = firstExpiry + 1+ const out = core.reconcileEgressState(s, [obsOk('st', ['S'], 60_000)], now, CFG)+ assert.deepEqual(ipsOf(out), ['S'])+ assert.equal(out.entries[0].expiresAt, now + 60_000 + CFG.overlapMs)+})++// Audit M1: the write gate skips timestamp-only refreshes (H4), so the caller+// needs a signal to RE-PERSIST the renewed window before it goes stale —+// otherwise a stable-then-rotated IP is pruned with zero overlap grace. renewalDue+// fires when a surviving entry's PERSISTED window is within overlap/2 of lapsing.+test('M1 renewalDue: false right after a write (persisted window still fresh)', () => {+ const s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['1.1.1.1'])], 1000, CFG).state+ const out = core.reconcileEgressState(s, [obsOk('gh', ['1.1.1.1'])], 2000, CFG)+ assert.equal(out.changed, false, 'set unchanged')+ assert.equal(out.renewalDue, false, 'window is fresh — no write needed')+})++test('M1 renewalDue: true when the persisted window is within overlap/2 of lapsing (set unchanged)', () => {+ // expiresAt = 1000 + 15000 + 300000 = 316000; overlap/2 = 150000.+ const s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['1.1.1.1'])], 1000, CFG).state+ // now = 200000 → 316000 - 200000 = 116000 < 150000 → renewal due.+ const out = core.reconcileEgressState(s, [obsOk('gh', ['1.1.1.1'])], 200_000, CFG)+ assert.equal(out.changed, false, 'the IP set did not change — this is the M1 case')+ assert.equal(out.renewalDue, true, 'persist the renewed window to preserve overlap grace')+})++test('M1 renewalDue: false on bootstrap (no previous entries to renew)', () => {+ const out = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['1.1.1.1'])], 1000, CFG)+ assert.equal(out.changed, true)+ assert.equal(out.renewalDue, false)+})++// Audit R2-2: renewalDue must fire ONLY when a write would actually ADVANCE the+// entry's expiry. A FROZEN entry (transient DNS, H1) has a fixed expiresAt — a+// write cannot extend it, so forcing one every tick during a DNS outage is pure+// churn exactly when the control plane should be quiet.+test('R2-2 renewalDue: NOT due for a FROZEN entry whose expiry cannot advance', () => {+ const s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['1.1.1.1'])], 1000, CFG).state+ // sustained transient at a time within overlap/2 of the (frozen) expiry+ const out = core.reconcileEgressState(s, [obsTransient('gh')], 200_000, CFG)+ assert.deepEqual(out.frozenFqdns, ['gh'], 'entry is frozen (H1)')+ assert.equal(out.changed, false)+ assert.equal(out.renewalDue, false, 'a write cannot advance a frozen entry — no forced churn')+})++// A rotated-away IP that is being RETAINED (still within its window, not+// re-observed) also cannot be advanced by a write → no renewal churn for it.+test('R2-2 renewalDue: NOT due for a retained rotated-away IP (expiry cannot advance)', () => {+ // gh serves A, then rotates to B; A is retained. At a time where A is within+ // overlap/2 of expiry but B is fresh, renewalDue must be driven only by B, not A.+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['1.1.1.1'])], 1000, CFG).state+ // rotate to B at t=2000 (A retained, B fresh)+ s = core.reconcileEgressState(s, [obsOk('gh', ['2.2.2.2'])], 2000, CFG).state+ // at t=200000: A (expiresAt 316000) within overlap/2; B re-observed → B advances.+ const out = core.reconcileEgressState(s, [obsOk('gh', ['2.2.2.2'])], 200_000, CFG)+ // B is re-observed (advances) AND within overlap/2 (expiresAt 317000-200000=117000<150000)+ // so renewalDue is legitimately true — but driven by B, not the frozen A.+ assert.equal(out.renewalDue, true)+ // The point: if ONLY A were present (no advancing entry), renewalDue would be false.+ let sA = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['1.1.1.1'])], 1000, CFG).state+ sA = core.reconcileEgressState(sA, [obsOk('gh', ['2.2.2.2'])], 2000, CFG).state+ // now observe ONLY B-removed: gh still declared but serves nothing new; A & B retained/expire+ const outA = core.reconcileEgressState(sA, [obsTransient('gh')], 200_000, CFG)+ assert.equal(outA.renewalDue, false, 'no advancing entry → no renewal churn')+})++test('expiry: an IP not re-observed, past its expiry, with an OK observation for its fqdn, is removed', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['A'])], 1000, CFG).state+ const past = s.entries[0].expiresAt + 1+ const out = core.reconcileEgressState(s, [obsOk('gh', ['B'])], past, CFG)+ assert.deepEqual(ipsOf(out), ['B'])+})++test('H1 fail-static: a TRANSIENT observation does NOT expire the fqdn entries (freeze + alarm)', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['A'])], 1000, CFG).state+ const past = s.entries[0].expiresAt + 1+ const out = core.reconcileEgressState(s, [obsTransient('gh')], past, CFG)+ assert.deepEqual(ipsOf(out), ['A'], 'entry must survive a sustained resolver failure')+ assert.deepEqual(out.frozenFqdns, ['gh'])+})++// Audit F1 (issue #299): an FQDN with NO observation this round is no longer+// DECLARED (removed from the spec) — it must be REVOKED, not frozen. Freezing is+// reserved for a DECLARED fqdn whose DNS is transiently failing (an explicit+// transient observation). Keeping an undeclared fqdn's IPs forever is a+// regression worse than the original snapshot (egress never shrinks on removal).+test('F1 revoke: an UNOBSERVED (undeclared) fqdn is dropped, not frozen', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['A'])], 1000, CFG).state+ // no observation for gh at all this round (it was removed from the declared set)+ const out = core.reconcileEgressState(s, [], 1500, CFG) // well within the window+ assert.deepEqual(ipsOf(out), [], 'a removed fqdn must be revoked immediately')+ assert.deepEqual(out.frozenFqdns, [], 'an undeclared fqdn is never frozen')+})++test('F1 revoke: removing ONE fqdn keeps the still-declared one and drops the removed one', () => {+ let s = core.reconcileEgressState(+ core.emptyState(),+ [obsOk('gh', ['A']), obsOk('store', ['B'])],+ 1000,+ CFG+ ).state+ // Next round declares only `store`; `gh` was removed from the spec.+ const out = core.reconcileEgressState(s, [obsOk('store', ['B'])], 1500, CFG)+ assert.deepEqual(ipsOf(out), ['B'], 'gh revoked, store retained')+})++test('permanent (no records) lets entries expire normally (not frozen)', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['A'])], 1000, CFG).state+ const past = s.entries[0].expiresAt + 1+ const out = core.reconcileEgressState(s, [obsPermanent('gh')], past, CFG)+ assert.deepEqual(ipsOf(out), [])+ assert.deepEqual(out.frozenFqdns, [])+})++test('a caducated IP that reappears enters as NEW (does not revive the old expiry)', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['A'])], 1000, CFG).state+ const past = s.entries[0].expiresAt + 1+ s = core.reconcileEgressState(s, [obsOk('gh', ['B'])], past, CFG).state // A expired+ const out = core.reconcileEgressState(s, [obsOk('gh', ['A'])], past + 10, CFG)+ const a = out.entries.find(e => e.ip === 'A')+ assert.equal(a.expiresAt, past + 10 + TTL + CFG.overlapMs)+})++test('H3 eviction: on overflow, evict soonest-to-expire; NEVER reject; keep the newly observed', () => {+ const cfg3 = { overlapMs: 300_000, maxEntries: 3 }+ // three old entries (short ttl → sooner expiry)+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('h', ['o1', 'o2', 'o3'], 1000)], 1000, cfg3).state+ // one fresh entry (long ttl → later expiry) pushes over the cap+ const out = core.reconcileEgressState(s, [obsOk('h', ['fresh'], 60_000)], 1500, cfg3)+ assert.equal(out.entries.length, 3, 'capped, never rejected/truncated to fewer')+ assert.equal(out.overCap, true)+ assert.equal(out.evicted.length, 1)+ assert.ok(out.entries.some(e => e.ip === 'fresh'), 'newly observed IP must never be evicted')+ assert.ok(['o1', 'o2', 'o3'].includes(out.evicted[0].ip), 'evicted one of the soonest-to-expire')+})++test('H3 eviction: soonest-to-expire, NOT oldest-by-insertion (a re-observed old entry survives)', () => {+ const cfg2 = { overlapMs: 300_000, maxEntries: 2 }+ // 'stable' inserted first but re-observed with long ttl; two younger entries with short ttl+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('h', ['stable'], 60_000)], 1000, cfg2).state+ s = core.reconcileEgressState(s, [obsOk('h', ['stable', 'y1'], 60_000)], 2000, cfg2).state+ const out = core.reconcileEgressState(s, [obsOk('h', ['stable', 'y2'], 1000)], 3000, cfg2)+ assert.ok(+ out.entries.some(e => e.ip === 'stable'),+ 'the oldest-by-insertion but re-observed entry must survive'+ )+})++test('H4 no-op: a refresh with the same IPs (only expiry renewed) does not change the hash', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['A', 'B'])], 1000, CFG).state+ const out = core.reconcileEgressState(s, [obsOk('gh', ['A', 'B'])], 5000, CFG)+ assert.equal(out.changed, false, 'renewing timestamps only must be a no-op write')+})++test('changed=true when a new IP is added, and when one is removed', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['A'])], 1000, CFG).state+ assert.equal(core.reconcileEgressState(s, [obsOk('gh', ['A', 'C'])], 2000, CFG).changed, true)+ const past = s.entries[0].expiresAt + 1+ assert.equal(core.reconcileEgressState(s, [obsOk('gh', ['C'])], past, CFG).changed, true)+})++test('stateHash excludes expiresAt (same IPs, different expiry → same hash)', () => {+ const a = [{ ip: '1.1.1.1', port: 443, protocol: 'TCP', fqdn: 'x', expiresAt: 10 }]+ const b = [{ ip: '1.1.1.1', port: 443, protocol: 'TCP', fqdn: 'x', expiresAt: 999999 }]+ assert.equal(core.stateHash(a), core.stateHash(b))+})++test('serializeState is deterministic regardless of entry order', () => {+ const s1 = { entries: [+ { ip: '2.2.2.2', port: 443, protocol: 'TCP', fqdn: 'b', expiresAt: 5 },+ { ip: '1.1.1.1', port: 443, protocol: 'TCP', fqdn: 'a', expiresAt: 9 },+ ] }+ const s2 = { entries: [...s1.entries].reverse() }+ assert.deepEqual(core.serializeState(s1), core.serializeState(s2))+})++test('H5 rehydration: new-format annotations round-trip faithfully', () => {+ const s = core.reconcileEgressState(+ core.emptyState(),+ [obsOk('gh', ['1.1.1.1', '2.2.2.2'])],+ 1000,+ CFG+ ).state+ const ann = core.serializeState(s)+ const back = core.parseState(ann, 2000, CFG)+ assert.deepEqual(ipsOf({ entries: back.entries }), ['1.1.1.1', '2.2.2.2'])+})++// Audit F3: a corrupted/tampered annotation with a malformed ip must NOT be+// rehydrated — otherwise it renders as "<junk>/32", which the apiserver rejects+// with 422, bricking the policy in a reconcile-error loop.+test('F3 rehydration hardening: entries with a malformed ip are dropped', () => {+ const raw = JSON.stringify([+ { ip: '140.82.112.3', port: 443, protocol: 'TCP', fqdn: 'gh', expiresAt: 9e12, lastObservedAt: 1000 },+ { ip: 'not-an-ip', port: 443, protocol: 'TCP', fqdn: 'gh', expiresAt: 9e12, lastObservedAt: 1000 },+ { ip: '10.0.0.999', port: 443, protocol: 'TCP', fqdn: 'gh', expiresAt: 9e12, lastObservedAt: 1000 },+ { ip: '1.2.3.4/32', port: 443, protocol: 'TCP', fqdn: 'gh', expiresAt: 9e12, lastObservedAt: 1000 },+ ])+ const back = core.parseState({ [core.STATE_ANNOTATION]: raw }, 2000, CFG)+ assert.deepEqual(back.entries.map(e => e.ip), ['140.82.112.3'], 'only the valid IPv4 survives')+})++test('F3 rehydration hardening: legacy targets with a malformed ip are dropped', () => {+ const legacy = { [core.TARGETS_ANNOTATION]: 'gh=140.82.112.3/32,bad=nonsense/32' }+ const back = core.parseState(legacy, 1000, CFG)+ assert.deepEqual(back.entries.map(e => e.ip), ['140.82.112.3'])+})++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)+ assert.deepEqual(back.entries.map(e => e.ip).sort(), ['140.82.112.3', '140.82.112.4'])+ assert.equal(back.entries[0].expiresAt, 1000 + CFG.overlapMs, 'bounded grace, TTL unknown')+})++test('H5 rehydration: unparseable annotations yield empty state (caller keeps live policy)', () => {+ assert.deepEqual(core.parseState({ 'clerum.io/egress-fqdn-state': '{not json' }, 1000, CFG).entries, [])+ assert.deepEqual(core.parseState({}, 1000, CFG).entries, [])+})++test('ok with empty ips adds nothing and allows expiry of stale entries for that fqdn', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['A'])], 1000, CFG).state+ const past = s.entries[0].expiresAt + 1+ const out = core.reconcileEgressState(s, [obsOk('gh', [])], past, CFG)+ assert.deepEqual(ipsOf(out), [])+})++// ─── classifyDnsError: the shared transient-vs-permanent contract (issue #299) ──+// One source of truth for "is this DNS failure transient?" used by BOTH the WRC+// and HCC resolvers, so fail-static freezing behaves identically platform-wide.+test('classifyDnsError treats resolver/upstream failures as transient', () => {+ for (const code of ['EAI_AGAIN', 'ESERVFAIL', 'ETIMEOUT', 'ETIMEDOUT', 'ECONNREFUSED', 'EREFUSED', 'ECONNRESET', 'ENETUNREACH']) {+ assert.equal(core.classifyDnsError(code), 'transient', `${code} should be transient`)+ }+})++test('classifyDnsError treats genuine no-records answers as permanent', () => {+ assert.equal(core.classifyDnsError('ENODATA'), 'permanent')+ assert.equal(core.classifyDnsError('ENOTFOUND'), 'permanent')+})++test('classifyDnsError reads the code off an Error object', () => {+ const err = Object.assign(new Error('query ESERVFAIL'), { code: 'ESERVFAIL' })+ assert.equal(core.classifyDnsError(err), 'transient')+ const perm = Object.assign(new Error('query ENOTFOUND'), { code: 'ENOTFOUND' })+ assert.equal(core.classifyDnsError(perm), 'permanent')+})++test('classifyDnsError defaults unknown/undefined codes to permanent (matches WRC)', () => {+ assert.equal(core.classifyDnsError(undefined), 'permanent')+ assert.equal(core.classifyDnsError('ESOMETHINGWEIRD'), 'permanent')+ assert.equal(core.classifyDnsError(new Error('no code')), 'permanent')+})diff --git a/packages/network-policy-core/package.json b/packages/network-policy-core/package.jsonnew file mode 100644index 000000000..75be6daaf--- /dev/null+++ b/packages/network-policy-core/package.json@@ -0,0 +1,20 @@+{+ "name": "@clerum/network-policy-core",+ "version": "0.1.0",+ "private": true,+ "description": "Shared sliding-window egress IP accumulation for FQDN NetworkPolicies (issue #299). Pure, no Kubernetes or DNS dependency; injectable clock.",+ "main": "index.cjs",+ "types": "index.d.ts",+ "exports": {+ ".": {+ "types": "./index.d.ts",+ "require": "./index.cjs",+ "default": "./index.cjs"+ }+ },+ "scripts": {+ "build": "node --check index.cjs",+ "test": "node --test index.test.cjs"+ },+ "license": "MIT"+}diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex 427d02206..f5dc2c0a1 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.280",+ "version": "0.1.281","lockfileVersion": 3,"requires": true,"packages": {@@ -34,7 +34,7 @@"engines": {"node": ">=24"},- "version": "0.1.280"+ "version": "0.1.281"},"../packages/image-policy": {"name": "@clerum/image-policy",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex 06f686096..ea7e0f2a3 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.280",+ "version": "0.1.281","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {@@ -30,6 +30,7 @@"@aws-sdk/client-s3": "^3.1009.0","@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",+ "@clerum/network-policy-core": "file:../packages/network-policy-core","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy","@clerum/workflow-runtime-core": "file:../packages/workflow-runtime-core","@kubernetes/client-node": "^1.0.0",diff --git a/workflow-recipes/src/config.test.ts b/workflow-recipes/src/config.test.tsindex b6acff47c..b6e482bf1 100644--- a/workflow-recipes/src/config.test.ts+++ b/workflow-recipes/src/config.test.ts@@ -252,6 +252,59 @@ describe('loadConfig', () => {const config = loadConfig()expect(config.devMode).toBe(false)})++ // ─── issue #299: external egress sliding-window accumulator knobs ─────────+ it('defaults the external egress accumulator knobs (overlap/floor/interval/max)', () => {+ delete process.env.WRC_EXTERNAL_EGRESS_OVERLAP_SECONDS+ delete process.env.WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS+ delete process.env.WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS+ delete process.env.WRC_EXTERNAL_EGRESS_MAX_ENTRIES+ const config = loadConfig()+ expect(config.externalEgressOverlapSeconds).toBe(300)+ expect(config.externalEgressRefreshFloorSeconds).toBe(5)+ expect(config.externalEgressRefreshIntervalSeconds).toBe(60)+ expect(config.externalEgressMaxEntries).toBe(128)+ })++ it('reads external egress accumulator overrides', () => {+ process.env.WRC_EXTERNAL_EGRESS_OVERLAP_SECONDS = '600'+ process.env.WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = '7'+ process.env.WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS = '30'+ process.env.WRC_EXTERNAL_EGRESS_MAX_ENTRIES = '256'+ const config = loadConfig()+ expect(config.externalEgressOverlapSeconds).toBe(600)+ expect(config.externalEgressRefreshFloorSeconds).toBe(7)+ expect(config.externalEgressRefreshIntervalSeconds).toBe(30)+ expect(config.externalEgressMaxEntries).toBe(256)+ })++ it.each([+ ['WRC_EXTERNAL_EGRESS_OVERLAP_SECONDS', '29'],+ ['WRC_EXTERNAL_EGRESS_OVERLAP_SECONDS', 'not-a-number'],+ ['WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS', '0'],+ ['WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS', '1.5'],+ ['WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS', '0'],+ ['WRC_EXTERNAL_EGRESS_MAX_ENTRIES', '7'],+ ['WRC_EXTERNAL_EGRESS_MAX_ENTRIES', 'lots'],+ ])('rejects invalid external egress knob %s=%s', (key, value) => {+ process.env[key] = value+ expect(() => loadConfig()).toThrow(new RegExp(key))+ })++ it('enforces the floor <= interval < overlap invariant (fail loud)', () => {+ // floor > interval+ process.env.WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = '40'+ process.env.WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS = '30'+ process.env.WRC_EXTERNAL_EGRESS_OVERLAP_SECONDS = '300'+ expect(() => loadConfig()).toThrow(/floor.*interval.*overlap|external egress/i)+ })++ it('rejects an interval that is not strictly below the overlap', () => {+ process.env.WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = '5'+ process.env.WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS = '300'+ process.env.WRC_EXTERNAL_EGRESS_OVERLAP_SECONDS = '300'+ expect(() => loadConfig()).toThrow(/floor.*interval.*overlap|external egress/i)+ })})// An unset/unparseable CLERUM_REGISTRY_URL makes isPlatformRegistryImage() return falsediff --git a/workflow-recipes/src/config.ts b/workflow-recipes/src/config.tsindex 0981abdf4..5098aa8e5 100644--- a/workflow-recipes/src/config.ts+++ b/workflow-recipes/src/config.ts@@ -82,6 +82,16 @@ export interface OperatorConfig {runtimeTokenTtlSeconds: numberruntimeTokenRefreshBeforeSeconds: numberruntimeEgressDnsOverlapSeconds: number+ // issue #299: external egress sliding-window accumulator (fqdnResolver ++ // externalEgressAccumulator). `overlap` is the grace kept after the DNS TTL;+ // `refreshInterval` is the periodic requeue backstop; `refreshFloor` clamps+ // the TTL-aware advance so a TTL=0/1 cannot hot-loop; `maxEntries` is the+ // per-policy alarm cap (evict, never reject). Invariant enforced at startup:+ // floor <= interval < overlap.+ externalEgressOverlapSeconds: number+ externalEgressRefreshIntervalSeconds: number+ externalEgressRefreshFloorSeconds: number+ externalEgressMaxEntries: numbernetworkPolicyEnforcementMode: NetworkPolicyEnforcementModenetworkPolicyEnforcementConfirmed: booleanworkflowMaxSteps: number@@ -112,6 +122,20 @@ export const DEFAULT_RUNTIME_EGRESS_DNS_OVERLAP_SECONDS = 5 * 60export const MIN_RUNTIME_EGRESS_DNS_OVERLAP_SECONDS = 30export const MAX_RUNTIME_EGRESS_DNS_OVERLAP_SECONDS = 60 * 60+// issue #299: external egress accumulator knobs.+export const DEFAULT_EXTERNAL_EGRESS_OVERLAP_SECONDS = 5 * 60+export const MIN_EXTERNAL_EGRESS_OVERLAP_SECONDS = 30+export const MAX_EXTERNAL_EGRESS_OVERLAP_SECONDS = 60 * 60+export const DEFAULT_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS = 60+export const MIN_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS = 1+export const MAX_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS = 60 * 60+export const DEFAULT_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = 5+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+function getEnvBool(key: string, defaultValue: boolean): boolean {const value = process.env[key]if (!value) return defaultValue@@ -278,6 +302,49 @@ export function loadConfig(): OperatorConfig {MAX_RUNTIME_EGRESS_DNS_OVERLAP_SECONDS)+ // issue #299: external egress sliding-window accumulator knobs.+ const externalEgressOverlapSeconds = getEnvBoundedIntRange(+ 'WRC_EXTERNAL_EGRESS_OVERLAP_SECONDS',+ DEFAULT_EXTERNAL_EGRESS_OVERLAP_SECONDS,+ MIN_EXTERNAL_EGRESS_OVERLAP_SECONDS,+ MAX_EXTERNAL_EGRESS_OVERLAP_SECONDS+ )+ const externalEgressRefreshIntervalSeconds = getEnvBoundedIntRange(+ 'WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS',+ DEFAULT_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS,+ MIN_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS,+ MAX_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS+ )+ const externalEgressRefreshFloorSeconds = getEnvBoundedIntRange(+ 'WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS',+ DEFAULT_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS,+ MIN_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS,+ MAX_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS+ )+ const externalEgressMaxEntries = getEnvBoundedIntRange(+ 'WRC_EXTERNAL_EGRESS_MAX_ENTRIES',+ DEFAULT_EXTERNAL_EGRESS_MAX_ENTRIES,+ 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.+ if (+ !(+ externalEgressRefreshFloorSeconds <= externalEgressRefreshIntervalSeconds &&+ externalEgressRefreshIntervalSeconds < externalEgressOverlapSeconds+ )+ ) {+ throw new Error(+ 'Invalid external egress accumulator configuration: require floor <= interval < overlap ' ++ `(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.'+ )+ }+return {devMode: getEnvBool('CLERUM_DEV_MODE', false),port: getEnvInt('CLERUM_OPERATOR_PORT', 8082),@@ -311,6 +378,10 @@ export function loadConfig(): OperatorConfig {runtimeTokenTtlSeconds,runtimeTokenRefreshBeforeSeconds,runtimeEgressDnsOverlapSeconds,+ externalEgressOverlapSeconds,+ externalEgressRefreshIntervalSeconds,+ externalEgressRefreshFloorSeconds,+ externalEgressMaxEntries,networkPolicyEnforcementMode: getNetworkPolicyEnforcementMode(),networkPolicyEnforcementConfirmed: getEnvBool('CLERUM_NETWORK_POLICY_ENFORCEMENT_CONFIRMED',diff --git a/workflow-recipes/src/k8sClient.test.ts b/workflow-recipes/src/k8sClient.test.tsindex 6e06b8fac..0e9c1496e 100644--- a/workflow-recipes/src/k8sClient.test.ts+++ b/workflow-recipes/src/k8sClient.test.ts@@ -2,6 +2,8 @@ import { describe, expect, it, vi } from 'vitest'import {WorkflowRecipeWatcher,controllerErrorTelemetryProjection,+ externalEgressRefreshIntervalMs,+ recipeHasExternalExactHostEgress,recipeReferencesNamedSecrets,reconcileOutcomeTelemetryProjection,rotateBrokerTokensOnce,@@ -1715,3 +1717,408 @@ describe('transient-result requeue (scheduleTransientRetry)', () => {}})})++// issue #299 §3.2/§5 — the periodic external-egress requeue timer. GitHub rotates+// its api.github.com A record (~15s TTL over 140.82.112.0/20) WITHOUT bumping the+// WorkflowRecipe CRD generation, so a generation-only reconcile trigger never+// re-runs the accumulator and the sliding-window set never converges on a fresh+// IP. This timer re-enqueues cached recipes that declare an exact-host EXTERNAL+// egress on a fixed cadence so the accumulator folds each new snapshot.+describe('external egress periodic refresh (issue #299 §3.2/§5)', () => {+ function makeUiEgressRecipe(name: string): WorkflowRecipeCRD {+ return makeWorkflowRecipe({+ metadata: { name, namespace: 'sandbox-recipes' },+ spec: {+ steps: [],+ workloads: [{ id: 'ui', type: 'deployment', image: 'clerum/ui:test' }],+ ui: {+ workloadRef: 'ui',+ port: 8080,+ egress: { external: [{ fqdn: 'api.github.com', port: 443 }] },+ },+ },+ })+ }++ function makeWorkloadEgressRecipe(name: string): WorkflowRecipeCRD {+ return makeWorkflowRecipe({+ metadata: { name, namespace: 'sandbox-recipes' },+ spec: {+ steps: [],+ workloads: [+ {+ id: 'api',+ type: 'deployment',+ image: 'clerum/api:test',+ egressBindings: [{ dns: 'api.github.com', port: 443 }],+ },+ ],+ },+ })+ }++ function makeClusterLocalOnlyRecipe(name: string): WorkflowRecipeCRD {+ return makeWorkflowRecipe({+ metadata: { name, namespace: 'sandbox-recipes' },+ spec: {+ steps: [],+ workloads: [+ { id: 'db', type: 'deployment', image: 'clerum/db:test' },+ {+ id: 'api',+ type: 'deployment',+ image: 'clerum/api:test',+ egressBindings: [{ dns: 'db.sandbox-recipes.svc.cluster.local', port: 5432 }],+ },+ ],+ },+ })+ }++ function makeTransportOnlyRecipe(name: string): WorkflowRecipeCRD {+ return makeWorkflowRecipe({+ metadata: { name, namespace: 'sandbox-recipes' },+ spec: {+ steps: [],+ workloads: [+ {+ id: 'mcp',+ type: 'deployment',+ image: 'clerum/mcp:test',+ transport: { type: 'streamableHttp' },+ egressBindings: [{ egressClass: 'public-web' }],+ },+ ],+ },+ })+ }++ function makePlainRecipe(name: string): WorkflowRecipeCRD {+ return makeWorkflowRecipe({+ metadata: { name, namespace: 'sandbox-recipes' },+ spec: {+ steps: [],+ workloads: [{ id: 'api', type: 'deployment', image: 'clerum/api:test' }],+ },+ })+ }++ describe('recipeHasExternalExactHostEgress', () => {+ it('is true for a UI external egress FQDN', () => {+ expect(recipeHasExternalExactHostEgress(makeUiEgressRecipe('ui'))).toBe(true)+ })++ it('is true for a non-transport workload egressBinding with an external FQDN', () => {+ expect(recipeHasExternalExactHostEgress(makeWorkloadEgressRecipe('wl'))).toBe(true)+ })++ it('is false when the only binding is a cluster-local sibling (not external)', () => {+ expect(recipeHasExternalExactHostEgress(makeClusterLocalOnlyRecipe('cl'))).toBe(false)+ })++ it('is false for a transport-only (HCC-delegated) egress workload', () => {+ // Transport egress is delegated to HCC/McpServer, NOT folded by the WRC+ // accumulator, so the timer must not select it.+ expect(recipeHasExternalExactHostEgress(makeTransportOnlyRecipe('tr'))).toBe(false)+ })++ it('is false for a recipe with no egress at all', () => {+ expect(recipeHasExternalExactHostEgress(makePlainRecipe('plain'))).toBe(false)+ })++ it('is false while the recipe is being deleted', () => {+ const recipe = makeUiEgressRecipe('deleting')+ recipe.metadata.deletionTimestamp = '2026-08-08T00:00:00Z'+ expect(recipeHasExternalExactHostEgress(recipe)).toBe(false)+ })++ it('excludes the UI workload id from the workload-binding scan (it is covered by ui.egress)', () => {+ // A recipe whose ONLY external binding lives on the ui workload itself must+ // still resolve true via ui.egress.external, never via the workload scan.+ const recipe = makeUiEgressRecipe('ui-wl')+ recipe.spec.workloads = [+ {+ id: 'ui',+ type: 'deployment',+ image: 'clerum/ui:test',+ egressBindings: [{ dns: 'db.sandbox-recipes.svc.cluster.local', port: 5432 }],+ },+ ]+ // ui.egress.external drives the true result; the ui workload's own binding+ // (cluster-local here) is skipped.+ expect(recipeHasExternalExactHostEgress(recipe)).toBe(true)+ })+ })++ describe('externalEgressRefreshIntervalMs', () => {+ it('returns the configured interval (seconds → ms) when above the floor', () => {+ expect(+ externalEgressRefreshIntervalMs({+ externalEgressRefreshIntervalSeconds: 60,+ externalEgressRefreshFloorSeconds: 5,+ })+ ).toBe(60_000)+ })++ it('clamps up to the floor when the interval is below it', () => {+ expect(+ externalEgressRefreshIntervalMs({+ externalEgressRefreshIntervalSeconds: 3,+ externalEgressRefreshFloorSeconds: 5,+ })+ ).toBe(5_000)+ })++ // H2 (issue #299): advance the refresh to <= observed TTL / 2 so a rotating+ // low-TTL host (GitHub api, TTL ~15s) is sampled every rotation, not every 60s.+ it('advances to TTL/2 when the observed TTL makes it faster than the configured interval', () => {+ expect(+ externalEgressRefreshIntervalMs(+ { externalEgressRefreshIntervalSeconds: 60, externalEgressRefreshFloorSeconds: 5 },+ 15_000 // observed min TTL 15s → 7.5s refresh+ )+ ).toBe(7_500)+ })++ it('never drops below the floor even for a tiny TTL', () => {+ expect(+ externalEgressRefreshIntervalMs(+ { externalEgressRefreshIntervalSeconds: 60, externalEgressRefreshFloorSeconds: 5 },+ 6_000 // TTL/2 = 3s < floor 5s → floor+ )+ ).toBe(5_000)+ })++ it('keeps the configured interval when the observed TTL is large', () => {+ expect(+ externalEgressRefreshIntervalMs(+ { externalEgressRefreshIntervalSeconds: 60, externalEgressRefreshFloorSeconds: 5 },+ 600_000 // TTL/2 = 300s > interval 60s → interval wins+ )+ ).toBe(60_000)+ })++ it('ignores a non-finite/absent observed TTL (falls back to the configured interval)', () => {+ expect(+ externalEgressRefreshIntervalMs(+ { externalEgressRefreshIntervalSeconds: 60, externalEgressRefreshFloorSeconds: 5 },+ Infinity+ )+ ).toBe(60_000)+ })+ })++ type InternalWatcher = {+ recipes: Map<string, WorkflowRecipeCRD>+ eventQueue: { enqueue: (key: string, task: () => Promise<void>) => Promise<void> }+ handleRecipeEvent: (+ type: string,+ recipe: WorkflowRecipeCRD,+ options?: { forceReconcile?: boolean }+ ) => Promise<void>+ stopped: boolean+ config: {+ externalEgressRefreshIntervalSeconds: number+ externalEgressRefreshFloorSeconds: number+ }+ externalEgressRefreshTimer: ReturnType<typeof setInterval> | null+ externalEgressRefreshRunning: boolean+ // H2 (issue #299): the refresh loop reads the reconciler's observed min TTL.+ reconciler: { externalEgressRefreshMinTtlMs: number }+ refreshExternalEgressForActiveRecipes: () => Promise<void>+ startExternalEgressRefreshLoop: () => void+ stop: () => Promise<void>+ }++ function makeInternal(recipes: WorkflowRecipeCRD[]) {+ const enqueue = vi.fn((_key: string, task: () => Promise<void>) => task())+ const handleRecipeEvent = vi.fn().mockResolvedValue(undefined)+ const internal = Object.create(WorkflowRecipeWatcher.prototype) as InternalWatcher+ internal.recipes = new Map(recipes.map(r => [r.metadata.name, r]))+ internal.eventQueue = { enqueue }+ internal.handleRecipeEvent = handleRecipeEvent+ internal.stopped = false+ internal.config = {+ externalEgressRefreshIntervalSeconds: 60,+ externalEgressRefreshFloorSeconds: 5,+ }+ internal.externalEgressRefreshTimer = null+ internal.externalEgressRefreshRunning = false+ internal.reconciler = { externalEgressRefreshMinTtlMs: Infinity }+ return { internal, enqueue, handleRecipeEvent }+ }++ it('refreshExternalEgressForActiveRecipes re-enqueues ONLY recipes with external exact-host egress', async () => {+ const { internal, enqueue, handleRecipeEvent } = makeInternal([+ makeUiEgressRecipe('with-ui-egress'),+ makeWorkloadEgressRecipe('with-wl-egress'),+ makePlainRecipe('plain'),+ makeClusterLocalOnlyRecipe('cluster-local'),+ makeTransportOnlyRecipe('transport'),+ ])++ await internal.refreshExternalEgressForActiveRecipes()++ expect(enqueue).toHaveBeenCalledWith('with-ui-egress', expect.any(Function))+ expect(enqueue).toHaveBeenCalledWith('with-wl-egress', expect.any(Function))+ expect(enqueue).not.toHaveBeenCalledWith('plain', expect.any(Function))+ expect(enqueue).not.toHaveBeenCalledWith('cluster-local', expect.any(Function))+ expect(enqueue).not.toHaveBeenCalledWith('transport', expect.any(Function))+ expect(enqueue).toHaveBeenCalledTimes(2)++ // A full reconcile is forced (generation is unchanged, so a plain MODIFIED+ // would short-circuit before the accumulator runs).+ for (const name of ['with-ui-egress', 'with-wl-egress']) {+ expect(handleRecipeEvent).toHaveBeenCalledWith('MODIFIED', internal.recipes.get(name), {+ forceReconcile: true,+ })+ }+ })++ it('refreshExternalEgressForActiveRecipes is a no-op while stopped', async () => {+ const { internal, enqueue } = makeInternal([makeUiEgressRecipe('with-ui-egress')])+ internal.stopped = true+ await internal.refreshExternalEgressForActiveRecipes()+ expect(enqueue).not.toHaveBeenCalled()+ })++ it('the timer re-enqueues external-egress recipes on each tick at the clamped interval', async () => {+ vi.useFakeTimers()+ try {+ const { internal, handleRecipeEvent } = makeInternal([+ makeUiEgressRecipe('with-ui-egress'),+ makePlainRecipe('plain'),+ ])++ internal.startExternalEgressRefreshLoop()+ expect(internal.externalEgressRefreshTimer).not.toBeNull()+ expect(handleRecipeEvent).not.toHaveBeenCalled()++ // 1ms before the 60s interval: nothing has fired.+ await vi.advanceTimersByTimeAsync(59_999)+ expect(handleRecipeEvent).not.toHaveBeenCalled()++ await vi.advanceTimersByTimeAsync(1)+ expect(handleRecipeEvent).toHaveBeenCalledTimes(1)+ expect(handleRecipeEvent).toHaveBeenCalledWith(+ 'MODIFIED',+ internal.recipes.get('with-ui-egress'),+ { forceReconcile: true }+ )++ // Second tick fires again — the requeue is periodic, not one-shot.+ await vi.advanceTimersByTimeAsync(60_000)+ expect(handleRecipeEvent).toHaveBeenCalledTimes(2)+ } finally {+ vi.useRealTimers()+ }+ })++ it('advances the refresh to TTL/2 when the reconciler has observed a low TTL (H2 wiring)', async () => {+ vi.useFakeTimers()+ try {+ const { internal, handleRecipeEvent } = makeInternal([makeUiEgressRecipe('with-ui-egress')])+ // The reconciler observed GitHub's ~15s TTL → the loop must fire at 7.5s,+ // not the 60s configured interval.+ internal.reconciler = { externalEgressRefreshMinTtlMs: 15_000 }++ internal.startExternalEgressRefreshLoop()+ await vi.advanceTimersByTimeAsync(7_499)+ expect(handleRecipeEvent).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ expect(handleRecipeEvent).toHaveBeenCalledTimes(1)+ } finally {+ vi.useRealTimers()+ }+ })++ it('startExternalEgressRefreshLoop is idempotent (does not create a second timer)', () => {+ vi.useFakeTimers()+ try {+ const { internal } = makeInternal([makeUiEgressRecipe('with-ui-egress')])+ internal.startExternalEgressRefreshLoop()+ const first = internal.externalEgressRefreshTimer+ internal.startExternalEgressRefreshLoop()+ expect(internal.externalEgressRefreshTimer).toBe(first)+ } finally {+ vi.useRealTimers()+ }+ })++ it('does not start a second refresh pass while one is still running (no concurrent duplicates)', async () => {+ vi.useFakeTimers()+ try {+ // handleRecipeEvent returns a promise that stays pending until we release it,+ // so the first pass is still in-flight when the second tick fires.+ let release: (() => void) | undefined+ const gate = new Promise<void>(resolve => {+ release = resolve+ })+ const enqueue = vi.fn((_key: string, task: () => Promise<void>) => task())+ const handleRecipeEvent = vi.fn().mockReturnValue(gate)+ const internal = Object.create(WorkflowRecipeWatcher.prototype) as InternalWatcher+ internal.recipes = new Map([['with-ui-egress', makeUiEgressRecipe('with-ui-egress')]])+ internal.eventQueue = { enqueue }+ internal.handleRecipeEvent = handleRecipeEvent+ internal.stopped = false+ internal.config = {+ externalEgressRefreshIntervalSeconds: 60,+ externalEgressRefreshFloorSeconds: 5,+ }+ internal.externalEgressRefreshTimer = null+ internal.externalEgressRefreshRunning = false+ internal.reconciler = { externalEgressRefreshMinTtlMs: Infinity }++ internal.startExternalEgressRefreshLoop()+ await vi.advanceTimersByTimeAsync(60_000) // first tick — pass starts, stays in-flight+ expect(handleRecipeEvent).toHaveBeenCalledTimes(1)+ expect(internal.externalEgressRefreshRunning).toBe(true)++ await vi.advanceTimersByTimeAsync(60_000) // second tick — must be skipped+ expect(handleRecipeEvent).toHaveBeenCalledTimes(1)++ release?.()+ await gate+ } finally {+ vi.useRealTimers()+ }+ })++ it('stop() clears the refresh timer so no further ticks fire', async () => {+ vi.useFakeTimers()+ try {+ const { internal, handleRecipeEvent } = makeInternal([makeUiEgressRecipe('with-ui-egress')])+ // Minimal shape for stop() — every other subsystem is absent in this fixture.+ const stoppableInternal = internal as unknown as {+ transientRetries: Map<string, { timer: ReturnType<typeof setTimeout>; attempts: number }>+ runtimeCredentialRefreshTimer: ReturnType<typeof setInterval> | null+ workloadStatusRefreshTimer: ReturnType<typeof setInterval> | null+ watchRequest: { abort: () => void } | null+ secretWatchLoops: { stop: () => void }[]+ brokerRotationTimer: ReturnType<typeof setInterval> | null+ dbRunProcessor: { stop: () => Promise<void> } | null+ traceReporter: null+ }+ stoppableInternal.transientRetries = new Map()+ stoppableInternal.runtimeCredentialRefreshTimer = null+ stoppableInternal.workloadStatusRefreshTimer = null+ stoppableInternal.watchRequest = null+ stoppableInternal.secretWatchLoops = []+ stoppableInternal.brokerRotationTimer = null+ stoppableInternal.dbRunProcessor = null+ stoppableInternal.traceReporter = null++ internal.startExternalEgressRefreshLoop()+ expect(internal.externalEgressRefreshTimer).not.toBeNull()++ await internal.stop()+ expect(internal.externalEgressRefreshTimer).toBeNull()+ expect(internal.stopped).toBe(true)++ await vi.advanceTimersByTimeAsync(120_000)+ expect(handleRecipeEvent).not.toHaveBeenCalled()+ } finally {+ vi.useRealTimers()+ }+ })+})diff --git a/workflow-recipes/src/k8sClient.ts b/workflow-recipes/src/k8sClient.tsindex 591cec3af..3d67281bc 100644--- a/workflow-recipes/src/k8sClient.ts+++ b/workflow-recipes/src/k8sClient.ts@@ -31,7 +31,10 @@ import {} from './reconciler/dbRunProcessor'import { getErrorCode } from './reconciler/k8sErrors'import { RecipeEventQueue } from './reconciler/recipeEventQueue'-import { recipeHasBackgroundAccessClient } from './reconciler/resourceBuilder'+import {+ parseClusterLocalFqdn,+ recipeHasBackgroundAccessClient,+} from './reconciler/resourceBuilder'import { SecretReverseIndex } from './reconciler/secretReverseIndex'import { SecretWatcher } from './reconciler/secretWatcher'import {@@ -52,6 +55,11 @@ const MIN_RUNTIME_CREDENTIAL_REFRESH_INTERVAL_MS = 5_000const MAX_RUNTIME_CREDENTIAL_REFRESH_INTERVAL_MS = 30_000const WORKLOAD_STATUS_REFRESH_INTERVAL_MS = 30_000const WORKFLOW_RUN_ID_LABEL = 'clerum.io/workflow-run-id'+// Bound the fan-out of the periodic external-egress requeue: the per-recipe+// eventQueue already serializes each recipe, but without a global cap a refresh+// pass over N recipes would enqueue N reconciles at once. This caps the number of+// reconciles started concurrently per pass; the rest queue and drain in order.+const EXTERNAL_EGRESS_REFRESH_MAX_CONCURRENCY = 8export interface WorkflowRecipeWatchObject {metadata: {@@ -372,6 +380,90 @@ export function workflowNeedsOwnershipBackstop(recipe: WorkflowRecipeCRD): boolereturn recipeReferencesNamedSecrets(recipe)}+/**+ * issue #299 §3.2/§5 — does this recipe declare at least one exact-host EXTERNAL+ * egress target that the WRC accumulator folds into a sliding-window policy?+ *+ * Two accumulator-driven sources qualify:+ * - `spec.ui.egress.external[]` — sandbox-ui external FQDNs (always exact-host).+ * - a NON-transport workload's `egressBindings[]` whose `dns` is an external FQDN+ * (i.e. NOT `<svc>.<ns>.svc.cluster.local`). Validation guarantees non-transport+ * workloads use exact-host egress, so any external-FQDN binding here is+ * exact-host. The UI workload's own bindings are skipped (its egress is declared+ * via `spec.ui.egress`, and the reconciler's workload loop skips it too).+ *+ * Transport-workload egress is intentionally EXCLUDED: it is delegated to HCC via+ * the McpServer CRD, not folded by this accumulator, so re-enqueueing on its+ * account would do no accumulator work.+ *+ * The predicate is pure and cheap (no DNS, no apiserver) so the refresh timer can+ * filter the cached recipe set synchronously each tick.+ */+export function recipeHasExternalExactHostEgress(recipe: WorkflowRecipeCRD): boolean {+ if (recipe.metadata.deletionTimestamp) return false+ if ((recipe.spec.ui?.egress?.external ?? []).length > 0) return true++ const uiWorkloadId = recipe.spec.ui?.workloadRef+ return (recipe.spec.workloads ?? []).some(workload => {+ if (workload.transport) return false+ if (uiWorkloadId && workload.id === uiWorkloadId) return false+ return (workload.egressBindings ?? []).some(+ binding =>+ Boolean(binding.dns) &&+ binding.port != null &&+ parseClusterLocalFqdn(binding.dns as string) === null+ )+ })+}++/**+ * issue #299 §3.2/§5 — the external-egress refresh cadence in ms.+ *+ * `clamp(refreshInterval, floor)`: never tick faster than the floor. `loadConfig`+ * already enforces `floor <= interval < overlap`, but clamping here keeps the+ * timer correct even if a caller passes an unvalidated config (tests, future+ * callers), so a sub-floor interval can never turn the timer into a busy loop.+ */+export function externalEgressRefreshIntervalMs(+ config: {+ externalEgressRefreshIntervalSeconds: number+ externalEgressRefreshFloorSeconds: number+ },+ minObservedTtlMs = Infinity+): number {+ const floorMs = config.externalEgressRefreshFloorSeconds * 1000+ const configuredMs = config.externalEgressRefreshIntervalSeconds * 1000+ // H2 (issue #299): advance the refresh to <= observed TTL/2 so a rotating+ // low-TTL host is sampled every rotation. A finite observed TTL can only make+ // the refresh FASTER than the configured interval, never slower; the floor is+ // the hard lower bound to avoid a hot-loop.+ const ttlAwareMs = Number.isFinite(minObservedTtlMs)+ ? Math.min(configuredMs, minObservedTtlMs / 2)+ : configuredMs+ return Math.max(ttlAwareMs, floorMs)+}++/**+ * Run `worker` over `items` with at most `limit` promises in flight at once.+ * Deterministic worker-pool: `limit` runners pull from a shared cursor until the+ * list drains. Used to bound the external-egress refresh fan-out.+ */+async function runWithConcurrency<T>(+ items: T[],+ limit: number,+ worker: (item: T) => Promise<void>+): Promise<void> {+ let cursor = 0+ const runnerCount = Math.min(Math.max(limit, 1), items.length)+ const runners = Array.from({ length: runnerCount }, async () => {+ while (cursor < items.length) {+ const item = items[cursor++]+ await worker(item)+ }+ })+ await Promise.all(runners)+}+export interface WorkflowRecipeProvider {getAllRecipes(): WorkflowRecipeCRD[]start(): Promise<void>@@ -423,6 +515,11 @@ export class WorkflowRecipeWatcher implements WorkflowRecipeProvider {private runtimeCredentialRefreshRunning = falseprivate workloadStatusRefreshTimer: ReturnType<typeof setInterval> | null = nullprivate workloadStatusRefreshRunning = false+ // issue #299 — periodic external-egress requeue. GitHub (and other single-A-record+ // rotators) change their resolved IP without bumping the CRD generation, so the+ // accumulator's sliding window only converges if we re-reconcile on a timer.+ private externalEgressRefreshTimer: ReturnType<typeof setTimeout> | null = null+ private externalEgressRefreshRunning = falseprivate eventQueue = new RecipeEventQueue((key, error) => {console.error(`[WR-K8s] Unhandled event failure for "${key}":`, error)})@@ -537,6 +634,7 @@ export class WorkflowRecipeWatcher implements WorkflowRecipeProvider {this.startBrokerTokenRotationLoop()this.startRuntimeCredentialRefreshLoop()this.startWorkloadStatusRefreshLoop()+ this.startExternalEgressRefreshLoop()if (this.dbRunProcessor) {await this.dbRunProcessor.start()@@ -917,6 +1015,82 @@ export class WorkflowRecipeWatcher implements WorkflowRecipeProvider {this.workloadStatusRefreshTimer.unref?.()}+ /**+ * issue #299 §3.2/§5 — start the periodic external-egress requeue.+ *+ * A recipe's exact-host external egress (`spec.ui.egress.external` or a+ * non-transport workload's external `egressBindings`) resolves to IPs that a+ * single-A-record provider (GitHub: api.github.com, ~15s TTL over+ * 140.82.112.0/20) rotates WITHOUT bumping the CRD generation. Generation-only+ * reconcile triggers therefore never re-run the accumulator, and the+ * sliding-window egress set on the NetworkPolicy stops covering the pod's next+ * resolution. This timer re-enqueues a FULL reconcile (forceReconcile — a plain+ * MODIFIED would short-circuit as status-only) for every cached recipe with such+ * egress, so the accumulator folds each fresh DNS snapshot into the window.+ *+ * Overlapping passes are impossible by construction: the next delay is armed in+ * the pass's `.finally`, so a slow pass simply pushes the next tick out rather+ * than stacking. `externalEgressRefreshRunning` is an in-flight indicator (read+ * by tests); per-recipe coalescing is handled by the eventQueue.+ */+ private startExternalEgressRefreshLoop(): void {+ if (this.externalEgressRefreshTimer) return++ // Self-rescheduling (not a fixed setInterval) so the delay can advance to+ // <= observed TTL/2 (H2, issue #299) as low-TTL hosts are seen. Rescheduling+ // AFTER each pass completes also guarantees no overlapping refreshes.+ const scheduleNext = (): void => {+ if (this.stopped) return+ const delayMs = externalEgressRefreshIntervalMs(+ this.config,+ this.reconciler.externalEgressRefreshMinTtlMs+ )+ this.externalEgressRefreshTimer = setTimeout(() => {+ this.externalEgressRefreshRunning = true+ void this.refreshExternalEgressForActiveRecipes().finally(() => {+ this.externalEgressRefreshRunning = false+ scheduleNext()+ })+ }, delayMs)+ this.externalEgressRefreshTimer.unref?.()+ }+ scheduleNext()+ }++ private async refreshExternalEgressForActiveRecipes(): Promise<void> {+ if (this.stopped) return++ const started = Date.now()+ const selected = [...this.recipes.keys()].filter(name => {+ const recipe = this.recipes.get(name)+ return recipe ? recipeHasExternalExactHostEgress(recipe) : false+ })+ if (selected.length === 0) return++ let enqueued = 0+ await runWithConcurrency(selected, EXTERNAL_EGRESS_REFRESH_MAX_CONCURRENCY, async name => {+ if (this.stopped) return+ const latest = this.recipes.get(name)+ if (!latest) return+ try {+ await this.eventQueue.enqueue(name, () =>+ // Generation is unchanged for a DNS-rotation refresh, so force the full+ // reconcile; otherwise handleRecipeEvent classifies this synthetic+ // MODIFIED as status-only and returns before the accumulator runs.+ this.handleRecipeEvent('MODIFIED', latest, { forceReconcile: true })+ )+ enqueued+++ } catch (error) {+ console.error(`[WR-K8s] External egress refresh failed for "${name}":`, error)+ }+ })++ // Counts and duration only — never the resolved FQDNs/IPs or any Secret.+ console.log(+ `[WR-K8s] External egress refresh: re-enqueued ${enqueued}/${selected.length} recipe(s) in ${Date.now() - started}ms`+ )+ }+private async refreshWorkloadStatusesForSteadyRecipes(): Promise<void> {if (this.stopped) return@@ -1015,6 +1189,10 @@ export class WorkflowRecipeWatcher implements WorkflowRecipeProvider {clearInterval(this.workloadStatusRefreshTimer)this.workloadStatusRefreshTimer = null}+ if (this.externalEgressRefreshTimer) {+ clearTimeout(this.externalEgressRefreshTimer)+ this.externalEgressRefreshTimer = null+ }if (this.watchRequest) {console.log('[WR-K8s] Stopping watch')this.watchRequest.abort()diff --git a/workflow-recipes/src/reconciler/externalEgressAccumulator.test.ts b/workflow-recipes/src/reconciler/externalEgressAccumulator.test.tsnew file mode 100644index 000000000..1b915c92b--- /dev/null+++ b/workflow-recipes/src/reconciler/externalEgressAccumulator.test.ts@@ -0,0 +1,294 @@+import { describe, expect, it } from 'vitest'+import {+ RESOLVED_AT_ANNOTATION,+ STATE_ANNOTATION,+ TARGETS_ANNOTATION,+ emptyState,+ reconcileEgressState,+ serializeState,+} from '@clerum/network-policy-core'+import { accumulateExternalEgress } from './externalEgressAccumulator'+import type { ResolveResult } from './fqdnResolver'++const CONFIG = { overlapMs: 300_000, maxEntries: 128 }+const NOW = 1_000_000_000++function okResolve(+ entries: Array<{ fqdn: string; port: number; ip: string; ttlSeconds: number }>+): ResolveResult {+ return {+ resolved: entries.map(e => ({+ cidr: `${e.ip}/32`,+ port: e.port,+ reason: undefined,+ source: { kind: 'fqdn' as const, fqdn: e.fqdn },+ ttlSeconds: e.ttlSeconds,+ })),+ failures: [],+ }+}++// Build previous-round annotations by folding one OK round into empty state.+function previousAnnotations(+ entries: Array<{ fqdn: string; port: number; ip: string; ttlSeconds: number }>,+ at: number+): Record<string, string> {+ const out = reconcileEgressState(+ emptyState(),+ entries.map(e => ({+ fqdn: e.fqdn,+ port: e.port,+ kind: 'ok' as const,+ ips: [e.ip],+ ttlMs: e.ttlSeconds * 1000,+ })),+ at,+ CONFIG+ )+ return serializeState(out.state)+}++describe('accumulateExternalEgress — observation building & mapping', () => {+ it('accumulates OK resolutions into effective /32 entries and stamps annotations', () => {+ const out = accumulateExternalEgress({+ externals: [+ { fqdn: 'api.github.com', port: 443 },+ { fqdn: 'api.anthropic.com', port: 443 },+ ],+ resolveResult: okResolve([+ { fqdn: 'api.github.com', port: 443, ip: '140.82.112.3', ttlSeconds: 15 },+ { fqdn: 'api.anthropic.com', port: 443, ip: '160.79.104.10', ttlSeconds: 300 },+ ]),+ previousAnnotations: undefined,+ now: NOW,+ config: CONFIG,+ })++ expect(out.changed).toBe(true)+ expect(out.resolved.map(r => r.cidr).sort()).toEqual(['140.82.112.3/32', '160.79.104.10/32'])+ expect(out.resolved.every(r => r.source.kind === 'fqdn')).toBe(true)+ expect(out.annotations[STATE_ANNOTATION]).toBeTruthy()+ expect(out.annotations[TARGETS_ANNOTATION]).toContain('api.github.com=140.82.112.3/32')+ expect(out.annotations[RESOLVED_AT_ANNOTATION]).toBe(new Date(NOW).toISOString())+ expect(out.frozenFqdns).toEqual([])+ expect(out.overCap).toBe(false)+ })++ it('maps entry expiry off the fqdn TTL + overlap (github 15s window)', () => {+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'api.github.com', port: 443 }],+ resolveResult: okResolve([+ { fqdn: 'api.github.com', port: 443, ip: '140.82.112.3', ttlSeconds: 15 },+ ]),+ previousAnnotations: undefined,+ now: NOW,+ config: CONFIG,+ })+ expect(out.entries).toHaveLength(1)+ expect(out.entries[0].expiresAt).toBe(NOW + 15_000 + CONFIG.overlapMs)+ })+})++describe('accumulateExternalEgress — H1 fail-static under transient DNS failure', () => {+ it('FREEZES a previously-authorized fqdn whose resolution went transient', () => {+ const prev = previousAnnotations(+ [{ fqdn: 'api.github.com', port: 443, ip: '140.82.112.3', ttlSeconds: 15 }],+ NOW+ )+ const resolveResult: ResolveResult = {+ resolved: [],+ failures: [{ fqdn: 'api.github.com', error: 'ESERVFAIL', retryable: true }],+ }+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'api.github.com', port: 443 }],+ resolveResult,+ previousAnnotations: prev,+ // well past TTL + overlap: a naive window would have expired it+ now: NOW + 15_000 + CONFIG.overlapMs + 60_000,+ config: CONFIG,+ })+ // The IP is CONSERVED (frozen), not pruned.+ expect(out.resolved.map(r => r.cidr)).toEqual(['140.82.112.3/32'])+ expect(out.frozenFqdns).toContain('api.github.com')+ })+})++describe('accumulateExternalEgress — M1 renewalDue (audit #299)', () => {+ it('flags renewalDue (set unchanged) when the persisted window is within overlap/2 of lapsing', () => {+ // expiresAt = NOW + 15000 + 300000; overlap/2 = 150000. now past NOW+165000 → due.+ const prev = previousAnnotations(+ [{ fqdn: 'api.github.com', port: 443, ip: '140.82.112.3', ttlSeconds: 15 }],+ NOW+ )+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'api.github.com', port: 443 }],+ resolveResult: okResolve([+ { fqdn: 'api.github.com', port: 443, ip: '140.82.112.3', ttlSeconds: 15 },+ ]),+ previousAnnotations: prev,+ now: NOW + 200_000,+ config: CONFIG,+ })+ expect(out.changed).toBe(false)+ expect(out.renewalDue).toBe(true)+ })++ it('does NOT flag renewalDue right after a write (window fresh)', () => {+ const prev = previousAnnotations(+ [{ fqdn: 'api.github.com', port: 443, ip: '140.82.112.3', ttlSeconds: 15 }],+ NOW+ )+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'api.github.com', port: 443 }],+ resolveResult: okResolve([+ { fqdn: 'api.github.com', port: 443, ip: '140.82.112.3', ttlSeconds: 15 },+ ]),+ previousAnnotations: prev,+ now: NOW + 1000,+ config: CONFIG,+ })+ expect(out.changed).toBe(false)+ expect(out.renewalDue).toBe(false)+ })+})++describe('accumulateExternalEgress — F1 revocation of a removed fqdn (audit #299)', () => {+ it('REVOKES a fqdn removed from the declared externals, keeping the still-declared one', () => {+ // Prior state accumulated TWO fqdns.+ const prev = previousAnnotations(+ [+ { fqdn: 'api.github.com', port: 443, ip: '140.82.112.3', ttlSeconds: 15 },+ { fqdn: 'api.anthropic.com', port: 443, ip: '160.79.104.10', ttlSeconds: 300 },+ ],+ NOW+ )+ // This round the recipe declares ONLY anthropic (github was removed from spec).+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'api.anthropic.com', port: 443 }],+ resolveResult: okResolve([+ { fqdn: 'api.anthropic.com', port: 443, ip: '160.79.104.10', ttlSeconds: 300 },+ ]),+ previousAnnotations: prev,+ now: NOW + 1000, // well within the github window: a naive freeze would keep it+ config: CONFIG,+ })+ // The removed fqdn's IP is GONE (revoked immediately), not frozen forever.+ expect(out.resolved.map(r => r.cidr)).toEqual(['160.79.104.10/32'])+ expect(out.frozenFqdns).toEqual([])+ })++ it('does NOT confuse a transient failure (declared, keep) with a removal (undeclared, drop)', () => {+ const prev = previousAnnotations(+ [+ { fqdn: 'api.github.com', port: 443, ip: '140.82.112.3', ttlSeconds: 15 },+ { fqdn: 'api.anthropic.com', port: 443, ip: '160.79.104.10', ttlSeconds: 300 },+ ],+ NOW+ )+ // github is STILL declared but its DNS transiently fails → freeze (keep).+ // anthropic is REMOVED from the declared set → revoke (drop).+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'api.github.com', port: 443 }],+ resolveResult: {+ resolved: [],+ failures: [{ fqdn: 'api.github.com', error: 'ESERVFAIL', retryable: true }],+ },+ previousAnnotations: prev,+ now: NOW + 1000,+ config: CONFIG,+ })+ expect(out.resolved.map(r => r.cidr)).toEqual(['140.82.112.3/32'])+ expect(out.frozenFqdns).toEqual(['api.github.com'])+ })+})++describe('accumulateExternalEgress — permanent failure expires normally', () => {+ it('does NOT freeze a fqdn that failed permanently (no records)', () => {+ const prev = previousAnnotations(+ [{ fqdn: 'gone.example.com', port: 443, ip: '93.184.216.10', ttlSeconds: 30 }],+ NOW+ )+ const resolveResult: ResolveResult = {+ resolved: [],+ failures: [{ fqdn: 'gone.example.com', error: 'no A or AAAA records', retryable: false }],+ }+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'gone.example.com', port: 443 }],+ resolveResult,+ previousAnnotations: prev,+ now: NOW + 30_000 + CONFIG.overlapMs + 1,+ config: CONFIG,+ })+ // Past its window with an OK-eligible (permanent) round → it expires.+ expect(out.resolved).toEqual([])+ expect(out.frozenFqdns).not.toContain('gone.example.com')+ })+})++describe('accumulateExternalEgress — H4 no-op', () => {+ it('reports changed=false when the effective set is unchanged (only timestamps renew)', () => {+ const prev = previousAnnotations(+ [{ fqdn: 'api.anthropic.com', port: 443, ip: '160.79.104.10', ttlSeconds: 300 }],+ NOW+ )+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'api.anthropic.com', port: 443 }],+ resolveResult: okResolve([+ { fqdn: 'api.anthropic.com', port: 443, ip: '160.79.104.10', ttlSeconds: 300 },+ ]),+ previousAnnotations: prev,+ now: NOW + 10_000,+ config: CONFIG,+ })+ expect(out.changed).toBe(false)+ expect(out.resolved.map(r => r.cidr)).toEqual(['160.79.104.10/32'])+ })+})++describe('accumulateExternalEgress — H5 rehydration', () => {+ it('rehydrates previous entries and MERGES a newly observed IP (accumulation across restart)', () => {+ const prev = previousAnnotations(+ [{ fqdn: 'api.github.com', port: 443, ip: '140.82.112.3', ttlSeconds: 15 }],+ NOW+ )+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'api.github.com', port: 443 }],+ resolveResult: okResolve([+ // GitHub rotated to a new single IP; the old one is still within window+ { fqdn: 'api.github.com', port: 443, ip: '140.82.112.4', ttlSeconds: 15 },+ ]),+ previousAnnotations: prev,+ now: NOW + 5_000,+ config: CONFIG,+ })+ expect(out.resolved.map(r => r.cidr).sort()).toEqual(['140.82.112.3/32', '140.82.112.4/32'])+ expect(out.changed).toBe(true)+ })+})++describe('accumulateExternalEgress — H3 eviction / overCap', () => {+ it('evicts to the cap NEVER rejects, and always keeps the freshly observed IP', () => {+ // Seed a previous set at the cap with old (soonest-to-expire) IPs.+ const seed = Array.from({ length: 4 }, (_, i) => ({+ fqdn: 'pool.example.com',+ port: 443,+ ip: `10.0.0.${i + 1}`,+ ttlSeconds: 10,+ }))+ const prev = previousAnnotations(seed, NOW)+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'pool.example.com', port: 443 }],+ resolveResult: okResolve([+ { fqdn: 'pool.example.com', port: 443, ip: '10.0.0.99', ttlSeconds: 10 },+ ]),+ previousAnnotations: prev,+ now: NOW + 1_000,+ config: { overlapMs: 300_000, maxEntries: 4 },+ })+ expect(out.overCap).toBe(true)+ expect(out.evicted.length).toBeGreaterThan(0)+ expect(out.entries).toHaveLength(4)+ // The freshly observed IP must survive eviction.+ expect(out.resolved.map(r => r.cidr)).toContain('10.0.0.99/32')+ })+})diff --git a/workflow-recipes/src/reconciler/externalEgressAccumulator.ts b/workflow-recipes/src/reconciler/externalEgressAccumulator.tsnew file mode 100644index 000000000..c3b16d50b--- /dev/null+++ b/workflow-recipes/src/reconciler/externalEgressAccumulator.ts@@ -0,0 +1,168 @@+/**+ * externalEgressAccumulator — the WRC-side adapter between the DNS resolver+ * (`fqdnResolver.ts`) and the pure sliding-window core+ * (`@clerum/network-policy-core`), for issue #299.+ *+ * The resolver produces a single-generation DNS snapshot (one /32 per A record+ * of this reconcile). A provider that serves ONE rotating A record (GitHub's+ * api.github.com, TTL ~15s over 140.82.112.0/20) makes that snapshot pin one IP+ * of ~16, so the pod's next resolution lands on an un-pinned IP and the+ * NetworkPolicy drops it. This adapter folds each snapshot into the accumulated+ * set persisted on the policy's annotations, so the effective egress set is the+ * union of recently-live IPs rather than a single photo.+ *+ * It is a PURE function (clock injected as `now`, previous state read from the+ * caller-supplied annotations), so it is unit-testable without Kubernetes or+ * DNS. All Kubernetes I/O (reading the existing NetworkPolicy, writing it) stays+ * in the reconciler.+ *+ * Guarantees delegated to the core (see plan §0/§3/§5):+ * - H1 fail-static: a `transient` resolver failure FREEZES that FQDN's entries+ * (never prunes them while DNS is failing) and surfaces it in `frozenFqdns`.+ * - H3 eviction: on overflow, evict soonest-to-expire, NEVER reject/truncate.+ * - H4 no-op: `changed` is over (ip,port,protocol) only — a timestamp-only+ * refresh writes nothing.+ * - H5 rehydration: previous state is parsed from the policy's annotations; an+ * unparseable/legacy format is NOT collapsed to an empty set.+ */+import {+ type EgressCoreConfig,+ type EgressEntry,+ type Observation,+ RESOLVED_AT_ANNOTATION,+ emptyState,+ parseState,+ reconcileEgressState,+ serializeState,+} from '@clerum/network-policy-core'+import type { ResolveResult } from './fqdnResolver'+import type { ResolvedExternalEgressInput } from './resourceBuilder'++/** A declared external egress target (fqdn + port) for one policy. */+export interface DeclaredExternal {+ fqdn: string+ port: number+}++export interface AccumulateInput {+ /** The `external[]`/`egressBindings[]` targets declared on the recipe. */+ externals: DeclaredExternal[]+ /** This reconcile's resolver output (with per-fqdn TTLs). */+ resolveResult: ResolveResult+ /** Annotations of the existing NetworkPolicy, or undefined on bootstrap. */+ previousAnnotations: Record<string, string> | undefined+ /** Injected clock (epoch ms). */+ now: number+ config: EgressCoreConfig+}++export interface AccumulateOutput {+ /** The effective live entries (the accumulated set) to render as ipBlocks. */+ entries: EgressEntry[]+ /** `entries` mapped to the builder's ipBlock input shape. */+ resolved: ResolvedExternalEgressInput[]+ /** Annotations to stamp on the policy: serialized state + resolved-at. */+ annotations: Record<string, string>+ /** True iff the (ip,port,protocol) set changed vs the previous state. */+ changed: boolean+ /** True iff the persisted window is aging and must be re-persisted (audit M1). */+ renewalDue: boolean+ /** Entries removed by the cap this round (for a Warning event / metric). */+ evicted: EgressEntry[]+ /** True iff the cap was hit and eviction happened. */+ overCap: boolean+ /** FQDNs frozen this round because their observation was transient. */+ frozenFqdns: string[]+}++/**+ * Turn the declared externals + this round's resolver output into normalized+ * observations for the core. Iterating the DECLARED list (not the resolver+ * output) is deliberate: a name that resolved OK-but-empty produces no resolved+ * entry and no failure, yet the core still needs an `ok` observation with an+ * empty ip set so its stale entries can expire.+ */+function buildObservations(+ externals: DeclaredExternal[],+ resolveResult: ResolveResult+): Observation[] {+ // A failing fqdn yields one failure per declared entry; retryability is+ // consistent per fqdn (one lookup), so index by fqdn.+ const retryableByFqdn = new Map<string, boolean>()+ for (const f of resolveResult.failures) {+ // If a fqdn ever has a non-retryable failure this round, it is permanent.+ const prior = retryableByFqdn.get(f.fqdn)+ retryableByFqdn.set(f.fqdn, prior === false ? false : f.retryable)+ }++ // Group resolved /32s back to their fqdn: ip set + the fqdn's TTL (ms).+ const okByFqdn = new Map<string, { ips: string[]; ttlMs: number }>()+ for (const r of resolveResult.resolved) {+ const fqdn = r.source.fqdn+ const ip = r.cidr.replace(/\/\d+$/, '')+ const existing = okByFqdn.get(fqdn)+ if (existing) {+ existing.ips.push(ip)+ } else {+ okByFqdn.set(fqdn, { ips: [ip], ttlMs: r.ttlSeconds * 1000 })+ }+ }++ const observations: Observation[] = []+ for (const ext of externals) {+ const failure = retryableByFqdn.get(ext.fqdn)+ if (failure !== undefined) {+ observations.push({+ fqdn: ext.fqdn,+ port: ext.port,+ kind: failure ? 'transient' : 'permanent',+ })+ continue+ }+ const ok = okByFqdn.get(ext.fqdn)+ observations.push({+ fqdn: ext.fqdn,+ port: ext.port,+ kind: 'ok',+ ips: ok?.ips ?? [],+ ttlMs: ok?.ttlMs ?? 0,+ })+ }+ return observations+}++/**+ * Fold this reconcile's DNS snapshot into the accumulated egress set persisted+ * on the policy's annotations, applying the sliding window, fail-static expiry,+ * and eviction from `@clerum/network-policy-core`.+ */+export function accumulateExternalEgress(input: AccumulateInput): AccumulateOutput {+ const { externals, resolveResult, previousAnnotations, now, config } = input++ const previous = previousAnnotations ? parseState(previousAnnotations, now, config) : emptyState()++ const observations = buildObservations(externals, resolveResult)+ const out = reconcileEgressState(previous, observations, now, config)++ const resolved: ResolvedExternalEgressInput[] = out.entries.map(entry => ({+ cidr: `${entry.ip}/32`,+ port: entry.port,+ source: { kind: 'fqdn', fqdn: entry.fqdn },+ }))++ const annotations: Record<string, string> = {+ ...serializeState(out.state),+ [RESOLVED_AT_ANNOTATION]: new Date(now).toISOString(),+ }++ return {+ entries: out.entries,+ resolved,+ annotations,+ changed: out.changed,+ renewalDue: out.renewalDue,+ evicted: out.evicted,+ overCap: out.overCap,+ frozenFqdns: out.frozenFqdns,+ }+}diff --git a/workflow-recipes/src/reconciler/fqdnResolver.test.ts b/workflow-recipes/src/reconciler/fqdnResolver.test.tsindex e2e798f64..2b6bef92f 100644--- a/workflow-recipes/src/reconciler/fqdnResolver.test.ts+++ b/workflow-recipes/src/reconciler/fqdnResolver.test.ts@@ -32,6 +32,7 @@ describe('resolveExternalEgress', () => {kind: 'ok',ipv4: ['93.184.216.10', '93.184.216.11'],ipv6: [],+ ttlSeconds: 300,},})const result = await resolveExternalEgress(@@ -44,12 +45,14 @@ describe('resolveExternalEgress', () => {port: 443,reason: 'Charge cards',source: { kind: 'fqdn', fqdn: 'api.stripe.com' },+ ttlSeconds: 300,},{cidr: '93.184.216.11/32',port: 443,reason: 'Charge cards',source: { kind: 'fqdn', fqdn: 'api.stripe.com' },+ ttlSeconds: 300,},])})@@ -63,6 +66,7 @@ describe('resolveExternalEgress', () => {kind: 'ok',ipv4: ['160.79.104.10'],ipv6: ['2607:6bc0::10'],+ ttlSeconds: 300,},})const result = await resolveExternalEgress([{ fqdn: 'api.anthropic.com', port: 443 }], lookup)@@ -72,6 +76,7 @@ describe('resolveExternalEgress', () => {port: 443,reason: undefined,source: { kind: 'fqdn', fqdn: 'api.anthropic.com' },+ ttlSeconds: 300,},])expect(result.failures).toEqual([])@@ -79,8 +84,8 @@ describe('resolveExternalEgress', () => {it('preserves fqdn ordering across multiple entries', async () => {const lookup = fakeLookup({- 'api.stripe.com': { kind: 'ok', ipv4: ['93.184.216.10'], ipv6: [] },- 'ingest.sentry.io': { kind: 'ok', ipv4: ['93.184.216.20'], ipv6: [] },+ 'api.stripe.com': { kind: 'ok', ipv4: ['93.184.216.10'], ipv6: [], ttlSeconds: 300 },+ 'ingest.sentry.io': { kind: 'ok', ipv4: ['93.184.216.20'], ipv6: [], ttlSeconds: 300 },})const result = await resolveExternalEgress([@@ -94,7 +99,7 @@ describe('resolveExternalEgress', () => {it('records a failure when fqdn resolution errors and continues with the rest', async () => {const lookup = fakeLookup({- 'good.example.com': { kind: 'ok', ipv4: ['93.184.216.5'], ipv6: [] },+ 'good.example.com': { kind: 'ok', ipv4: ['93.184.216.5'], ipv6: [], ttlSeconds: 300 },'bad.example.com': { kind: 'error', error: 'NXDOMAIN' },})const result = await resolveExternalEgress(@@ -112,7 +117,7 @@ describe('resolveExternalEgress', () => {it('treats an empty A-record set as no expansion (no entries, no failure)', async () => {const lookup = fakeLookup({- 'empty.example.com': { kind: 'ok', ipv4: [], ipv6: [] },+ 'empty.example.com': { kind: 'ok', ipv4: [], ipv6: [], ttlSeconds: 0 },})const result = await resolveExternalEgress([{ fqdn: 'empty.example.com', port: 443 }], lookup)expect(result.resolved).toEqual([])@@ -125,6 +130,7 @@ describe('resolveExternalEgress', () => {kind: 'ok',ipv4: ['93.184.216.34', '169.254.169.254'],ipv6: [],+ ttlSeconds: 300,},})const result = await resolveExternalEgress([{ fqdn: 'mixed.example.com', port: 443 }], lookup)@@ -163,10 +169,10 @@ describe('defaultFqdnLookup classification', () => {})it('returns ok with A records even when AAAA has none', async () => {- resolve4Mock.mockResolvedValue(['160.79.104.10'])+ resolve4Mock.mockResolvedValue([{ address: '160.79.104.10', ttl: 300 }])resolve6Mock.mockRejectedValue(dnsError('ENODATA'))const result = await defaultFqdnLookup('api.anthropic.com')- expect(result).toEqual({ kind: 'ok', ipv4: ['160.79.104.10'], ipv6: [] })+ expect(result).toEqual({ kind: 'ok', ipv4: ['160.79.104.10'], ipv6: [], ttlSeconds: 300 })})it('classifies SERVFAIL as a retryable error and surfaces the code', async () => {@@ -221,3 +227,63 @@ describe('defaultFqdnLookup classification', () => {expect(result).toMatchObject({ kind: 'error', retryable: true })})})++// ─── issue #299: TTL propagation (feeds the sliding-window accumulator) ─────+describe('defaultFqdnLookup TTL propagation (issue #299)', () => {+ afterEach(() => {+ resolve4Mock.mockReset()+ resolve6Mock.mockReset()+ })++ it('requests per-record TTLs via resolve4({ ttl: true })', async () => {+ resolve4Mock.mockResolvedValue([{ address: '140.82.112.3', ttl: 18 }])+ resolve6Mock.mockRejectedValue(dnsError('ENODATA'))+ await defaultFqdnLookup('api.github.com')+ expect(resolve4Mock).toHaveBeenCalledWith('api.github.com', { ttl: true })+ })++ it('reports the MINIMUM TTL across A records (the whole fqdn window)', async () => {+ resolve4Mock.mockResolvedValue([+ { address: '140.82.112.3', ttl: 18 },+ { address: '140.82.112.4', ttl: 12 },+ ])+ resolve6Mock.mockRejectedValue(dnsError('ENODATA'))+ const result = await defaultFqdnLookup('api.github.com')+ expect(result).toEqual({+ kind: 'ok',+ ipv4: ['140.82.112.3', '140.82.112.4'],+ ipv6: [],+ ttlSeconds: 12,+ })+ })+})++describe('resolveExternalEgress TTL propagation (issue #299)', () => {+ it('stamps the fqdn TTL onto every resolved /32 entry', async () => {+ const lookup = fakeLookup({+ 'api.github.com': {+ kind: 'ok',+ ipv4: ['140.82.112.3', '140.82.112.4'],+ ipv6: [],+ ttlSeconds: 15,+ },+ })+ const result = await resolveExternalEgress([{ fqdn: 'api.github.com', port: 443 }], lookup)+ expect(result.resolved).toEqual([+ {+ cidr: '140.82.112.3/32',+ port: 443,+ reason: undefined,+ source: { kind: 'fqdn', fqdn: 'api.github.com' },+ ttlSeconds: 15,+ },+ {+ cidr: '140.82.112.4/32',+ port: 443,+ reason: undefined,+ source: { kind: 'fqdn', fqdn: 'api.github.com' },+ ttlSeconds: 15,+ },+ ])+ })+})diff --git a/workflow-recipes/src/reconciler/fqdnResolver.ts b/workflow-recipes/src/reconciler/fqdnResolver.tsindex 6e98c0c1c..7f74ddb8b 100644--- a/workflow-recipes/src/reconciler/fqdnResolver.ts+++ b/workflow-recipes/src/reconciler/fqdnResolver.ts@@ -1,4 +1,6 @@+import type { RecordWithTtl } from 'node:dns'import { resolve4, resolve6 } from 'node:dns/promises'+import { classifyDnsError } from '@clerum/network-policy-core'import type { SandboxUiExternalEgress } from '../types'const BLOCKED_EGRESS_CIDRS = [@@ -71,10 +73,21 @@ export interface ResolvedExternalEgress {port: numberreason?: stringsource: { kind: 'fqdn'; fqdn: string }+ /**+ * TTL (seconds) of the FQDN this /32 was resolved from — the MINIMUM TTL+ * across the FQDN's A records, i.e. the refresh window for the whole name+ * (issue #299). The sliding-window accumulator uses this to compute each+ * entry's expiry = now + ttl + overlap. All /32s of one FQDN share it.+ */+ ttlSeconds: number}export type FqdnLookupResult =- | { kind: 'ok'; ipv4: string[]; ipv6: string[] }+ // `ttlSeconds` is the MINIMUM TTL (seconds) across the resolved A records —+ // the binding window for the whole FQDN, consumed by the egress accumulator+ // (issue #299). It is 0 when only AAAA resolved (A-less), since no /32 is+ // emitted for an IPv4-only enforcement target in that case.+ | { kind: 'ok'; ipv4: string[]; ipv6: string[]; ttlSeconds: number }// `retryable` distinguishes a transient resolver failure (SERVFAIL, timeout,// unreachable upstream) — worth retrying on a later reconcile — from a// permanent one (the name genuinely has no A/AAAA records). Absent ⇒ permanent.@@ -83,33 +96,13 @@ export type FqdnLookupResult =export type FqdnLookup = (host: string) => Promise<FqdnLookupResult>/**- * c-ares / system error codes that mean the resolver or its upstream was- * unavailable at query time, NOT that the name has no records. A reconcile that- * hits one of these should be retried rather than bricking the recipe — these- * map to `retryable: true`. Stable DNS answers (ENODATA, ENOTFOUND/NXDOMAIN, an- * empty answer) fail closed permanently.+ * Transient-vs-permanent DNS classification is centralized in+ * `@clerum/network-policy-core` (`classifyDnsError`) so WRC and HCC agree on what+ * a transient failure is — a single source of truth avoids drift between the two+ * controllers' fail-static behavior (issue #299 audit F6). c-ares / system codes+ * meaning "resolver/upstream temporarily unavailable" map to `retryable: true`;+ * stable answers (ENODATA, ENOTFOUND/NXDOMAIN, empty) fail closed permanently.*/-const TRANSIENT_DNS_CODES = new Set([- 'EAI_AGAIN', // system resolver temporary failure- 'ESERVFAIL', // upstream returned SERVFAIL- 'EFORMERR', // upstream/protocol format error for this query- 'ENOTIMP', // upstream does not implement the query- 'EREFUSED', // query refused (upstream policy / overload)- 'ETIMEOUT', // c-ares query timeout- 'ETIMEDOUT', // system-level timeout- 'ECONNREFUSED', // nameserver unreachable- 'ECONNRESET',- 'ENETUNREACH',- 'ECANCELLED', // query cancelled (e.g. resolver shutting down)- 'EBADRESP', // malformed reply from upstream- 'EOF', // resolver connection closed- 'EFILE', // resolver config/file problem- 'ENOMEM', // resolver allocation failure- 'EDESTRUCTION', // channel destroyed while query was pending- 'ENOTINITIALIZED',- 'ELOADIPHLPAPI',- 'EADDRGETNETWORKPARAMS',-])/*** Default FQDN lookup using node:dns/promises. Returns ipv4 and ipv6 record@@ -125,22 +118,40 @@ const TRANSIENT_DNS_CODES = new Set([* "no A or AAAA records".*/export const defaultFqdnLookup: FqdnLookup = async host => {- const settle = (p: Promise<string[]>) =>+ // A records are requested WITH per-record TTLs (`{ ttl: true }`) so the+ // accumulator can size the sliding window off the real DNS TTL (issue #299).+ // AAAA is resolved without TTLs: /128 blocks are dropped (IPv4-only targets),+ // so their TTL would be inert.+ const settleV4 = (p: Promise<RecordWithTtl[]>) =>+ p.then(+ records => ({ records }) as { records: RecordWithTtl[] },+ (err: NodeJS.ErrnoException) => ({ err }) as { err: NodeJS.ErrnoException }+ )+ const settleV6 = (p: Promise<string[]>) =>p.then(addrs => ({ addrs }) as { addrs: string[] },(err: NodeJS.ErrnoException) => ({ err }) as { err: NodeJS.ErrnoException })- const [v4, v6] = await Promise.all([settle(resolve4(host)), settle(resolve6(host))])+ const [v4, v6] = await Promise.all([+ settleV4(resolve4(host, { ttl: true })),+ settleV6(resolve6(host)),+ ])- const ipv4 = 'addrs' in v4 ? v4.addrs : []+ const v4Records = 'records' in v4 ? v4.records : []+ const ipv4 = v4Records.map(r => r.address)const ipv6 = 'addrs' in v6 ? v6.addrs : []if (ipv4.length > 0 || ipv6.length > 0) {- return { kind: 'ok', ipv4, ipv6 }+ // Minimum TTL across the A records = the window for the whole FQDN. 0 when+ // A-less (AAAA-only), where no /32 is emitted anyway.+ const ttlSeconds = v4Records.length > 0 ? Math.min(...v4Records.map(r => r.ttl)) : 0+ return { kind: 'ok', ipv4, ipv6, ttlSeconds }}const codes = ['err' in v4 ? v4.err.code : undefined, 'err' in v6 ? v6.err.code : undefined]- const transientCode = codes.find(code => code !== undefined && TRANSIENT_DNS_CODES.has(code))+ const transientCode = codes.find(+ code => code !== undefined && classifyDnsError(code) === 'transient'+ )if (transientCode) {return {kind: 'error',@@ -211,6 +222,7 @@ export async function resolveExternalEgress(port: entry.port,reason: entry.reason,source: { kind: 'fqdn', fqdn: entry.fqdn },+ ttlSeconds: result.ttlSeconds,})}}diff --git a/workflow-recipes/src/reconciler/generatedNetworkPolicyHardening.test.ts b/workflow-recipes/src/reconciler/generatedNetworkPolicyHardening.test.tsindex ed27c6c16..18ed2aeb1 100644--- a/workflow-recipes/src/reconciler/generatedNetworkPolicyHardening.test.ts+++ b/workflow-recipes/src/reconciler/generatedNetworkPolicyHardening.test.ts@@ -114,6 +114,7 @@ describe('generated WRC NetworkPolicy hardening', () => {cidr: '93.184.216.10/32',port: 443,source: { kind: 'fqdn', fqdn: 'api.stripe.com' },+ ttlSeconds: 300,},]diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.tsindex c8ae73600..cad439386 100644--- a/workflow-recipes/src/reconciler/reconciler.test.ts+++ b/workflow-recipes/src/reconciler/reconciler.test.ts@@ -2316,7 +2316,7 @@ describe('WorkflowRecipeReconciler', () => {},})const reconcilerWithLookup = new WorkflowRecipeReconciler(new k8s.KubeConfig(), undefined, {- fqdnLookup: async () => ({ kind: 'ok', ipv4: ['93.184.216.10'], ipv6: [] }),+ fqdnLookup: async () => ({ kind: 'ok', ipv4: ['93.184.216.10'], ipv6: [], ttlSeconds: 300 }),})const result = await reconcilerWithLookup.reconcile(recipe)@@ -2355,7 +2355,12 @@ describe('WorkflowRecipeReconciler', () => {networkPolicyEnforcementConfirmed: false,},{- fqdnLookup: async () => ({ kind: 'ok', ipv4: ['93.184.216.10'], ipv6: [] }),+ fqdnLookup: async () => ({+ kind: 'ok',+ ipv4: ['93.184.216.10'],+ ipv6: [],+ ttlSeconds: 300,+ }),})@@ -2389,7 +2394,12 @@ describe('WorkflowRecipeReconciler', () => {},})const reconcilerWithLookup = new WorkflowRecipeReconciler(new k8s.KubeConfig(), undefined, {- fqdnLookup: async () => ({ kind: 'ok', ipv4: ['169.254.169.254'], ipv6: [] }),+ fqdnLookup: async () => ({+ kind: 'ok',+ ipv4: ['169.254.169.254'],+ ipv6: [],+ ttlSeconds: 300,+ }),})const result = await reconcilerWithLookup.reconcile(recipe)@@ -3818,7 +3828,7 @@ describe('WorkflowRecipeReconciler', () => {})const kc = new k8s.KubeConfig()const reconcilerWithLookup = new WorkflowRecipeReconciler(kc, undefined, {- fqdnLookup: async () => ({ kind: 'ok', ipv4: ['93.184.216.10'], ipv6: [] }),+ fqdnLookup: async () => ({ kind: 'ok', ipv4: ['93.184.216.10'], ipv6: [], ttlSeconds: 300 }),})await reconcilerWithLookup.reconcile(recipe)expect(mockNetworkingApi.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)@@ -3852,7 +3862,12 @@ describe('WorkflowRecipeReconciler', () => {networkPolicyEnforcementConfirmed: false,},{- fqdnLookup: async () => ({ kind: 'ok', ipv4: ['93.184.216.10'], ipv6: [] }),+ fqdnLookup: async () => ({+ kind: 'ok',+ ipv4: ['93.184.216.10'],+ ipv6: [],+ ttlSeconds: 300,+ }),})@@ -3885,7 +3900,12 @@ describe('WorkflowRecipeReconciler', () => {})const kc = new k8s.KubeConfig()const reconcilerWithLookup = new WorkflowRecipeReconciler(kc, undefined, {- fqdnLookup: async () => ({ kind: 'ok', ipv4: ['169.254.169.254'], ipv6: [] }),+ fqdnLookup: async () => ({+ kind: 'ok',+ ipv4: ['169.254.169.254'],+ ipv6: [],+ ttlSeconds: 300,+ }),})const result = await reconcilerWithLookup.reconcile(recipe)@@ -3911,7 +3931,12 @@ describe('WorkflowRecipeReconciler', () => {})const kc = new k8s.KubeConfig()const reconcilerWithLookup = new WorkflowRecipeReconciler(kc, undefined, {- fqdnLookup: async () => ({ kind: 'ok', ipv4: ['169.254.169.254'], ipv6: [] }),+ fqdnLookup: async () => ({+ kind: 'ok',+ ipv4: ['169.254.169.254'],+ ipv6: [],+ ttlSeconds: 300,+ }),})const workflowReconcile = vi.fn().mockResolvedValue({phase: 'deploying',@@ -9637,7 +9662,12 @@ describe('WorkflowRecipeReconciler', () => {vi.spyOn(console, 'warn').mockImplementation(() => {})const kc = new k8s.KubeConfig()const r = new WorkflowRecipeReconciler(kc, undefined, {- fqdnLookup: async () => ({ kind: 'ok', ipv4: ['93.184.216.34'], ipv6: [] }),+ fqdnLookup: async () => ({+ kind: 'ok',+ ipv4: ['93.184.216.34'],+ ipv6: [],+ ttlSeconds: 300,+ }),})mockNetworkingApi.createNamespacedNetworkPolicy.mockRejectedValueOnce(Object.assign(diff --git a/workflow-recipes/src/reconciler/resourceBuilder.test.ts b/workflow-recipes/src/reconciler/resourceBuilder.test.tsindex cf65c6dea..a0160891b 100644--- a/workflow-recipes/src/reconciler/resourceBuilder.test.ts+++ b/workflow-recipes/src/reconciler/resourceBuilder.test.ts@@ -1973,6 +1973,43 @@ describe('buildUiEgressNetworkPolicy', () => {const policy = buildUiEgressNetworkPolicy(recipe, SBX_UI, SBX_RECIPES, [])!expect(policy.metadata?.annotations).toBeUndefined()})++ // issue #299: when the reconciler supplies the accumulated sliding-window+ // state annotations, the builder stamps THOSE (state + targets + resolved-at)+ // instead of the single-snapshot provenance, and renders ipBlocks from the+ // effective (accumulated) entries it was handed.+ it('stamps supplied accumulated state annotations and renders effective ipBlocks', () => {+ const recipe = makeRecipe()+ recipe.spec.ui = { workloadRef: 'web', port: 8080 }+ const effective = [+ {+ cidr: '140.82.112.3/32',+ port: 443,+ source: { kind: 'fqdn' as const, fqdn: 'api.github.com' },+ },+ {+ cidr: '140.82.112.4/32',+ port: 443,+ source: { kind: 'fqdn' as const, fqdn: 'api.github.com' },+ },+ ]+ const stateAnnotations = {+ 'clerum.io/egress-fqdn-state': '[{"ip":"140.82.112.3"}]',+ 'clerum.io/egress-fqdn-targets':+ 'api.github.com=140.82.112.3/32,api.github.com=140.82.112.4/32',+ 'clerum.io/egress-fqdn-resolved-at': '2026-08-08T00:00:00.000Z',+ }+ const policy = buildUiEgressNetworkPolicy(+ recipe,+ SBX_UI,+ SBX_RECIPES,+ effective,+ stateAnnotations+ )!+ expect(policy.metadata?.annotations).toEqual(stateAnnotations)+ const cidrs = policy.spec!.egress!.flatMap(r => r.to?.map(t => t.ipBlock?.cidr) ?? [])+ expect(cidrs).toEqual(['140.82.112.3/32', '140.82.112.4/32'])+ })})// ─── OAuth broker token (Path B) ────────────────────────────────────diff --git a/workflow-recipes/src/reconciler/resourceBuilder.ts b/workflow-recipes/src/reconciler/resourceBuilder.tsindex 98bb5ace7..4fd9dfe32 100644--- a/workflow-recipes/src/reconciler/resourceBuilder.ts+++ b/workflow-recipes/src/reconciler/resourceBuilder.ts@@ -1372,7 +1372,12 @@ export function buildUiEgressNetworkPolicy(recipe: WorkflowRecipeCRD,sandboxUiNamespace: string,sandboxRecipesNamespace: string,- resolvedExternal: ResolvedExternalEgressInput[]+ resolvedExternal: ResolvedExternalEgressInput[],+ // issue #299: when the reconciler runs the sliding-window accumulator it+ // supplies the serialized state (state + targets + resolved-at). When+ // present these REPLACE the single-snapshot provenance — `resolvedExternal`+ // is then the accumulated effective set, and these annotations describe it.+ stateAnnotations?: Record<string, string>): k8s.V1NetworkPolicy | null {const ui = recipe.spec.uiif (!ui) return null@@ -1415,7 +1420,7 @@ export function buildUiEgressNetworkPolicy(})}- const annotations = buildEgressProvenanceAnnotations(external)+ const annotations = stateAnnotations ?? buildEgressProvenanceAnnotations(external)return {apiVersion: 'networking.k8s.io/v1',@@ -1666,7 +1671,11 @@ export function buildWorkloadEgressNetworkPolicy(workload: WorkloadDef,recipe: WorkflowRecipeCRD,workloadNamespace: string,- resolvedExternal: ResolvedExternalEgressInput[]+ resolvedExternal: ResolvedExternalEgressInput[],+ // issue #299: accumulated sliding-window state (state + targets + resolved-at)+ // supplied by the reconciler. When present, REPLACES single-snapshot+ // provenance; `resolvedExternal` is then the accumulated effective set.+ stateAnnotations?: Record<string, string>): k8s.V1NetworkPolicy | null {const bindings = workload.egressBindings ?? []if (bindings.length === 0) return null@@ -1712,7 +1721,7 @@ export function buildWorkloadEgressNetworkPolicy(if (egress.length === 0) return null- const annotations = buildEgressProvenanceAnnotations(resolvedExternal)+ const annotations = stateAnnotations ?? buildEgressProvenanceAnnotations(resolvedExternal)return {apiVersion: 'networking.k8s.io/v1',diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.tsindex 1691629b6..faae6105c 100644--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts@@ -14,6 +14,7 @@* 11. Handle delete (reverse dependency order, skip PVCs)*/import * as k8s from '@kubernetes/client-node'+import { STATE_ANNOTATION } from '@clerum/network-policy-core'import { OperatorConfig, loadConfig } from '../config'import { getPool } from '../db'import {@@ -54,6 +55,7 @@ import {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 { filterByIncludeWhen } from './includeWhenFilter'import { resolve as resolveInputs } from './inputResolver'@@ -627,6 +629,28 @@ 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`.+ */+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}`)+ }+ }+ return tuples.sort().join(',')+}+export class WorkflowRecipeReconciler {private appsApi: k8s.AppsV1Apiprivate batchApi: k8s.BatchV1Api@@ -637,6 +661,12 @@ export class WorkflowRecipeReconciler {private workflowReconciler: WorkflowReconciler | null = nullprivate _tokenFactory: JwtTokenFactory | null = nullprivate fqdnLookup: FqdnLookup+ // H2 (issue #299): the smallest DNS TTL (ms) observed across external-egress+ // resolutions. The refresh loop advances to <= this/2 so a rotating low-TTL+ // host is sampled every rotation. Ratchets down and never recovers until+ // restart — deliberately: over-refreshing is cheap (writes are no-ops via the+ // F2 gate) and the safe direction; under-refreshing would reopen #299.+ private externalEgressMinObservedTtlMs = Infinityprivate secretReverseIndex: SecretReverseIndex | nullprivate verifyWorkflowRunProvenance: NonNullable<WorkflowRecipeReconcilerDeps['verifyWorkflowRunProvenance']@@ -3905,20 +3935,62 @@ export class WorkflowRecipeReconciler {const externals = recipe.spec.ui?.egress?.external ?? []const { resolved, failures } = await resolveExternalEgress(externals, this.fqdnLookup)- if (failures.length > 0) {+ this.recordExternalEgressTtl(resolved)++ // Permanent failures (no-records / blocked range) never author a partial+ // policy — fail exactly as the single-snapshot resolver did.+ const permanentFailures = failures.filter(f => !f.retryable)+ if (permanentFailures.length > 0) {throw egressResolutionError(`WorkflowRecipe "${recipe.metadata.name}" ui external egress resolution failed`,- failures+ permanentFailures)}++ let effectiveResolved: rb.ResolvedExternalEgressInput[] = resolved+ let stateAnnotations: Record<string, string> | undefined+ let existing: k8s.V1NetworkPolicy | null = null+ let egressRenewalDue = falseif (externals.length > 0) {+ // issue #299: fold this DNS snapshot into the accumulated sliding-window+ // set persisted on the live policy's annotations (rehydrate H5).+ existing = await this.readNetworkPolicyOrNull(policyName, ns)+ const acc = accumulateExternalEgress({+ externals: externals.map(e => ({ fqdn: e.fqdn, port: e.port })),+ resolveResult: { resolved, failures },+ previousAnnotations: existing?.metadata?.annotations,+ now: Date.now(),+ config: {+ overlapMs: this.config.externalEgressOverlapSeconds * 1000,+ maxEntries: this.config.externalEgressMaxEntries,+ },+ })+ // Bootstrap fail-closed: a transient resolver failure with NOTHING to+ // freeze (no rehydratable prior set) must not author an empty policy.+ if (acc.entries.length === 0 && failures.length > 0) {+ throw egressResolutionError(+ `WorkflowRecipe "${recipe.metadata.name}" ui external egress resolution failed`,+ failures+ )+ }+ this.warnEgressAccumulator(policyName, acc)+ effectiveResolved = acc.resolved+ stateAnnotations = acc.annotations+ egressRenewalDue = acc.renewalDue+this.assertClusterEnforcesExternalEgress(recipe,'WRC sandbox-ui external egress policy is ready to apply')}- const policy = rb.buildUiEgressNetworkPolicy(recipe, ns, this.config.sandboxNamespace, resolved)+ const policy = rb.buildUiEgressNetworkPolicy(+ recipe,+ ns,+ this.config.sandboxNamespace,+ effectiveResolved,+ stateAnnotations+ )if (!policy) {await this.safeDelete(@@ -3928,6 +4000,17 @@ export class WorkflowRecipeReconciler {return}+ // issue #299: NO-OP when the accumulated egress set and rules are already+ // live — a TTL-only refresh must not churn the apiserver/dataplane. But DO+ // write when the persisted window is aging (renewalDue, audit M1), even if+ // the set is unchanged, so a stable-then-rotated IP keeps its overlap grace.+ if (!this.egressWriteNeeded(existing, policy) && !egressRenewalDue) {+ console.log(+ `[WR-Reconciler] NetworkPolicy "${policyName}" in ${ns} egress set unchanged — no-op`+ )+ return+ }+await this.createOrReplace(() =>this.networkingApi.createNamespacedNetworkPolicy({@@ -4290,24 +4373,72 @@ export class WorkflowRecipeReconciler {externalDeclared.map(e => ({ fqdn: e.fqdn, port: e.port })),this.fqdnLookup)- if (failures.length > 0) {+ this.recordExternalEgressTtl(resolvedExternal)++ // Permanent failures never author a partial policy — fail as before.+ const permanentFailures = failures.filter(f => !f.retryable)+ if (permanentFailures.length > 0) {throw egressResolutionError(`WorkflowRecipe "${recipe.metadata.name}" workload "${w.id}" egress resolution failed`,- failures+ permanentFailures)}++ let effectiveExternal: rb.ResolvedExternalEgressInput[] = resolvedExternal+ let wlStateAnnotations: Record<string, string> | undefined+ let existingWlPolicy: k8s.V1NetworkPolicy | null = null+ let wlEgressRenewalDue = false+ const wlPolicyName = rb.workloadEgressPolicyName(recipe.metadata.name, w.id)if (externalDeclared.length > 0) {+ // issue #299: accumulate the sliding-window egress set (rehydrate H5).+ existingWlPolicy = await this.readNetworkPolicyOrNull(wlPolicyName, wlNs)+ const acc = accumulateExternalEgress({+ externals: externalDeclared.map(e => ({ fqdn: e.fqdn, port: e.port })),+ resolveResult: { resolved: resolvedExternal, failures },+ previousAnnotations: existingWlPolicy?.metadata?.annotations,+ now: Date.now(),+ config: {+ overlapMs: this.config.externalEgressOverlapSeconds * 1000,+ maxEntries: this.config.externalEgressMaxEntries,+ },+ })+ // Bootstrap fail-closed: transient failure with nothing to freeze.+ if (acc.entries.length === 0 && failures.length > 0) {+ throw egressResolutionError(+ `WorkflowRecipe "${recipe.metadata.name}" workload "${w.id}" egress resolution failed`,+ failures+ )+ }+ this.warnEgressAccumulator(wlPolicyName, acc)+ effectiveExternal = acc.resolved+ wlStateAnnotations = acc.annotations+ wlEgressRenewalDue = acc.renewalDue+this.assertClusterEnforcesExternalEgress(recipe,`WRC workload "${w.id}" external egress policy is ready to apply`)}- const policy = rb.buildWorkloadEgressNetworkPolicy(w, recipe, wlNs, resolvedExternal)+ const policy = rb.buildWorkloadEgressNetworkPolicy(+ w,+ recipe,+ wlNs,+ effectiveExternal,+ wlStateAnnotations+ )if (!policy) {await this.deleteWorkloadEgressIfExists(recipe.metadata.name, w.id, wlNs)continue}+ // issue #299: NO-OP when the accumulated set and rules are already live —+ // but still write when the persisted window is aging (renewalDue, M1).+ if (!this.egressWriteNeeded(existingWlPolicy, policy) && !wlEgressRenewalDue) {+ console.log(+ `[WR-Reconciler] NetworkPolicy "${wlPolicyName}" in ${wlNs} egress set unchanged — no-op`+ )+ continue+ }await this.applyNetworkPolicy(policy, wlNs)}@@ -4354,6 +4485,99 @@ export class WorkflowRecipeReconciler {}}+ /**+ * Read a NetworkPolicy for rehydration/no-op, returning null when it does not+ * yet exist. Fails LOUD on any non-404 read error (issue #299): a rehydration+ * we cannot perform must not silently blank the accumulated egress state.+ */+ private async readNetworkPolicyOrNull(+ name: string,+ namespace: string+ ): Promise<k8s.V1NetworkPolicy | null> {+ try {+ return await this.networkingApi.readNamespacedNetworkPolicy({ name, namespace })+ } catch (error: unknown) {+ if (getErrorCode(error) === 404) return null+ throw error+ }+ }++ /**+ * True when the live policy differs from the desired one and must be written+ * (issue #299 NO-OP gate). Compares the accumulated-state fingerprint AND the+ * enforced egress rules, so a change to either the external IP set OR the+ * internal (sibling) rules still triggers a write — only a byte-for-byte match+ * is a no-op.+ */+ /**+ * The smallest DNS TTL (ms) observed so far across external-egress+ * resolutions, or Infinity if none. The k8s refresh loop reads this to advance+ * to <= TTL/2 (H2, issue #299).+ */+ get externalEgressRefreshMinTtlMs(): number {+ return this.externalEgressMinObservedTtlMs+ }++ /**+ * Ratchet the observed-min-TTL down from this round's resolved entries. Only+ * positive TTLs count (an empty/A-less answer yields ttlSeconds 0, which is not+ * a real refresh cadence).+ */+ private recordExternalEgressTtl(resolved: Array<{ ttlSeconds: number }>): void {+ for (const r of resolved) {+ if (r.ttlSeconds > 0) {+ this.externalEgressMinObservedTtlMs = Math.min(+ this.externalEgressMinObservedTtlMs,+ r.ttlSeconds * 1000+ )+ }+ }+ }++ private egressWriteNeeded(+ existing: k8s.V1NetworkPolicy | null,+ desired: k8s.V1NetworkPolicy+ ): boolean {+ if (!existing) return true+ // Decide the write off the ENFORCED rules (the ipBlock set + ports), NOT the+ // raw state annotation: serializeState embeds expiresAt/lastObservedAt, which+ // renew on every OK tick, so comparing the annotation string would rewrite+ // the policy every refresh even when the IP set is identical — an apiserver /+ // dataplane write-storm (issue #299 audit F2). H4: a timestamp-only refresh+ // must be a no-op.+ if (egressSignature(existing) !== egressSignature(desired)) {+ return true+ }+ // Rules are identical. Persist the new-format state annotation exactly once to+ // migrate a policy that predates it, so a controller restart can rehydrate+ // the accumulated window; thereafter (annotation present, egress unchanged)+ // it is a no-op.+ return !existing.metadata?.annotations?.[STATE_ANNOTATION]+ }++ /**+ * Surface the accumulator's staleness/pressure alarms (issue #299): a frozen+ * FQDN means the resolver is transiently failing and we are serving last-known+ * IPs (fail-static, H1); an over-cap eviction means the pool exceeded the+ * alarm cap and least-recently-observed entries were dropped (H3).+ */+ private warnEgressAccumulator(policyName: string, acc: AccumulateOutput): void {+ if (acc.frozenFqdns.length > 0) {+ console.warn(+ `[WR-Reconciler] ${policyName}: egress set FROZEN (fail-static) for ${acc.frozenFqdns.join(+ ', '+ )} — DNS resolution is transiently failing; serving last-known IPs, not pruning.`+ )+ }+ if (acc.overCap) {+ console.warn(+ `[WR-Reconciler] ${policyName}: egress set hit the maxEntries cap — evicted ${acc.evicted.length} least-recently-observed entr${+ acc.evicted.length === 1 ? 'y' : 'ies'+ } (never rejecting the policy).`+ )+ }+ }+private async applyNetworkPolicy(policy: k8s.V1NetworkPolicy, namespace: string): Promise<void> {const policyName = policy.metadata!.name!await this.createOrReplace(