Skip to content

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

TypeScript

Merge remote-tracking branch 'origin/dev' into pr205-sync

Alfredo Lopez870f7a5375f1
diff --cc deploy/base/control-plane/host-context-controller.yaml
index 782697b37,47786ee6b..f96c3d995
--- a/deploy/base/control-plane/host-context-controller.yaml
+++ b/deploy/base/control-plane/host-context-controller.yaml
@@@ -86,10 -85,14 +97,16 @@@ spec
# API or the HCC discovery API, so they get only deny-all + DNS.
- name: CONTEXT_MAPPER_MINIMAL_INFRA_NAMESPACES
value: sandbox-ui
+ # issue #299: the external-egress resync interval MUST stay <= half the
+ # overlap window (HCC_EXTERNAL_EGRESS_OVERLAP_SEC, default 300s) so the
+ # persisted sliding window of resolved /32s never lapses between
+ # refreshes. The legacy 300 (== the overlap) let the accumulated set
+ # expire before the next refresh, which is the #299 drift itself; HCC
+ # now fails closed at startup on any interval > overlap/2.
- name: HCC_EXTERNAL_EGRESS_RESYNC_SEC
- value: "300"
+ value: "60"
+ - name: HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS
+ value: "5000"
- name: HCC_HOST_K8S_REQUEST_TIMEOUT_MS
value: "30000"
# Bounded cross-Host concurrency for a full/lifecycle Host fleet pass.
diff --cc host-context-controller/package-lock.json
index da7d0ca03,770f7c707..894e839d9
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-host-context-controller",
- "version": "0.1.217",
- "version": "0.1.169",
++ "version": "0.1.218",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.217",
- "version": "0.1.169",
++ "version": "0.1.218",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --cc host-context-controller/package.json
index eaab62ec1,04b826ebf..138dc09bc
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-host-context-controller",
- "version": "0.1.217",
- "version": "0.1.169",
++ "version": "0.1.218",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --cc host-context-controller/src/config.ts
index decfeaeb8,7b7632b75..162ccd06e
--- a/host-context-controller/src/config.ts
+++ b/host-context-controller/src/config.ts
@@@ -193,13 -193,25 +193,29 @@@ 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
+ // Deadline for one DNS resolution attempt. A silent resolver cannot block
+ // safety convergence indefinitely.
+ externalEgressDnsResolveTimeoutMs: 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.
@@@ -233,17 -245,26 +249,37 @@@ function getEnvInt(key: string, default
return isNaN(parsed) ? defaultValue : parsed
}
+export function parseExternalEgressDnsTimeoutMs(raw: string | undefined): number {
+ if (raw === undefined || raw.trim() === '') return 5_000
+ const parsed = Number(raw)
+ if (!Number.isSafeInteger(parsed) || parsed <= 0 || parsed > 2_147_483_647) {
+ throw new Error(
+ `HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS must be a positive integer no greater than 2147483647, got '${raw}'`
+ )
+ }
+ return parsed
+}
+
+ /**
+ * Loud integer env parser for the external-egress knobs (audit R1-L1). Unlike
+ * getEnvInt (parseInt), this rejects non-canonical values instead of silently
+ * coercing them: '60.5'->60 or '60abc'->60 would pass getEnvInt AND the
+ * range invariant (which re-checks the already-truncated value), letting an
+ * in-range typo through quietly. Canonical unsigned base-10 only; empty -> default.
+ */
+ function getExternalEgressEnvInt(key: string, defaultValue: number): number {
+ const raw = process.env[key]
+ if (raw === undefined || raw === '') return defaultValue
+ if (!/^\d+$/.test(raw)) {
+ throw new Error(`${key} must be an unsigned base-10 integer (seconds), got '${raw}'`)
+ }
+ const parsed = Number(raw)
+ if (!Number.isSafeInteger(parsed)) {
+ throw new Error(`${key} is out of the safe integer range, got '${raw}'`)
+ }
+ return parsed
+ }
+
/**
* CONTEXT_MAPPER_HEARTBEAT_POLL_MS — cadence of HCC's control-api heartbeat
* poll. Fails config load loudly on a non-positive-integer value: a silent
@@@ -609,11 -709,17 +724,20 @@@ 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: getExternalEgressEnvInt('HCC_EXTERNAL_EGRESS_RESYNC_SEC', 60),
+ externalEgressDnsResolveTimeoutMs: parseExternalEgressDnsTimeoutMs(
+ getEnv('HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS')
+ ),
+ externalEgressOverlapSec: getExternalEgressEnvInt('HCC_EXTERNAL_EGRESS_OVERLAP_SEC', 300),
+ externalEgressRefreshFloorSec: getExternalEgressEnvInt(
+ 'HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC',
+ 5
+ ),
+ externalEgressMaxEntries: getExternalEgressEnvInt('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).
diff --cc host-context-controller/src/k8sClient.test.ts
index d57bd367a,2aa0ccea4..0304adcb3
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@@ -4,15 -3,11 +4,16 @@@ import { HostFleetReconcileError } fro
import { HostK8sRequestTimeoutError } from './k8s/hostK8sApiClient'
import {
McpServerWatcher,
+ externalEgressResyncDelayMs,
+ getContext,
listAllCommunicationChannels,
+ listAllGlobalFileSystems,
listAllHosts,
+ listAllSharedFileSystems,
} from './k8sClient'
-import type { HostCRD } from './types'
+import { registry } from './metrics'
+import { ContextMapperServer } from './server'
+import type { HostCRD, McpServerCRD } from './types'
function deferred<T = void>(): {
promise: Promise<T>
@@@ -369,18 -224,9 +372,19 @@@ describe('McpServerWatcher startup', (
afterEach(() => {
vi.useRealTimers()
- mockConfig.externalEgressResyncIntervalSec = 0 // R1-M4: keep the timer off by default
+ vi.restoreAllMocks()
+ // Certified is the resting state. vi.clearAllMocks() in beforeEach clears
+ // calls but not implementations, so a test that degrades this getter and
+ // fails before its own restore would silently re-gate readiness for every
+ // later test in the file. Restore it structurally rather than by
+ // per-test discipline.
+ mocks.hasCertifiedSafetyInventory.mockReset().mockReturnValue(true)
++ mockConfig.externalEgressResyncIntervalSec = 0 // keep periodic resync off by default
mocks.ensureDefaultPolicies.mockReset().mockResolvedValue(undefined)
- mocks.netPolFullReconcile.mockReset().mockResolvedValue(undefined)
+ mocks.netPolFullReconcile.mockReset().mockImplementation(async (...args: unknown[]) => {
+ const options = args[2] as { onAuthoritativeRevocationComplete?: () => void } | undefined
+ options?.onAuthoritativeRevocationComplete?.()
+ })
mocks.serverFullReconcile.mockReset().mockResolvedValue(undefined)
mocks.hostFullReconcile.mockReset().mockResolvedValue(undefined)
mocks.sfsFullReconcile.mockReset().mockResolvedValue(undefined)
diff --cc host-context-controller/src/k8sClient.ts
index 3f4795cc3,7fe7ceaec..eefa960a7
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@@ -105,12 -83,30 +105,31 @@@ const PLURAL_HOSTS = 'hosts
const PLURAL_SHAREDFILESYSTEMS = 'sharedfilesystems'
const PLURAL_GLOBALFILESYSTEMS = 'globalfilesystems'
const PLURAL_COMMUNICATIONCHANNELS = 'communicationchannels'
-const EXTERNAL_EGRESS_RETRY_DELAYS_MS = [5000, 15000, 30000]
-const EXTERNAL_EGRESS_RESYNC_MAX_CONCURRENCY = 10
-const EXTERNAL_EGRESS_RESYNC_JITTER_MS = 5000
+// Before readiness was decoupled, a failed initial McpServer or NetworkPolicy
+// sweep made provider.start() fail and Kubernetes restarted HCC. These retries
+// retain that convergence guarantee now that the sweeps run in the background.
+const INITIAL_CONVERGENCE_RETRY_DELAYS_MS = [5000, 15000, 30000, 60000, 300000]
+const INVENTORY_CACHE_RECOVERY_RETRY_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 = 5000
-const COMMUNICATION_CHANNEL_FLEET_RETRY_DELAYS_MS = [5000, 15000, 30000, 60000, 300000]
const HOST_CACHE_RECOVERY_RETRY_MS = 5000
const HOST_WATCH_RECONCILE_RETRY_DELAYS_MS = [5000, 15000, 30000]
// Wake-pending Hosts get immediate per-Host admission after watch recovery
@@@ -2507,366 -1846,35 +2526,370 @@@ export class McpServerWatcher implement
}
const externalEgressResyncSec = config.externalEgressResyncIntervalSec
- if (externalEgressResyncSec > 0) {
- // 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, advancing to <= TTL/2)`
++ // #205 delegates external-egress periodic resync to the convergence
++ // coordinator. Its runResyncCore drives reconcileExternalEgress, so the
++ // #299 sliding-window accumulation still converges on DNS rotation between
++ // McpServer events (the coordinator, not a standalone timer, owns cadence).
+ this.externalEgressCoordinator.startPeriodicResync(externalEgressResyncSec)
+
+ // Full convergence is observable and retains each lane's existing retry or
+ // periodic-resync contract, but it no longer extends provider.start().
+ // NetworkPolicy safety starts first and launches McpServer convergence from
+ // its certification callback, before additive policy convergence completes.
+ // This prevents the startup egress refresh from racing or undoing the safety
+ // pass while keeping readiness independent from both additive fleets.
+ void this.runInitialNetworkPolicyConvergence()
+ void initialSharedFileSystemInventory.then(inventoryComplete => {
+ if (inventoryComplete && !this.stopped) {
+ void this.runInitialSharedFileSystemConvergence()
+ }
+ })
+ void this.startGlobalFileSystemBackgroundLane()
+ }
+
+ private async startSharedFileSystemInventoryAndWatch(): Promise<boolean> {
+ let inventoryComplete = false
+ try {
+ const initialSfses = await listAllSharedFileSystems()
+ inventoryComplete = true
+ for (const sfs of initialSfses) this.sharedFileSystems.set(sfs.name, sfs)
+ } catch (error) {
+ console.error(
+ '[K8s] Skipping initial SharedFileSystem background convergence because discovery failed:',
+ error
)
- } 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.'
+ }
+ // The cold-start Host fleet pass gates on this promise, so it must settle on
+ // the inventory alone. `k8s.Watch` carries no transport deadline — the
+ // client builds `AbortSignal.any([controller, timeout])` and then overwrites
+ // it with the bare controller — so awaiting the watch start here would
+ // re-strand the fleet behind an already-certified readiness, which is the
+ // exact failure bounding the LIST was meant to close.
+ void this.startSharedFileSystemWatch().catch(error => {
+ console.error('[K8s] SharedFileSystem background watch failed to start:', error)
+ this.scheduleSharedFileSystemWatchRestart(5000)
+ })
+ if (inventoryComplete && !this.stopped) {
+ return true
+ }
+ return false
+ }
+
+ private async startGlobalFileSystemBackgroundLane(): Promise<void> {
+ let inventoryComplete = false
+ try {
+ const initialGfses = await listAllGlobalFileSystems()
+ inventoryComplete = true
+ for (const gfs of initialGfses) this.globalFileSystems.set(gfs.name, gfs)
+ } catch (error) {
+ console.error(
+ '[K8s] Skipping initial GlobalFileSystem background convergence because discovery failed:',
+ error
+ )
+ }
+ try {
+ await this.startGlobalFileSystemWatch()
+ } catch (error) {
+ console.error('[K8s] GlobalFileSystem background watch failed to start:', error)
+ this.scheduleGlobalFileSystemWatchRestart(5000)
+ }
+ if (inventoryComplete && !this.stopped) {
+ void this.runInitialGlobalFileSystemConvergence()
+ }
+ }
+
+ private runInitialMcpServerConvergence(): Promise<void> {
+ return this.runInitialConvergence('McpServer')
+ }
+
+ private currentNetworkPolicySafetyCertificate(): NetworkPolicySafetyCertificate | null {
+ if (
+ this.stopped ||
+ !this.contextCacheSynced ||
+ !this.mcpServerCacheSynced ||
+ !this.netPolReconciler.hasCertifiedSafetyInventory() ||
+ this.networkPolicyRevocationContextGeneration !== this.contextWatchGeneration ||
+ this.networkPolicyRevocationServerGeneration !== this.mcpWatchGeneration ||
+ this.networkPolicyRevocationContextRevision !== this.contextDesiredRevision ||
+ this.networkPolicyRevocationServerRevision !== this.mcpServerDesiredRevision
+ ) {
+ return null
+ }
+ return {
+ contextGeneration: this.contextWatchGeneration,
+ serverGeneration: this.mcpWatchGeneration,
+ contextRevision: this.contextDesiredRevision,
+ serverRevision: this.mcpServerDesiredRevision,
+ }
+ }
+
+ private recordNetworkPolicySafetyCertificate(
+ certificate: NetworkPolicySafetyCertificate
+ ): boolean {
+ if (
+ this.stopped ||
+ !this.contextCacheSynced ||
+ !this.mcpServerCacheSynced ||
+ this.contextWatchGeneration !== certificate.contextGeneration ||
+ this.mcpWatchGeneration !== certificate.serverGeneration ||
+ this.contextDesiredRevision !== certificate.contextRevision ||
+ this.mcpServerDesiredRevision !== certificate.serverRevision
+ ) {
+ return false
+ }
+ this.networkPolicyRevocationContextGeneration = certificate.contextGeneration
+ this.networkPolicyRevocationServerGeneration = certificate.serverGeneration
+ this.networkPolicyRevocationContextRevision = certificate.contextRevision
+ this.networkPolicyRevocationServerRevision = certificate.serverRevision
+ return true
+ }
+
+ private isNetworkPolicySafetyCertificateCurrent(
+ certificate: NetworkPolicySafetyCertificate
+ ): boolean {
+ const current = this.currentNetworkPolicySafetyCertificate()
+ return (
+ current !== null &&
+ current.contextGeneration === certificate.contextGeneration &&
+ current.serverGeneration === certificate.serverGeneration &&
+ current.contextRevision === certificate.contextRevision &&
+ current.serverRevision === certificate.serverRevision
+ )
+ }
+
+ private async runInitialMcpServerConvergenceCore(): Promise<void> {
+ const safetyCertificate = this.currentNetworkPolicySafetyCertificate()
+ if (safetyCertificate === null) return
+ const inventoryGeneration = this.mcpWatchGeneration
+ const inventoryAuthoritative = () =>
+ this.hasMcpServerInventoryAuthority(inventoryGeneration) &&
+ this.isNetworkPolicySafetyCertificateCurrent(safetyCertificate)
+ try {
+ const initialServers = [...this.servers.values()]
+ const initialExternalEgressGates = this.externalEgressCoordinator.prepareStartupGates(
+ initialServers,
+ inventoryAuthoritative
+ )
+ if (this.stopped) return
+ console.log('[K8s] Running initial McpServer background reconciliation...')
+ await this.reconciler.fullReconcile(initialServers, {
+ runEffect: async (serverName, work) => {
+ const selected = this.servers.get(serverName)
+ const laneOwner = selected ?? {
+ name: serverName,
+ namespace: config.namespace,
+ }
+ if (!(await initialExternalEgressGates.waitFor(laneOwner))) return
+ if (!inventoryAuthoritative()) return
+ await this.enqueueMcpServerReconciliation(laneOwner, async () => {
+ if (!inventoryAuthoritative()) return
+ await work()
+ })
+ },
+ })
+ if (!inventoryAuthoritative()) return
+ initialConvergenceLastSuccessTimestampSeconds.set({ lane: 'McpServer' }, Date.now() / 1000)
+ this.clearInitialConvergenceRetry('McpServer')
+ } catch (error) {
+ console.error('[K8s] Initial McpServer background reconciliation failed:', error)
+ this.scheduleInitialConvergenceRetry('McpServer')
+ }
+ }
+
+ private runInitialNetworkPolicyConvergence(): Promise<void> {
+ return this.runInitialConvergence('NetworkPolicy')
+ }
+
+ private runInitialConvergence(lane: InitialConvergenceLane): Promise<void> {
+ const active = this.initialConvergenceRuns.get(lane)
+ if (active) {
+ active.trailingRequested = true
+ return active.promise
+ }
+
+ const run: ActiveInitialConvergenceRun = {
+ trailingRequested: false,
+ promise: Promise.resolve(),
+ }
+ this.initialConvergenceRuns.set(lane, run)
+ run.promise = Promise.resolve()
+ .then(async () => {
+ do {
+ run.trailingRequested = false
+ if (lane === 'McpServer') {
+ await this.runInitialMcpServerConvergenceCore()
+ } else {
+ await this.runInitialNetworkPolicyConvergenceCore()
+ }
+ } while (!this.stopped && run.trailingRequested)
+ // Retire the active slot synchronously before this promise settles.
+ // A request arriving in the following settlement microtask must start
+ // a new run instead of attaching to a pass whose loop already exited.
+ if (this.initialConvergenceRuns.get(lane) === run) {
+ this.initialConvergenceRuns.delete(lane)
+ }
+ })
+ .finally(() => {
+ // Errors bypass the normal retirement above.
+ if (this.initialConvergenceRuns.get(lane) === run) {
+ this.initialConvergenceRuns.delete(lane)
+ }
+ })
+ return run.promise
+ }
+
+ private async runInitialNetworkPolicyConvergenceCore(): Promise<void> {
+ // A NetworkPolicy full pass combines authoritative Context/McpServer allow
+ // revocation with additive Context policy effects. External egress
+ // creation and DNS refresh have one separate owner: the startup/resync
+ // coordinator. Running safety from a partial inventory would be neither a
+ // full convergence nor safe evidence of success. Recovery of either
+ // missing LIST -> WATCH pair schedules a fresh current-cache pass.
+ if (!this.contextCacheSynced || !this.mcpServerCacheSynced) return
+ let authoritativeRevocationCompleted = false
+ try {
+ const initialContexts = [...this.contexts.values()]
+ const initialServers = [...this.servers.values()]
+ const contextInventoryGeneration = this.contextWatchGeneration
+ const serverInventoryGeneration = this.mcpWatchGeneration
+ const safetyCertificate: NetworkPolicySafetyCertificate = {
+ contextGeneration: contextInventoryGeneration,
+ serverGeneration: serverInventoryGeneration,
+ contextRevision: this.contextDesiredRevision,
+ serverRevision: this.mcpServerDesiredRevision,
+ }
+ const serverInventoryComplete = this.mcpServerCacheSynced
+ const contextInventoryAuthoritative = () =>
+ this.hasContextInventoryAuthority(contextInventoryGeneration)
+ const serverInventoryAuthoritative = () =>
+ this.hasMcpServerInventoryAuthority(serverInventoryGeneration)
+ console.log('[K8s] Running initial NetworkPolicy background reconciliation...')
+ await this.netPolReconciler.fullReconcile(initialContexts, initialServers, {
+ serverInventoryComplete,
+ ensureDefaults: false,
+ contextInventoryAuthoritative,
+ serverInventoryAuthoritative,
+ runContextEffect: (contextId, work) =>
+ this.enqueueContextReconciliation(contextId, async () => {
+ if (!contextInventoryAuthoritative() || !serverInventoryAuthoritative()) return
+ await work()
+ }),
+ runServerEffect: (serverName, work) => {
+ const selected = this.servers.get(serverName)
+ return this.enqueueMcpServerReconciliation(
+ selected ?? { name: serverName, namespace: config.namespace },
+ async () => {
+ if (!serverInventoryAuthoritative()) return
+ await work()
+ }
+ )
+ },
+ resolveCurrentContext: name => this.contexts.get(name),
+ resolveCurrentContextById: contextId =>
+ [...this.contexts.values()].find(context => context.spec.contextId === contextId),
+ resolveCurrentServer: name => this.servers.get(name),
+ contextDesiredRevision: () => this.contextDesiredRevision,
+ serverDesiredRevision: () => this.mcpServerDesiredRevision,
+ // B3 piece-2: queue an additive recreation for every server whose
+ // external-egress allow the authoritative pass revoked — fired at the
+ // deletion, so an abort/throw cannot strand a revoked-but-desired allow.
+ // The coordinator maps against the current cache (absent → DELETED, no
+ // recreate) and rebuilds from the current spec with fresh DNS.
+ onExternalEgressRevoked: server =>
+ this.externalEgressCoordinator.scheduleRetry('MODIFIED', server),
+ onAuthoritativeRevocationComplete: () => {
+ if (!this.recordNetworkPolicySafetyCertificate(safetyCertificate)) return
+ authoritativeRevocationCompleted = true
+ // Start runtime convergence at the safety boundary, before this full
+ // pass enters additive Context work. Startup egress gates may now
+ // preserve only policies certified by this exact authoritative
+ // inventory generation.
+ void this.runInitialMcpServerConvergence()
+ },
+ })
+ if (!contextInventoryAuthoritative() || !serverInventoryAuthoritative()) return
+ initialConvergenceLastSuccessTimestampSeconds.set(
+ { lane: 'NetworkPolicy' },
+ Date.now() / 1000
+ )
+ this.clearInitialConvergenceRetry('NetworkPolicy')
+ } catch (error) {
+ console.error(
+ authoritativeRevocationCompleted
+ ? '[K8s] Initial NetworkPolicy post-certification additive reconciliation failed:'
+ : '[K8s] Initial NetworkPolicy background reconciliation failed:',
+ error
)
+ this.scheduleInitialConvergenceRetry('NetworkPolicy')
+ }
+ }
+
+ private clearInitialConvergenceRetry(lane: InitialConvergenceLane): void {
+ const timer = this.initialConvergenceRetryTimers.get(lane)
+ if (timer) {
+ clearTimeout(timer)
+ this.initialConvergenceRetryTimers.delete(lane)
+ }
+ this.initialConvergenceRetryAttempts.delete(lane)
+ }
+
+ private scheduleInitialConvergenceRetry(lane: InitialConvergenceLane): void {
+ if (this.stopped || this.initialConvergenceRetryTimers.has(lane)) return
+
+ const attempt = (this.initialConvergenceRetryAttempts.get(lane) ?? 0) + 1
+ const delayMs =
+ INITIAL_CONVERGENCE_RETRY_DELAYS_MS[
+ Math.min(attempt - 1, INITIAL_CONVERGENCE_RETRY_DELAYS_MS.length - 1)
+ ]
+ this.initialConvergenceRetryAttempts.set(lane, attempt)
+ initialConvergenceRetriesTotal.inc({ lane })
+ console.warn(
+ `[K8s] Scheduling initial ${lane} background convergence retry ${attempt} in ${delayMs}ms`
+ )
+
+ const timer = setTimeout(() => {
+ this.initialConvergenceRetryTimers.delete(lane)
+ if (this.stopped) return
+ if (lane === 'McpServer') {
+ void this.runInitialMcpServerConvergence()
+ return
+ }
+ void this.runInitialNetworkPolicyConvergence()
+ }, delayMs)
+ this.initialConvergenceRetryTimers.set(lane, timer)
+ }
+
+ private runInitialSharedFileSystemConvergence(): Promise<void> {
+ const names = [...this.sharedFileSystems.keys()]
+ return this.enqueueSharedFileSystemFleetReconciliation(names, () =>
+ this.runInitialSharedFileSystemConvergenceCore()
+ )
+ }
+
+ private async runInitialSharedFileSystemConvergenceCore(): Promise<void> {
+ try {
+ const initialSfses = [...this.sharedFileSystems.values()]
+ console.log('[K8s] Running initial SharedFileSystem background reconciliation...')
+ await this.sharedFileSystemReconciler.fullReconcile(initialSfses)
+ } catch (error) {
+ console.error('[K8s] Initial SharedFileSystem background reconciliation failed:', error)
+ }
+ }
+
+ private runInitialGlobalFileSystemConvergence(): Promise<void> {
+ const names = [...this.globalFileSystems.keys()]
+ return this.enqueueGlobalFileSystemFleetReconciliation(names, () =>
+ this.runInitialGlobalFileSystemConvergenceCore()
+ )
+ }
+
+ private async runInitialGlobalFileSystemConvergenceCore(): Promise<void> {
+ try {
+ const initialGfses = [...this.globalFileSystems.values()]
+ console.log('[K8s] Running initial GlobalFileSystem background reconciliation...')
+ await this.gfsReconciler.fullReconcile(initialGfses)
+ } catch (error) {
+ console.error('[K8s] Initial GlobalFileSystem background reconciliation failed:', error)
}
}
diff --cc host-context-controller/src/networkPolicyReconciler.test.ts
index 0b3011a69,8f3d3f3e1..e4a9b32e3
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@@ -3,37 -4,14 +4,42 @@@ import type { RecordWithTtl } from 'nod
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 { confirmAuthoritativeMcpServerAbsence } from './mcpServerSafety'
+import {
+ networkPolicySafetyPassDurationSeconds,
+ networkPolicySafetyPassPoliciesTotal,
+} from './metrics'
+import {
+ NetworkPolicyReconciler,
+ PUBLIC_EGRESS_EXCEPT_CIDRS,
+ sameContextDesiredRevision,
+} from './networkPolicyReconciler'
import { ContextCRD, McpServerCRD } from './types'
+function deferred<T = void>(): {
+ promise: Promise<T>
+ resolve: (value: T | PromiseLike<T>) => void
+} {
+ let resolve!: (value: T | PromiseLike<T>) => void
+ const promise = new Promise<T>(res => {
+ resolve = res
+ })
+ return { promise, resolve }
+}
+
+vi.mock('./mcpServerSafety', async () => {
+ const actual = await vi.importActual<typeof import('./mcpServerSafety')>('./mcpServerSafety')
+ return {
+ ...actual,
+ confirmAuthoritativeMcpServerAbsence: vi.fn(actual.confirmAuthoritativeMcpServerAbsence),
+ }
+})
+
+ // 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 config
vi.mock('./config', () => ({
config: {
@@@ -44,20 -22,23 +50,29 @@@
port: 8081,
runtimeNamespaces: ['mcp-server', 'mcp-host', 'sandbox-recipes', 'rpc-proxy'],
k8sApiCidrs: [],
+ externalEgressDnsResolveTimeoutMs: 5_000,
+ // #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 },
+ ]),
}))
+vi.mock('./metrics', () => ({
+ networkPolicySafetyPassDurationSeconds: { observe: vi.fn() },
+ networkPolicySafetyPassPoliciesTotal: { inc: vi.fn() },
+}))
+
function makeMockNetworkingApi() {
return {
createNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
@@@ -164,105 -85,9 +179,105 @@@ 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'))
})
+ it('compares Context desired revisions canonically and fences identity changes', () => {
+ const expected: ContextCRD = {
+ name: 'default',
+ namespace: 'mcp-server',
+ uid: 'context-uid',
+ generation: 7,
+ spec: {
+ contextId: 'default',
+ mcpServers: ['alpha'],
+ sharedFileSystems: [{ name: 'workspace', mountPath: '/workspace' }],
+ },
+ }
+ const reordered: ContextCRD = {
+ namespace: 'mcp-server',
+ name: 'default',
+ generation: 7,
+ uid: 'context-uid',
+ spec: {
+ sharedFileSystems: [{ mountPath: '/workspace', name: 'workspace' }],
+ mcpServers: ['alpha'],
+ contextId: 'default',
+ },
+ }
+
+ expect(sameContextDesiredRevision(expected, reordered)).toBe(true)
+ expect(sameContextDesiredRevision(expected, { ...reordered, uid: 'replacement-uid' })).toBe(
+ false
+ )
+ expect(sameContextDesiredRevision(expected, { ...reordered, generation: 8 })).toBe(false)
+ })
+
+ it('records the authoritative safety-pass inventory, completed revocations, and duration', async () => {
+ mockApi.listNamespacedNetworkPolicy
+ .mockResolvedValueOnce({
+ items: [
+ {
+ metadata: {
+ name: 'orphan-context',
+ labels: { 'clerum.io/context': 'missing-context' },
+ },
+ },
+ ],
+ })
+ .mockResolvedValueOnce({
+ items: [
+ {
+ metadata: {
+ name: 'orphan-host-egress',
+ labels: { 'clerum.io/context': 'missing-context' },
+ },
+ },
+ ],
+ })
+ .mockResolvedValueOnce({
+ items: [
+ {
+ metadata: {
+ name: 'orphan-rpc-egress',
+ labels: { 'clerum.io/context': 'missing-context' },
+ },
+ },
+ ],
+ })
+ .mockResolvedValueOnce({
+ items: [
+ {
+ metadata: {
+ name: 'orphan-external-egress',
+ labels: { 'clerum.io/mcpserver': 'missing-server' },
+ },
+ },
+ ],
+ })
+ const complete = vi.fn()
+
+ await reconciler.fullReconcile([], [], {
+ ensureDefaults: false,
+ onAuthoritativeRevocationComplete: complete,
+ })
+
+ expect(complete).toHaveBeenCalledOnce()
+ expect(networkPolicySafetyPassPoliciesTotal.inc).toHaveBeenCalledWith(
+ { operation: 'listed' },
+ 4
+ )
+ expect(networkPolicySafetyPassPoliciesTotal.inc).toHaveBeenCalledWith(
+ { operation: 'revoked' },
+ 4
+ )
+ expect(networkPolicySafetyPassDurationSeconds.observe).toHaveBeenCalledWith(
+ { outcome: 'completed' },
+ expect.any(Number)
+ )
+ expect(networkPolicySafetyPassDurationSeconds.observe).toHaveBeenCalledTimes(1)
+ })
+
describe('public egress blocklist parity', () => {
it('keeps the HCC and WRC IPv4 exclusion lists in sync', () => {
const wrcFactory = readFileSync(
diff --cc host-context-controller/src/networkPolicyReconciler.ts
index a4dc7ec59,8778887cd..b1feac9c7
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@@ -25,14 -26,7 +26,15 @@@ import
MCPSERVER_LABEL,
POLICY_TYPE_LABEL,
} from './constants'
+ import { accumulateHostExactHostEgress } from './externalEgressAccumulator'
+import {
+ confirmAuthoritativeMcpServerAbsence,
+ sameMcpServerDesiredRevision,
+} from './mcpServerSafety'
+import {
+ networkPolicySafetyPassDurationSeconds,
+ networkPolicySafetyPassPoliciesTotal,
+} from './metrics'
import {
ContextCRD,
EgressBinding,
@@@ -365,16 -205,13 +407,23 @@@ export class NetworkPolicyReconciler
/** Reference to the MCP server cache so we can look up ports. */
private serverCache: Map<string, McpServerCRD>
+ /**
+ * Set whenever an authoritative safety pass ends without certifying, cleared
+ * as soon as one certifies again. Only that pass enumerates the bounded
+ * namespaces and classifies every object it finds; the scoped delta lane sees
+ * nothing but its own label selectors. A delta therefore cannot vouch for a
+ * namespace whose classified inventory is still stuck on an unresolved
+ * policy, and must not certify readiness on its behalf.
+ */
+ private safetyPassLeftUncertified = false
+
+ // 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)
@@@ -1544,267 -801,8 +1623,272 @@@
console.log('[NetPol] Full reconciliation complete')
}
+ private async contextOrphanDeleteAllowed(
+ contextId: string,
+ inventoryAuthoritative: () => boolean,
+ resolveCurrentContextById?: (contextId: string) => ContextCRD | undefined
+ ): Promise<boolean> {
+ if (!inventoryAuthoritative() || resolveCurrentContextById?.(contextId)) return false
+
+ const response = (await this.customApi.listNamespacedCustomObject({
+ group: GROUP,
+ version: VERSION,
+ namespace: config.namespace,
+ plural: PLURAL_CONTEXTS,
+ })) as { items?: Array<{ spec?: { contextId?: string } }> }
+ if ((response.items ?? []).some(context => context.spec?.contextId === contextId)) return false
+
+ return inventoryAuthoritative() && !resolveCurrentContextById?.(contextId)
+ }
+
// ─── L3 External Egress ────────────────────────────────────────────
+ private buildPublicWebEgressPolicy(server: McpServerCRD, name: string): k8s.V1NetworkPolicy {
+ return {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: {
+ name,
+ namespace: server.namespace,
+ labels: {
+ [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
+ [POLICY_TYPE_LABEL]: EXTERNAL_EGRESS_POLICY_TYPE,
+ [MCPSERVER_LABEL]: server.name,
+ [EGRESS_CLASS_LABEL]: 'public-web',
+ },
+ },
+ spec: {
+ podSelector: {
+ matchLabels: { [MCPSERVER_LABEL]: server.name },
+ },
+ policyTypes: ['Egress'],
+ egress: [
+ {
+ to: [
+ {
+ ipBlock: {
+ cidr: '0.0.0.0/0',
+ except: PUBLIC_EGRESS_EXCEPT_CIDRS,
+ },
+ },
+ ],
+ ports: [
+ { port: 443, protocol: 'TCP' },
+ { port: 80, protocol: 'TCP' },
+ ],
+ },
+ ],
+ },
+ }
+ }
+
+ private buildExactHostEgressPolicy(
+ server: McpServerCRD,
+ name: string,
+ binding: EgressBinding,
+ cidrs: string[]
+ ): k8s.V1NetworkPolicy {
+ return {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: {
+ name,
+ namespace: server.namespace,
+ labels: {
+ [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
+ [POLICY_TYPE_LABEL]: EXTERNAL_EGRESS_POLICY_TYPE,
+ [MCPSERVER_LABEL]: server.name,
+ [EGRESS_CLASS_LABEL]: 'exact-host',
+ },
+ },
+ spec: {
+ podSelector: {
+ matchLabels: { [MCPSERVER_LABEL]: server.name },
+ },
+ policyTypes: ['Egress'],
+ egress: cidrs.map(cidr => ({
+ to: [{ ipBlock: { cidr } }],
+ ports: [{ port: binding.port!, protocol: binding.protocol ?? 'TCP' }],
+ })),
+ },
+ }
+ }
+
- private async resolveExternalEgressDns(hostname: string): Promise<string[]> {
++ private async resolveExternalEgressDns(
++ hostname: string
++ ): Promise<{ address: string; ttl: number }[]> {
++ // Resolve with TTL (issue #299 H2 ratchet needs the smallest observed TTL)
++ // while keeping the #205 bounded-timeout race so a silent resolver cannot
++ // block safety convergence indefinitely.
+ let timeout: ReturnType<typeof setTimeout> | undefined
+ try {
+ return await Promise.race([
- dns.resolve4(hostname),
++ dns.resolve4(hostname, { ttl: true }),
+ new Promise<never>((_, reject) => {
+ timeout = setTimeout(
+ () =>
+ reject(
+ new Error(
+ `DNS resolution timed out after ${config.externalEgressDnsResolveTimeoutMs}ms`
+ )
+ ),
+ config.externalEgressDnsResolveTimeoutMs
+ )
+ }),
+ ])
+ } finally {
+ if (timeout !== undefined) clearTimeout(timeout)
+ }
+ }
+
+ private async reconcileExternalEgressSafety(
+ server: McpServerCRD,
+ existingPolicies: k8s.V1NetworkPolicy[],
+ isCurrent: () => boolean,
+ onRevoked?: () => void
+ ): Promise<boolean> {
+ if (!isCurrent()) return false
+ const desired = new Map<string, { binding: EgressBinding; policy?: k8s.V1NetworkPolicy }>()
+ for (const binding of server.spec.egressBindings ?? []) {
+ const name = this.externalEgressPolicyName(server.name, binding)
+ if (!name) continue
+ const egressClass = binding.egressClass ?? 'exact-host'
+ if (
+ egressClass === 'public-web' &&
+ !binding.dns &&
+ !binding.cidr &&
+ binding.port === undefined &&
+ binding.protocol === undefined
+ ) {
+ desired.set(name, { binding, policy: this.buildPublicWebEgressPolicy(server, name) })
+ } else if (
+ egressClass === 'exact-host' &&
+ binding.cidr &&
+ isAllowedExternalEgressCidr(binding.cidr) &&
+ binding.port !== undefined &&
+ Number.isInteger(binding.port) &&
+ binding.port >= 1 &&
+ binding.port <= 65535
+ ) {
+ desired.set(name, {
+ binding,
+ policy: this.buildExactHostEgressPolicy(server, name, binding, [binding.cidr]),
+ })
+ } else if (
+ egressClass === 'exact-host' &&
+ binding.dns &&
+ isPublicDnsHostname(binding.dns) &&
+ binding.port !== undefined &&
+ Number.isInteger(binding.port) &&
+ binding.port >= 1 &&
+ binding.port <= 65535
+ ) {
+ desired.set(name, { binding })
+ }
+ }
+
+ const stale: k8s.V1NetworkPolicy[] = []
+ const unprovableDnsPolicies: k8s.V1NetworkPolicy[] = []
+ const deterministicReplacements: Array<{
+ snapshot: k8s.V1NetworkPolicy
+ desired: k8s.V1NetworkPolicy
+ }> = []
+ for (const existing of existingPolicies) {
+ const name = existing.metadata?.name
+ const selected = name ? desired.get(name) : undefined
+ if (!selected) {
+ stale.push(existing)
+ continue
+ }
+ desired.delete(name!)
+ if (!selected.policy) {
+ // DNS binding: the /32s cannot be proven without a fresh lookup, but
+ // the binding IDENTITY (protocol, spec-level ports, selector,
+ // ownership) can. Retain the live allow when identity is unchanged;
+ // revoke only on an identity change (a port move in the CRD changes the
+ // policy NAME and is handled by the stale lane above). The comparison is
+ // "modulo cidr": the desired policy is rebuilt WITH the live cidrs, so
+ // the cidrs compare against themselves and everything else must match
+ // exactly. A policy with no ipBlock peers is a deny disguised as an
+ // allow and is never retained.
+ const existingCidrs = (existing.spec?.egress ?? [])
+ .flatMap(rule => rule.to ?? [])
+ .map(peer => peer.ipBlock?.cidr)
+ .filter((cidr): cidr is string => typeof cidr === 'string')
+ const identityUnchanged =
+ existingCidrs.length > 0 &&
+ hasExpectedPolicyOwnership(existing, EXTERNAL_EGRESS_POLICY_TYPE) &&
+ sameNetworkPolicySpec(
+ existing,
+ this.buildExactHostEgressPolicy(server, name!, selected.binding, existingCidrs)
+ )
+ if (!identityUnchanged) unprovableDnsPolicies.push(existing)
+ continue
+ }
+ const retainable =
+ sameNetworkPolicySpec(existing, selected.policy) &&
+ hasExpectedPolicyOwnership(existing, EXTERNAL_EGRESS_POLICY_TYPE)
+ if (!retainable) {
+ deterministicReplacements.push({ snapshot: existing, desired: selected.policy })
+ }
+ }
+
+ // Preserve traffic only with deterministic CIDR/public-web policies. A
+ // renamed deterministic binding is created before its stale predecessor is
+ // removed; a same-name conflict is converged only under the ownership
+ // guard, which still refuses to adopt a foreign live object.
+ if (stale.length > 0) {
+ for (const selected of desired.values()) {
+ if (!selected.policy) continue
+ if (
+ !(await this.createSafetyPolicy(
+ server.namespace,
+ selected.policy,
+ 'external-egress',
+ isCurrent
+ ))
+ ) {
+ return false
+ }
+ }
+ }
+ for (const replacement of deterministicReplacements) {
+ if (
+ !(await this.replaceSafetyPolicySnapshot(
+ server.namespace,
+ replacement.snapshot,
+ replacement.desired,
+ 'external-egress',
+ isCurrent
+ ))
+ ) {
+ return false
+ }
+ onRevoked?.()
+ }
+
+ // DNS-derived /32s are unprovable without a fresh lookup. Revoke them
+ // immediately; replacement belongs to the additive lane and must not put
+ // external DNS latency back on the global readiness path.
+ await this.cleanupExternalEgress(
+ server.name,
+ server.namespace,
+ unprovableDnsPolicies,
+ async () => isCurrent(),
+ onRevoked
+ )
+ if (!isCurrent()) return false
+
+ await this.cleanupExternalEgress(
+ server.name,
+ server.namespace,
+ stale,
+ async () => isCurrent(),
+ onRevoked
+ )
+ return isCurrent()
+ }
+
/**
* Reconcile external egress policies for an McpServer with egressBindings.
* For DNS bindings, resolves hostnames to IPs and creates ipBlock rules.
@@@ -1908,13 -904,49 +2009,15 @@@
}
desiredPolicyNames.add(name)
- await this.applyOwnedPolicy(
- name,
- server.namespace,
- this.buildPublicWebEgressPolicy(server, name),
- 'external-egress',
- isCurrent
- )
+
- const policy: k8s.V1NetworkPolicy = {
- apiVersion: 'networking.k8s.io/v1',
- kind: 'NetworkPolicy',
- metadata: {
- name,
- namespace: server.namespace,
- labels: {
- [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
- [POLICY_TYPE_LABEL]: EXTERNAL_EGRESS_POLICY_TYPE,
- [MCPSERVER_LABEL]: server.name,
- [EGRESS_CLASS_LABEL]: egressClass,
- },
- },
- spec: {
- podSelector: {
- matchLabels: { [MCPSERVER_LABEL]: server.name },
- },
- policyTypes: ['Egress'],
- egress: [
- {
- to: [
- {
- ipBlock: {
- cidr: '0.0.0.0/0',
- except: PUBLIC_EGRESS_EXCEPT_CIDRS,
- },
- },
- ],
- ports: [
- { port: 443, protocol: 'TCP' },
- { port: 80, protocol: 'TCP' },
- ],
- },
- ],
- },
- }
-
- // 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).
++ // public-web is a static policy. Preserve #205's ownership-fenced write
++ // (applyOwnedPolicy asserts ownership + honors the isCurrent generation
++ // fence) while keeping dev's F2 no-churn gate so the TTL-accelerated
++ // resync does not rewrite it every tick.
++ const policy = this.buildPublicWebEgressPolicy(server, name)
+ if (this.externalEgressWriteNeeded(existingPolicy, policy)) {
- await applyNetworkPolicy(this.networkingApi, name, server.namespace, policy, '[NetPol]')
++ await this.applyOwnedPolicy(name, server.namespace, policy, 'external-egress', isCurrent)
+ }
continue
}
@@@ -1945,10 -978,23 +2049,24 @@@
)
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 this.resolveExternalEgressDns(binding.dns)
- const records = await dns.resolve4(binding.dns, { ttl: true })
++ const records = await this.resolveExternalEgressDns(binding.dns)
+ if (!isCurrent()) return
- const uniqueIps = [...new Set(ips)].sort()
+ 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
@@@ -1979,14 -1093,47 +2165,29 @@@
}
desiredPolicyNames.add(name)
- const desiredPolicy = this.buildExactHostEgressPolicy(server, name, binding, cidrs)
- await this.applyOwnedPolicy(
- name,
- server.namespace,
- desiredPolicy,
- 'external-egress',
- isCurrent
- )
+
- const policy: k8s.V1NetworkPolicy = {
- apiVersion: 'networking.k8s.io/v1',
- kind: 'NetworkPolicy',
- metadata: {
- name,
- namespace: server.namespace,
- labels: {
- [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
- [POLICY_TYPE_LABEL]: EXTERNAL_EGRESS_POLICY_TYPE,
- [MCPSERVER_LABEL]: server.name,
- [EGRESS_CLASS_LABEL]: egressClass,
- },
- // 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: {
- matchLabels: { [MCPSERVER_LABEL]: server.name },
- },
- policyTypes: ['Egress'],
- egress: cidrs.map(cidr => ({
- to: [{ ipBlock: { cidr } }],
- ports: [{ port: binding.port, protocol }],
- })),
- },
++ // Build the exact-host policy from #205's helper, then fold in the #299
++ // sliding-window state annotations so the next reconcile rehydrates the
++ // accumulated set instead of collapsing to a single snapshot.
++ const policy = this.buildExactHostEgressPolicy(server, name, binding, cidrs)
++ if (stateAnnotations) {
++ policy.metadata = { ...(policy.metadata ?? {}), annotations: stateAnnotations }
+ }
+
+ // 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.
++ // Route the write through applyOwnedPolicy so #205's ownership assertion
++ // and isCurrent generation fence still guard the mutation.
+ if (
+ this.externalEgressWriteNeeded(existingPolicy, policy) ||
+ egressRenewalDue ||
+ egressStateChanged
+ ) {
- await applyNetworkPolicy(this.networkingApi, name, server.namespace, policy, '[NetPol]')
++ await this.applyOwnedPolicy(name, server.namespace, policy, 'external-egress', isCurrent)
+ } else {
+ console.log(`[NetPol] External egress "${name}" unchanged — no-op (issue #299 no-churn)`)
+ }
}
try {