Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(egress): resolve Codex review Medium findings for #299
Alfredo Lopez442031dd0a8f
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex 553fab500..b6b312367 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -67,6 +67,7 @@ jobs:- packages/desktop-app-links- packages/workflow-runtime-core- packages/workflow-sdk+ - packages/network-policy-coresteps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4@@ -112,8 +113,11 @@ jobs:# project and just prints its help text. Adding a strict root tsconfig surfaces# ~10 pre-existing type errors in its __tests__ — worth fixing, but as its own# change rather than smuggled into a CI-coverage PR.+ # network-policy-core is a hand-authored .cjs + .d.ts with no tsconfig, so+ # `tsc --noEmit` resolves no project (like mcp-servers). Its .d.ts is kept+ # aligned with the runtime by the "runtime exports stay aligned" node:test.- name: Typecheck (tsc --noEmit)- if: matrix.service != 'mcp-servers' && matrix.service != 'packages/desktop-app-links'+ if: matrix.service != 'mcp-servers' && matrix.service != 'packages/desktop-app-links' && matrix.service != 'packages/network-policy-core'working-directory: ${{ matrix.service }}run: npx tsc --noEmitdiff --git a/Makefile b/Makefileindex c47a43581..876a5559a 100644--- a/Makefile+++ b/Makefile@@ -67,7 +67,8 @@ TEST_SERVICES := \mcp-servers \packages/desktop-app-links \packages/workflow-runtime-core \- packages/workflow-sdk+ packages/workflow-sdk \+ packages/network-policy-core# ── Optional private infra (gcp-*, promotion) ──────────────────────────────-include Makefile.infradiff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex b53cae8f9..9a64a11d4 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.166",+ "version": "0.1.167","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.166",+ "version": "0.1.167","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 4e8406104..17f38b785 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.166",+ "version": "0.1.167","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/config.externalEgressResync.test.ts b/host-context-controller/src/config.externalEgressResync.test.tsindex 63a01fd9e..5cff9906d 100644--- a/host-context-controller/src/config.externalEgressResync.test.ts+++ b/host-context-controller/src/config.externalEgressResync.test.ts@@ -92,4 +92,38 @@ describe('external egress sliding-window config (issue #299)', () => {/HCC_EXTERNAL_EGRESS_RESYNC_SEC/)})++ // M-C prong 1: cadence knobs must be capped at 3600s. An unbounded value like+ // 2_200_000 exceeds Node's signed-32-bit setTimeout limit (2^31-1 ms) and is+ // clamped to 1ms → a back-to-back DNS-resync hot loop. Port of commit 3f968956.+ it('fails loud when the overlap exceeds the 3600s cap (M-C timer overflow)', async () => {+ await expect(loadConfig({ HCC_EXTERNAL_EGRESS_OVERLAP_SEC: '3601' })).rejects.toThrow(/3600/)+ })++ it('fails loud when the resync interval exceeds the 3600s cap (M-C timer overflow)', async () => {+ await expect(+ loadConfig({+ HCC_EXTERNAL_EGRESS_RESYNC_SEC: '3601',+ HCC_EXTERNAL_EGRESS_OVERLAP_SEC: '3600',+ })+ ).rejects.toThrow(/3600/)+ })++ it('accepts the cadence knobs exactly at the 3600s cap', async () => {+ const { config } = await loadConfig({+ HCC_EXTERNAL_EGRESS_RESYNC_SEC: '1800',+ HCC_EXTERNAL_EGRESS_OVERLAP_SEC: '3600',+ })+ expect(config.externalEgressOverlapSec).toBe(3600)+ expect(config.externalEgressResyncIntervalSec).toBe(1800)+ })++ it('fails loud when max entries exceed the 4096 cap (M-C annotation-size bound)', async () => {+ await expect(loadConfig({ HCC_EXTERNAL_EGRESS_MAX_ENTRIES: '4097' })).rejects.toThrow(/4096/)+ })++ it('accepts max entries exactly at the 4096 cap', async () => {+ const { config } = await loadConfig({ HCC_EXTERNAL_EGRESS_MAX_ENTRIES: '4096' })+ expect(config.externalEgressMaxEntries).toBe(4096)+ })})diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.tsindex 10030d05f..2aa403dd0 100644--- a/host-context-controller/src/config.ts+++ b/host-context-controller/src/config.ts@@ -390,6 +390,15 @@ validateRemovedStatelessCommunicationChannelPolicy(* 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.*/+// Upper bounds (audit M-C, port of commit 3f968956). The one-hour cadence+// ceiling keeps every timer far below Node's signed-32-bit setTimeout limit+// (2^31-1 ms ≈ 24.8 days) — an unbounded seconds value multiplied to ms would+// overflow and Node clamps it to 1ms, turning the self-rescheduling resync into+// a back-to-back DNS hot loop. The 4096 entry ceiling bounds the serialized+// state annotation and matches WRC's accumulator contract.+const MAX_EXTERNAL_EGRESS_CADENCE_SEC = 60 * 60+const MAX_EXTERNAL_EGRESS_MAX_ENTRIES = 4096+export function validateExternalEgressResyncInvariant(cfg: {externalEgressResyncIntervalSec: numberexternalEgressOverlapSec: number@@ -401,24 +410,31 @@ export function validateExternalEgressResyncInvariant(cfg: {const floor = cfg.externalEgressRefreshFloorSecconst max = cfg.externalEgressMaxEntries- if (!Number.isInteger(overlap) || overlap <= 0) {+ if (!Number.isInteger(overlap) || overlap <= 0 || overlap > MAX_EXTERNAL_EGRESS_CADENCE_SEC) {throw new Error(- `HCC_EXTERNAL_EGRESS_OVERLAP_SEC must be a positive integer (seconds), got '${overlap}'`+ `HCC_EXTERNAL_EGRESS_OVERLAP_SEC must be an integer between 1 and ` ++ `${MAX_EXTERNAL_EGRESS_CADENCE_SEC} (seconds), got '${overlap}'`)}- if (!Number.isInteger(floor) || floor < 1) {+ if (!Number.isInteger(floor) || floor < 1 || floor > MAX_EXTERNAL_EGRESS_CADENCE_SEC) {throw new Error(- `HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC must be an integer >= 1 (seconds), got '${floor}'`+ `HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC must be an integer between 1 and ` ++ `${MAX_EXTERNAL_EGRESS_CADENCE_SEC} (seconds), got '${floor}'`)}- if (!Number.isInteger(max) || max < 1) {- throw new Error(`HCC_EXTERNAL_EGRESS_MAX_ENTRIES must be an integer >= 1, got '${max}'`)+ if (!Number.isInteger(max) || max < 1 || max > MAX_EXTERNAL_EGRESS_MAX_ENTRIES) {+ throw new Error(+ `HCC_EXTERNAL_EGRESS_MAX_ENTRIES must be an integer between 1 and ` ++ `${MAX_EXTERNAL_EGRESS_MAX_ENTRIES}, 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) {+ // The upper cap (M-C) prevents a signed-32-bit setTimeout overflow.+ if (!Number.isInteger(interval) || interval < 0 || interval > MAX_EXTERNAL_EGRESS_CADENCE_SEC) {throw new Error(- `HCC_EXTERNAL_EGRESS_RESYNC_SEC must be an integer >= 0 (0 disables), got '${interval}'`+ `HCC_EXTERNAL_EGRESS_RESYNC_SEC must be an integer between 0 and ` ++ `${MAX_EXTERNAL_EGRESS_CADENCE_SEC} (0 disables), got '${interval}'`)}// interval 0 disables periodic resync; only enforce ordering when enabled.diff --git a/host-context-controller/src/egressSignature.test.ts b/host-context-controller/src/egressSignature.test.tsindex f31ce3600..1ce59e1a6 100644--- a/host-context-controller/src/egressSignature.test.ts+++ b/host-context-controller/src/egressSignature.test.ts@@ -36,4 +36,27 @@ describe('egressSignature (issue #299 audit H1/R2-1)', () => {])expect(egressSignature(a)).not.toBe(egressSignature(b))})++ // H-C: the signature projects podSelector + policyTypes, not just spec.egress,+ // so an out-of-band drift with identical destination rules re-owns the policy.+ const sameEgress = [+ { to: [{ ipBlock: { cidr: '1.2.3.4/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },+ ]+ const withSpec = (podSelector: unknown, policyTypes: string[]): k8s.V1NetworkPolicy =>+ ({ spec: { podSelector, policyTypes, egress: sameEgress } }) as k8s.V1NetworkPolicy++ it('H-C: DETECTS a podSelector drift even when egress rules are identical', () => {+ expect(egressSignature(withSpec({ matchLabels: { app: 'scanner' } }, ['Egress']))).not.toBe(+ egressSignature(withSpec({ matchLabels: { app: 'attacker' } }, ['Egress']))+ )+ })++ it('H-C: DETECTS a policyTypes change but is order-insensitive', () => {+ expect(egressSignature(withSpec({}, ['Egress']))).not.toBe(+ egressSignature(withSpec({}, ['Egress', 'Ingress']))+ )+ expect(egressSignature(withSpec({}, ['Egress', 'Ingress']))).toBe(+ egressSignature(withSpec({}, ['Ingress', 'Egress']))+ )+ })})diff --git a/host-context-controller/src/externalEgressAccumulator.ts b/host-context-controller/src/externalEgressAccumulator.tsindex 4e22ad9fa..cbe124868 100644--- a/host-context-controller/src/externalEgressAccumulator.ts+++ b/host-context-controller/src/externalEgressAccumulator.ts@@ -82,7 +82,12 @@ export function accumulateHostExactHostEgress(): AccumulateHostEgressOutput {const { fqdn, port, protocol, resolution, previousAnnotations, now, config } = input- const previous = previousAnnotations ? parseState(previousAnnotations, now, config) : emptyState()+ // This policy owns exactly one exact-host binding, so its declared identity is+ // (fqdn,port,protocol). Pass it so a legacy (portless) migration keeps that+ // port instead of guessing 443 and drops any other stale FQDN (H-B).+ const previous = previousAnnotations+ ? parseState(previousAnnotations, now, config, [{ fqdn, port, protocol }])+ : emptyState()let observation: Observationif (resolution.kind === 'ok') {diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.tsindex e8cb7865e..8778887cd 100644--- a/host-context-controller/src/networkPolicyReconciler.ts+++ b/host-context-controller/src/networkPolicyReconciler.ts@@ -131,12 +131,23 @@ function canonicalize(value: unknown): unknown {* (deep key-sorted) JSON of `spec.egress`. Decides whether a write is needed* WITHOUT the key-ordering fragility of a raw JSON.stringify (audit R2-1). Unlike* the earlier tuple-only signature (ipBlock cidr/port), this captures the FULL- * rule including selector-based `to` entries (audit H1). HCC external-egress- * policies are ipBlock-only today, so H1 does not bite here, but this keeps the- * gate correct and mirrors WRC's `egressSignature`.+ * rule including selector-based `to` entries (audit H1). It also projects+ * `podSelector` and `policyTypes` (audit H-C), not just `spec.egress`, so a+ * policy whose selector or policy types drifted out-of-band (same destination+ * rules) counts as changed and the reconcile re-owns it instead of leaving+ * egress applied to the wrong pods. `policyTypes` is order-insensitive (sorted).+ * HCC external-egress policies are ipBlock-only today, so H1 does not bite here,+ * but this keeps the gate correct and mirrors WRC's `egressSignature`.*/export function egressSignature(policy: k8s.V1NetworkPolicy): string {- return JSON.stringify(canonicalize(policy.spec?.egress ?? []))+ const spec = policy.spec+ return JSON.stringify(+ canonicalize({+ podSelector: spec?.podSelector ?? {},+ policyTypes: [...(spec?.policyTypes ?? [])].sort(),+ egress: spec?.egress ?? [],+ })+ )}function isPublicDnsHostname(host: string): boolean {@@ -863,6 +874,11 @@ export class NetworkPolicyReconciler {// (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 = false+ // H-E: a rename onto the same ip/port is spec-identical, so the rendered+ // egress gate would skip it and discard the re-attributed state annotation.+ // accumulated.changed is over (fqdn,ip,port,protocol), so it forces the+ // write that re-persists the identity and preserves the overlap grace.+ let egressStateChanged = falseconst name = this.externalEgressPolicyName(server.name, binding)if (!name) {failures.push('exact-host external egress bindings must declare dns or cidr')@@ -1023,6 +1039,7 @@ export class NetworkPolicyReconciler {cidrs = accumulated.cidrs.filter(c => isAllowedExternalEgressCidr(c))stateAnnotations = accumulated.annotationsegressRenewalDue = accumulated.renewalDue+ egressStateChanged = accumulated.changedresolvedEgressIPs.push({dns: binding.dns,ips: cidrs.map(cidr => cidr.replace(/\/32$/, '')),@@ -1061,6 +1078,7 @@ export class NetworkPolicyReconciler {// 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+ egressStateChanged = accumulated.changedresolvedEgressIPs.push({dns: binding.dns,ips: cidrs.map(cidr => cidr.replace(/\/32$/, '')),@@ -1107,7 +1125,11 @@ export class NetworkPolicyReconciler {// 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) {+ if (+ this.externalEgressWriteNeeded(existingPolicy, policy) ||+ egressRenewalDue ||+ egressStateChanged+ ) {await applyNetworkPolicy(this.networkingApi, name, server.namespace, policy, '[NetPol]')} else {console.log(`[NetPol] External egress "${name}" unchanged — no-op (issue #299 no-churn)`)diff --git a/packages/network-policy-core/index.cjs b/packages/network-policy-core/index.cjsindex fe944bcaf..b2373e8b8 100644Binary files a/packages/network-policy-core/index.cjs 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.tsindex d0a99cb03..3390617a0 100644--- a/packages/network-policy-core/index.d.ts+++ b/packages/network-policy-core/index.d.ts@@ -112,11 +112,18 @@ export declare function serializeState(state: EgressState): Record<string, strin* 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.+ *+ * `declarations` (H-B): the currently-declared external targets. The legacy+ * annotation is portless, so when supplied, each migrated entry takes the+ * port/protocol of its current declaration (not a guessed 443/TCP) and pairs for+ * no-longer-declared FQDNs are dropped. Omit it only from callers that cannot+ * supply the declarations, which then fall back to the historical 443/TCP grace.*/export declare function parseState(annotations: Record<string, string>,now: number,- config: EgressCoreConfig+ config: EgressCoreConfig,+ declarations?: ReadonlyArray<{ fqdn: string; port: number; protocol?: string }>): EgressStateexport declare const STATE_ANNOTATION: stringdiff --git a/packages/network-policy-core/index.test.cjs b/packages/network-policy-core/index.test.cjsindex 48a432909..6312ce88c 100644--- a/packages/network-policy-core/index.test.cjs+++ b/packages/network-policy-core/index.test.cjs@@ -333,3 +333,100 @@ test('classifyDnsError defaults unknown/undefined codes to permanent (matches WRassert.equal(core.classifyDnsError('ESOMETHINGWEIRD'), 'permanent')assert.equal(core.classifyDnsError(new Error('no code')), 'permanent')})++// ─── H-A: revocation/freeze keyed by (fqdn,port,protocol), not fqdn alone ──────+// The state map is keyed by (fqdn,ip,port,protocol) but classification used to be+// keyed by fqdn only, so an entry whose declared PORT was removed survived under+// the still-declared fqdn's `ok` branch (and was frozen forever under a transient+// failure). Revocation must track the full declared identity.+test('H-A: changing a declared port REVOKES the old-port entry immediately', () => {+ let s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['1.2.3.4'], TTL, 443)], 1000, CFG)+ .state+ assert.deepEqual(+ s.entries.map(e => `${e.ip}:${e.port}`),+ ['1.2.3.4:443']+ )+ // gh is re-declared on 8443 ONLY (443 removed); same IP resolves.+ const out = core.reconcileEgressState(s, [obsOk('gh', ['1.2.3.4'], TTL, 8443)], 2000, CFG)+ assert.deepEqual(+ out.entries.map(e => `${e.ip}:${e.port}`).sort(),+ ['1.2.3.4:8443'],+ 'the removed port 443 must be revoked; only the still-declared 8443 remains'+ )+})++test('H-A: a removed port is revoked even while the still-declared port DNS-fails', () => {+ const s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['1.2.3.4'], TTL, 443)], 1000, CFG)+ .state+ // 443 removed from the spec; 8443 declared but DNS transiently failing.+ const out = core.reconcileEgressState(s, [obsTransient('gh', 8443)], 2000, CFG)+ assert.deepEqual(+ out.entries.map(e => `${e.ip}:${e.port}`),+ [],+ 'the removed 443 identity is revoked; the transient freeze only protects the declared 8443'+ )+})++test('H-A: a transient failure still freezes the SAME declared identity', () => {+ const s = core.reconcileEgressState(core.emptyState(), [obsOk('gh', ['1.2.3.4'], TTL, 443)], 1000, CFG)+ .state+ // gh:443 is still declared; DNS transiently fails → freeze, do not prune.+ const out = core.reconcileEgressState(s, [obsTransient('gh', 443)], 2000, CFG)+ assert.deepEqual(+ out.entries.map(e => `${e.ip}:${e.port}`),+ ['1.2.3.4:443'],+ 'the declared identity is frozen (H1) while its own DNS fails'+ )+ assert.deepEqual(out.frozenFqdns, ['gh'])+})++// ─── H-B: legacy migration derives port/protocol from the declaration ─────────+// The portless `egress-fqdn-targets` legacy annotation must migrate to the port+// the target is CURRENTLY declared on, not a guessed 443/TCP, and must drop pairs+// for FQDNs that are no longer declared.+test('H-B: legacy targets migrate to the DECLARED port, not a guessed 443', () => {+ const legacy = { [core.TARGETS_ANNOTATION]: 'db.example.com=10.0.0.5/32' }+ const declarations = [{ fqdn: 'db.example.com', port: 5432 }]+ const back = core.parseState(legacy, 1000, CFG, declarations)+ assert.deepEqual(+ back.entries.map(e => `${e.ip}:${e.port}`),+ ['10.0.0.5:5432'],+ 'migrated at the declared 5432, NOT widened to 443'+ )+})++test('H-B: legacy targets for an UNDECLARED fqdn are dropped', () => {+ const legacy = {+ [core.TARGETS_ANNOTATION]: 'gone.example.com=10.0.0.9/32,db.example.com=10.0.0.5/32',+ }+ const declarations = [{ fqdn: 'db.example.com', port: 5432 }]+ const back = core.parseState(legacy, 1000, CFG, declarations)+ assert.deepEqual(+ back.entries.map(e => `${e.fqdn}:${e.port}`),+ ['db.example.com:5432'],+ 'the undeclared gone.example.com is dropped; only the declared db survives'+ )+})++test('H-B: without declarations, legacy falls back to the historical 443 grace', () => {+ const legacy = { [core.TARGETS_ANNOTATION]: 'gh=140.82.112.3/32' }+ const back = core.parseState(legacy, 1000, CFG)+ assert.deepEqual(back.entries.map(e => `${e.ip}:${e.port}`), ['140.82.112.3:443'])+})++// M-C prong 2: the serialized state annotation must stay under the byte budget+// regardless of FQDN length. A fixed entry-count cap cannot bound bytes (a+// 253-char FQDN serializes ~5× a short one); an oversized annotation 422s at the+// apiserver and loops the reconcile.+test('M-C byte cap: the serialized state never exceeds the byte budget', () => {+ const longFqdn = `${'a'.repeat(240)}.example.com` // ~252 chars+ const bigCfg = { overlapMs: 300_000, maxEntries: 4096 } // count cap won't bite first+ // 900 distinct /32s under the long FQDN ≈ ~300KB if all kept — over the 200KB budget.+ const ips = Array.from({ length: 900 }, (_, i) => `10.${Math.floor(i / 256)}.${i % 256}.1`)+ const out = core.reconcileEgressState(core.emptyState(), [obsOk(longFqdn, ips, TTL, 443)], 1000, bigCfg)+ const bytes = core.serializeState(out.state)[core.STATE_ANNOTATION].length+ assert.ok(bytes <= 200 * 1000, `serialized state is ${bytes} bytes, must be <= 200000`)+ assert.ok(out.entries.length > 0, 'not everything was evicted')+ assert.ok(out.entries.length < 900, 'byte-budget eviction dropped the overflow')+ assert.equal(out.overCap, true, 'overCap flags the eviction for the alarm/metric')+})diff --git a/packages/network-policy-core/package-lock.json b/packages/network-policy-core/package-lock.jsonnew file mode 100644index 000000000..f9f7db1a4--- /dev/null+++ b/packages/network-policy-core/package-lock.json@@ -0,0 +1,13 @@+{+ "name": "@clerum/network-policy-core",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@clerum/network-policy-core",+ "version": "0.1.0",+ "license": "MIT"+ }+ }+}diff --git a/scripts/minikube/pre-gate-sync.sh b/scripts/minikube/pre-gate-sync.shindex f95ba0601..bbad658bb 100755--- a/scripts/minikube/pre-gate-sync.sh+++ b/scripts/minikube/pre-gate-sync.sh@@ -395,6 +395,7 @@ cluster_fingerprint="$(fingerprint_dir mcp-hostfingerprint_dir host-context-controllerfingerprint_dir packages/workflow-runtime-core+ fingerprint_dir packages/network-policy-corefingerprint_dir workflow-recipesfingerprint_dir packages/workflow-sdkfingerprint_dir tests/e2e/fixtures/custom-workflow-coordinator@@ -431,6 +432,9 @@ firun_if_changed packages/workflow-runtime-core "npm test && npm run build"ensure_artifact packages/workflow-runtime-core dist/index.js "npm run build"+# @clerum/network-policy-core is a file: dependency of workflow-recipes and+# host-context-controller (issue #299). Run its node:test suite when it changes.+run_if_changed packages/network-policy-core "npm test"run_if_changed control-api "npm test"run_if_changed external-rest-api "npm test"run_if_changed rpc-proxy "npm test"diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex 97d4c06c6..cf09c2004 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.283",+ "version": "0.1.284","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.283",+ "version": "0.1.284","license": "SEE LICENSE IN LICENSE","dependencies": {"@aws-sdk/client-s3": "^3.1009.0",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex fb6c2bd50..b891d68e4 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.283",+ "version": "0.1.284","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/reconciler/egressSignature.test.ts b/workflow-recipes/src/reconciler/egressSignature.test.tsindex a8ce8e4bd..2f8e29466 100644--- a/workflow-recipes/src/reconciler/egressSignature.test.ts+++ b/workflow-recipes/src/reconciler/egressSignature.test.ts@@ -69,4 +69,32 @@ describe('egressSignature (issue #299 audit H1/R2-1)', () => {egressSignature({ spec: { podSelector: {}, policyTypes: ['Egress'] } } as k8s.V1NetworkPolicy))})++ // H-C: the signature must project the FULL managed enforcement spec, not just+ // spec.egress — a policy whose podSelector or policyTypes drifted out-of-band+ // (same destination rules) must be treated as changed so the reconcile re-owns+ // it, instead of leaving external egress applied to the wrong pods.+ const sameEgress = [+ { to: [{ ipBlock: { cidr: '1.2.3.4/32' } }], ports: [{ protocol: 'TCP', port: 443 }] },+ ]+ const withSpec = (podSelector: unknown, policyTypes: string[]): k8s.V1NetworkPolicy =>+ ({ spec: { podSelector, policyTypes, egress: sameEgress } }) as k8s.V1NetworkPolicy++ it('H-C: DETECTS a podSelector drift even when egress rules are identical', () => {+ expect(egressSignature(withSpec({ matchLabels: { app: 'scanner' } }, ['Egress']))).not.toBe(+ egressSignature(withSpec({ matchLabels: { app: 'attacker' } }, ['Egress']))+ )+ })++ it('H-C: DETECTS a policyTypes change even when egress rules are identical', () => {+ expect(egressSignature(withSpec({}, ['Egress']))).not.toBe(+ egressSignature(withSpec({}, ['Egress', 'Ingress']))+ )+ })++ it('H-C: policyTypes order does not matter (Egress,Ingress == Ingress,Egress)', () => {+ expect(egressSignature(withSpec({}, ['Egress', 'Ingress']))).toBe(+ egressSignature(withSpec({}, ['Ingress', 'Egress']))+ )+ })})diff --git a/workflow-recipes/src/reconciler/externalEgressAccumulator.test.ts b/workflow-recipes/src/reconciler/externalEgressAccumulator.test.tsindex 1b915c92b..c9a6d7426 100644--- a/workflow-recipes/src/reconciler/externalEgressAccumulator.test.ts+++ b/workflow-recipes/src/reconciler/externalEgressAccumulator.test.ts@@ -243,6 +243,30 @@ describe('accumulateExternalEgress — H4 no-op', () => {expect(out.changed).toBe(false)expect(out.resolved.map(r => r.cidr)).toEqual(['160.79.104.10/32'])})++ // H-E: a rename onto the SAME ip/port renders an identical ipBlock, so the+ // reconciler's egress-signature gate alone would skip the write and discard the+ // re-attributed state. The accumulator must report changed=true (the signal the+ // gate now also consumes) and persist the IP under the NEW fqdn, so a later+ // rotation of the new name keeps the carried-over IP's overlap grace.+ it('H-E: a rename onto the same IP/port reports changed=true and re-attributes state', () => {+ const prev = previousAnnotations(+ [{ fqdn: 'old.example.com', port: 443, ip: '1.2.3.4', ttlSeconds: 300 }],+ NOW+ )+ const out = accumulateExternalEgress({+ externals: [{ fqdn: 'new.example.com', port: 443 }],+ resolveResult: okResolve([+ { fqdn: 'new.example.com', port: 443, ip: '1.2.3.4', ttlSeconds: 300 },+ ]),+ previousAnnotations: prev,+ now: NOW + 10_000,+ config: CONFIG,+ })+ expect(out.changed).toBe(true)+ expect(out.resolved.map(r => r.cidr)).toEqual(['1.2.3.4/32'])+ expect(out.entries.map(e => e.fqdn)).toEqual(['new.example.com'])+ })})describe('accumulateExternalEgress — H5 rehydration', () => {diff --git a/workflow-recipes/src/reconciler/externalEgressAccumulator.ts b/workflow-recipes/src/reconciler/externalEgressAccumulator.tsindex c3b16d50b..2effbc5a9 100644--- a/workflow-recipes/src/reconciler/externalEgressAccumulator.ts+++ b/workflow-recipes/src/reconciler/externalEgressAccumulator.ts@@ -139,7 +139,11 @@ function buildObservations(export function accumulateExternalEgress(input: AccumulateInput): AccumulateOutput {const { externals, resolveResult, previousAnnotations, now, config } = input- const previous = previousAnnotations ? parseState(previousAnnotations, now, config) : emptyState()+ // Pass the declared externals so a legacy (portless) migration takes the+ // current declared port, not a guessed 443, and drops undeclared FQDNs (H-B).+ const previous = previousAnnotations+ ? parseState(previousAnnotations, now, config, externals)+ : emptyState()const observations = buildObservations(externals, resolveResult)const out = reconcileEgressState(previous, observations, now, config)diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.tsindex cad439386..92f58a0d0 100644--- a/workflow-recipes/src/reconciler/reconciler.test.ts+++ b/workflow-recipes/src/reconciler/reconciler.test.ts@@ -3841,6 +3841,61 @@ describe('WorkflowRecipeReconciler', () => {expect(npCall.body.spec.egress).toHaveLength(2) // internal + external})+ // H-E (audit): a rename of the external FQDN onto the SAME resolved IP/port+ // renders identical spec.egress, so the egress-signature gate alone would no-op+ // and discard the re-attributed state annotation. acc.changed must force the+ // write. This guards the reconciler WIRING of egressStateChanged (the closing+ // Fable cert flagged the gate term as untested). Uses the reconciler's own+ // first-reconcile output as the live policy — no hand-built fixture.+ it('R.8.24 — H-E: renaming the external FQDN onto the same IP re-persists the policy', async () => {+ const kc = new k8s.KubeConfig()+ const rec = new WorkflowRecipeReconciler(kc, undefined, {+ fqdnLookup: async () => ({ kind: 'ok', ipv4: ['93.184.216.10'], ipv6: [], ttlSeconds: 300 }),+ })+ const uiWith = (fqdn: string) =>+ makeRecipe({+ spec: {+ workloads: [{ id: 'frontend', type: 'deployment', image: 'fe:1', port: 8080 }],+ ui: {+ workloadRef: 'frontend',+ port: 8080,+ egress: { external: [{ fqdn, port: 443 }] },+ },+ },+ })++ // First reconcile authors the live ui-egress policy (IP pinned under old fqdn).+ await rec.reconcile(uiWith('old.example.com'))+ const p1 = mockNetworkingApi.createNamespacedNetworkPolicy.mock.calls+ .map(c => c[0].body)+ .find(b => b?.metadata?.name === 'ui-egress-test-recipe')+ expect(p1).toBeTruthy()++ // That policy is now live; the next reconcile renames the FQDN onto the SAME IP.+ mockNetworkingApi.readNamespacedNetworkPolicy.mockImplementation(({ name }: { name: string }) =>+ Promise.resolve(+ name === 'ui-egress-test-recipe' ? p1 : { metadata: { name, resourceVersion: '1' } }+ )+ )+ mockNetworkingApi.createNamespacedNetworkPolicy.mockClear()+ mockNetworkingApi.replaceNamespacedNetworkPolicy.mockClear()++ await rec.reconcile(uiWith('new.example.com'))++ const wroteUiEgress =+ mockNetworkingApi.createNamespacedNetworkPolicy.mock.calls.some(+ c => c[0]?.body?.metadata?.name === 'ui-egress-test-recipe'+ ) ||+ mockNetworkingApi.replaceNamespacedNetworkPolicy.mock.calls.some(+ c =>+ c[0]?.name === 'ui-egress-test-recipe' ||+ c[0]?.body?.metadata?.name === 'ui-egress-test-recipe'+ )+ // Rendered egress is byte-identical (same /32, same port); only acc.changed+ // (old→new attribution) forces this write. Reverting the gate term no-ops it.+ expect(wroteUiEgress).toBe(true)+ })+it('fails sandbox UI external egress in required mode when cluster enforcement is not confirmed', async () => {const recipe = makeRecipe({spec: {diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.tsindex f8f9cf79d..f5eff8278 100644--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts@@ -660,11 +660,23 @@ function canonicalize(value: unknown): unknown {* and would defeat the no-churn gate. Unlike the earlier tuple-only signature,* this captures the FULL rule — including `namespaceSelector`/`podSelector` `to`* entries for internal/cluster-local egress (audit H1): a tuple signature over- * ipBlock only was blind to selector changes, stranding a stale policy. Mirrors- * HCC's `egressSignature`.+ * ipBlock only was blind to selector changes, stranding a stale policy.+ *+ * It also projects `podSelector` and `policyTypes` (audit H-C), not just+ * `spec.egress`: a policy whose selector or policy types drifted out-of-band —+ * with the same destination rules — must count as changed so the reconcile+ * re-owns it, rather than leaving external egress applied to the wrong pods.+ * `policyTypes` is order-insensitive (sorted). Mirrors HCC's `egressSignature`.*/export function egressSignature(policy: k8s.V1NetworkPolicy): string {- return JSON.stringify(canonicalize(policy.spec?.egress ?? []))+ const spec = policy.spec+ return JSON.stringify(+ canonicalize({+ podSelector: spec?.podSelector ?? {},+ policyTypes: [...(spec?.policyTypes ?? [])].sort(),+ egress: spec?.egress ?? [],+ })+ )}export class WorkflowRecipeReconciler {@@ -3967,6 +3979,12 @@ export class WorkflowRecipeReconciler {let stateAnnotations: Record<string, string> | undefinedlet existing: k8s.V1NetworkPolicy | null = nulllet egressRenewalDue = false+ // H-E: the write gate compares rendered spec.egress (ipBlock cidr+port, no+ // fqdn), so a rename old.example.com→new.example.com onto the SAME ip/port is+ // spec-identical and would be skipped, discarding the re-attributed state+ // annotation and losing the overlap grace when the new name later rotates.+ // acc.changed is over (fqdn,ip,port,protocol), so it catches the rename.+ let egressStateChanged = 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).@@ -4007,6 +4025,7 @@ export class WorkflowRecipeReconciler {)stateAnnotations = acc.annotationsegressRenewalDue = acc.renewalDue+ egressStateChanged = acc.changedthis.assertClusterEnforcesExternalEgress(recipe,@@ -4034,7 +4053,7 @@ export class WorkflowRecipeReconciler {// 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) {+ if (!this.egressWriteNeeded(existing, policy) && !egressRenewalDue && !egressStateChanged) {console.log(`[WR-Reconciler] NetworkPolicy "${policyName}" in ${ns} egress set unchanged — no-op`)@@ -4418,6 +4437,7 @@ export class WorkflowRecipeReconciler {let wlStateAnnotations: Record<string, string> | undefinedlet existingWlPolicy: k8s.V1NetworkPolicy | null = nulllet wlEgressRenewalDue = false+ let wlEgressStateChanged = false // H-E: catch fqdn-attribution-only changesconst wlPolicyName = rb.workloadEgressPolicyName(recipe.metadata.name, w.id)if (externalDeclared.length > 0) {// issue #299: accumulate the sliding-window egress set (rehydrate H5).@@ -4446,6 +4466,7 @@ export class WorkflowRecipeReconciler {)wlStateAnnotations = acc.annotationswlEgressRenewalDue = acc.renewalDue+ wlEgressStateChanged = acc.changedthis.assertClusterEnforcesExternalEgress(recipe,@@ -4466,7 +4487,11 @@ export class WorkflowRecipeReconciler {}// 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) {+ if (+ !this.egressWriteNeeded(existingWlPolicy, policy) &&+ !wlEgressRenewalDue &&+ !wlEgressStateChanged+ ) {console.log(`[WR-Reconciler] NetworkPolicy "${wlPolicyName}" in ${wlNs} egress set unchanged — no-op`)