Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(egress): defer the #513 fault so cleanup still de-authorizes removed bindings
Alfredo Lopez7297c9167739
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 677db12b5..aa4238fa6 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.286",+ "version": "0.1.287","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.286",+ "version": "0.1.287","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 2bc819451..53fc757ae 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.286",+ "version": "0.1.287","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/networkPolicyReconciler.egressClassification.test.ts b/host-context-controller/src/networkPolicyReconciler.egressClassification.test.tsindex 43b240ade..7bb699535 100644--- a/host-context-controller/src/networkPolicyReconciler.egressClassification.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.egressClassification.test.ts@@ -277,6 +277,48 @@ describe('#513: a non-DNS exception inside the resolve block is not a DNS conditexpect(egress.at(-1)?.reason).toBe('ExternalEgressRejected')})+ it("T6 still deletes a de-authorized binding's policy when a sibling binding faults", async () => {+ // Fail-loud must not cost fail-closed. `cleanupExternalEgress` runs AFTER the+ // binding loop and is the only place that deletes policies for bindings no+ // longer in the spec, so throwing from inside the loop skips it: a+ // destination the operator explicitly removed keeps its /32 allowed for as+ // long as an unrelated sibling keeps faulting — and the fault path retries+ // every 30s, so "as long as" means indefinitely.+ //+ // The file already has the right shape for this: `failures[]` accumulates,+ // the loop finishes, the cleanup runs, and only then does it write status and+ // throw. The fault path must follow that contract rather than invent a+ // parallel exit.+ const bindings = (dns: string[]): McpServerCRD => ({+ ...server,+ spec: { ...server.spec, egressBindings: dns.map(d => ({ dns: d, port: 443 })) },+ })++ await reconciler.reconcileExternalEgress(bindings(['a.example.com', 'b.example.com']), {+ isCurrent: () => true,+ })+ const written = mockApi.createNamespacedNetworkPolicy.mock.calls.map(+ call => (call[0] as { body: k8s.V1NetworkPolicy }).body+ )+ expect(written).toHaveLength(2)++ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({+ items: written.map(body => ({ metadata: { ...body.metadata }, spec: body.spec })),+ })+ mockApi.createNamespacedNetworkPolicy.mockClear()+ mockApi.deleteNamespacedNetworkPolicy.mockClear()++ // The operator removes a.example.com; b.example.com faults after resolution.+ injectPostResolutionTypeError()+ await expect(+ reconciler.reconcileExternalEgress(bindings(['b.example.com']), { isCurrent: () => true })+ ).rejects.toThrow(TypeError)++ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'ext-egress-classify-mcp-a.example.com-443' })+ )+ })+it('T5 keeps freezing the lapsed window on a real transient resolver code', async () => {// The gate has two exemptions and this pins the one the other tests do not// touch. Deleting `kind !== 'transient'` from the condition turns every@@ -306,11 +348,16 @@ describe('#513: a non-DNS exception inside the resolve block is not a DNS conditit("T4 treats EBADNAME as the operator's malformed name, not as a controller fault", async () => {// EBADNAME is a POSITIVE verdict about the name: c-ares refused to send the- // query at all. It is reachable from user input — the CRD pattern for- // `egressBindings[].dns` admits consecutive dots and labels over 63 octets —- // so it belongs with NXDOMAIN: prune and reject. Blaming the controller with- // ExternalEgressReconcileFailed would send the operator hunting through our- // logs for their own typo.+ // query at all, so it belongs with NXDOMAIN — prune and reject. Blaming the+ // controller with ExternalEgressReconcileFailed would send the operator+ // hunting through our logs for their own typo.+ //+ // This controller cannot currently produce EBADNAME from its own CRD field:+ // isPublicDnsHostname rejects `..` and 64-octet labels before we resolve, so+ // the injection here is synthetic. The classification is still HCC's to get+ // right — PERMANENT_DNS_CODES is shared with WRC, whose ui lane does reach+ // c-ares on the CRD pattern alone, and a validator is a weaker guarantee than+ // a gate that classifies correctly whatever arrives.await seedAccumulatedPolicy({ lapsed: true })resolve4Mock.mockRejectedValueOnce(Object.assign(new Error('queryA EBADNAME api.example.com'), { code: 'EBADNAME' })diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.tsindex baa9b392d..aa1825498 100644--- a/host-context-controller/src/networkPolicyReconciler.ts+++ b/host-context-controller/src/networkPolicyReconciler.ts@@ -2064,6 +2064,10 @@ export class NetworkPolicyReconciler {const desiredPolicyNames = new Set<string>()const resolvedEgressIPs: McpServerResolvedEgressIP[] = []const failures: string[] = []+ // Issue #513: faults that are NOT a DNS condition. Kept separate from+ // `failures` because those are rejected INPUT (the operator's) while these are+ // OUR bug, and the two earn different reasons and different messages.+ const reconcileFaults: Array<{ dns: string; err: unknown }> = []const resolvedAtMs = Date.now()const resolvedAt = new Date(resolvedAtMs).toISOString()@@ -2243,23 +2247,43 @@ export class NetworkPolicyReconciler {// at the resolver while the fault is here. Transient codes are positive// by construction (TRANSIENT_DNS_CODES); 'permanent' is positive only for// PERMANENT_DNS_CODES — the two no-records answers plus EBADNAME, a name- // c-ares refuses to query. EBADNAME passes the CRD pattern (`..`,- // 64-octet labels) and is the operator's misconfiguration, so it must- // keep pruning and reporting ExternalEgressRejected rather than blame- // the controller.+ // c-ares refuses to query. EBADNAME cannot arrive from this controller's+ // own CRD field (isPublicDnsHostname rejects `..` and 64-octet labels+ // before we resolve), but the set is shared with WRC, whose ui lane+ // validates the fqdn with the CRD pattern alone; there it IS the+ // operator's misconfiguration, and it must keep pruning and reporting+ // ExternalEgressRejected rather than blame the controller.+ //+ // `code` is read off any object, exactly as classifyDnsError does: a+ // rejection that is not an Error instance must not be reclassified as a+ // controller fault just because of how it was thrown.const kind = classifyDnsError(err)- const code = err instanceof Error ? (err as NodeJS.ErrnoException).code : undefined+ const code =+ typeof err === 'object' && err !== null+ ? (err as NodeJS.ErrnoException).code+ : undefinedif (kind !== 'transient' && !isPermanentDnsCode(code)) {- if (!isCurrent()) return- await this.writeExternalEgressStatus(- server,- resolvedEgressIPs,- 'False',- 'ExternalEgressReconcileFailed',- `External egress reconciliation failed on binding "${binding.dns}" with a non-DNS error (not a resolver condition, accumulated egress left untouched): ${this.errorMessage(err)}`,- isCurrent+ // Log before anything that can throw. writeExternalEgressStatus fails+ // on a stale uid/generation or a rejected patch, and the isCurrent+ // fence below returns without a word — either would swallow the very+ // fault this branch exists to surface.+ console.error(+ `[NetPol] External egress reconcile fault on binding "${binding.dns}" for "${server.name}" (not a DNS condition):`,+ err)- throw err+ // Recorded, not thrown: the throw is deferred to after the loop so+ // cleanupExternalEgress still runs. It is the only place that deletes+ // policies for bindings the operator removed from the spec, and+ // desiredPolicyNames is only complete once the loop ends. Throwing+ // here would leave a de-authorized destination allowed for as long as+ // the fault persists — fail-loud paid for with fail-open.+ // Still DESIRED: the binding is declared, we simply could not+ // reconcile it this pass. Without this the cleanup below would read+ // the omission as "the operator removed it" and delete the very+ // policy this branch promises to leave untouched.+ desiredPolicyNames.add(name)+ reconcileFaults.push({ dns: binding.dns ?? '(unnamed binding)', err })+ continue}const accumulated = accumulateHostExactHostEgress({fqdn: binding.dns,@@ -2348,6 +2372,29 @@ export class NetworkPolicyReconciler {}if (!isCurrent()) return+ // Issue #513: a controller fault outranks rejected input. `failures` means the+ // spec asked for something we refuse to enforce; a fault means we cannot trust+ // what we just enforced at all, so it is the condition the operator must see.+ // Reported only after cleanupExternalEgress above, so a binding removed from+ // the spec is still de-authorized on a pass that ends in a fault.+ if (reconcileFaults.length > 0) {+ const first = reconcileFaults[0]+ const message =+ `External egress reconciliation failed on binding "${first.dns}" with a non-DNS error ` ++ `(not a resolver condition, accumulated egress left untouched): ${this.errorMessage(first.err)}`+ await this.writeExternalEgressStatus(+ server,+ resolvedEgressIPs,+ 'False',+ 'ExternalEgressReconcileFailed',+ reconcileFaults.length > 1+ ? `${message} (and ${reconcileFaults.length - 1} more binding(s) faulted)`+ : message,+ isCurrent+ )+ throw first.err+ }+if (failures.length > 0) {const message = failures.join('; ')await this.writeExternalEgressStatus(diff --git a/packages/network-policy-core/index.cjs b/packages/network-policy-core/index.cjsindex 04983a7d1..2f2195f38 100644--- a/packages/network-policy-core/index.cjs+++ b/packages/network-policy-core/index.cjs@@ -71,10 +71,13 @@ const TRANSIENT_DNS_CODES = new Set([* DNS codes that are a POSITIVE permanent verdict about the NAME (issue #513):* the two genuine no-records answers, plus EBADNAME — c-ares refused to send* the query because the name is malformed. EBADNAME is reachable from user- * input: the CRD pattern for `egressBindings[].dns` admits consecutive dots and- * labels over 63 octets, so a typo in a manifest lands here. A malformed name is- * the operator's misconfiguration — not a resolver outage, not a controller- * fault — so it prunes and is reported as rejected exactly like NXDOMAIN.+ * input through exactly one field today: `spec.ui.egress.external[].fqdn`, whose+ * CRD pattern admits labels over 63 octets and which no controller validates+ * further. (The other two hostname fields do not reach it: HCC's+ * `isPublicDnsHostname` and WRC's workload-binding validator both apply a+ * per-label regex before resolving.) A malformed name is the operator's+ * misconfiguration — not a resolver outage, not a controller fault — so it+ * prunes and is reported as rejected exactly like NXDOMAIN.** Every other non-transient code stays OUT on purpose: EBADFAMILY, EBADFLAGS,* EBADHINTS, ENONAME, EBADQUERY and EBADSTR describe arguments neither