Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(guardrails): scope mcp-host→llm-hooks egress to referenced hooks (N1/N7)
Andy Pavia89c35dcb9aab
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 52c68406d..949683f89 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 bb5b441d4..44a681873 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/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex 00630f864..4b06b2db0 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -19,7 +19,6 @@ import {WFC_APP_LABEL,sharedFileSystemHash,} from './k8s/sharedFileSystemFactory'-import { referencedHookIds } from './llmHookReconciler'import { hccLogger } from './logger'import { issueMcpHostRuntimeTokens } from './mcpHostRuntimeTokenIssuerClient'import {@@ -3481,89 +3480,6 @@ export class HostReconciler {)}- /**- * Egress reverse-index for guardrail hooks (spec §8.2). Lifts the host pod's- * default-deny egress so it can reach installed LlmHook endpoints in the- * llm-hooks namespace — the counterpart to the per-podKey INGRESS reverse-index- * on the hook side (llmHookReconciler.buildNetworkPolicy). Without it a Host- * that references hooks resolves them but every `/v1` call is dropped by- * `deny-all-mcp-host`.- *- * The AUTHORITATIVE admission control stays the hook-side ingress NP (it admits- * only the referencing hosts, deny-all otherwise); this rule only opens the- * host→llm-hooks lane. Ports are per-hook (`img.port`) so the rule is not- * port-restricted — reachability is scoped by the hook-side ingress. Service- * targets in OTHER namespaces and remote (external) targets are out of scope- * (follow-up). Emitted only when the Host references ≥1 hook; otherwise the NP- * is removed so clearing all hooks re-closes the lane.- */- private async ensureMcpHostLlmHooksEgressNetworkPolicy(host: HostCRD): Promise<void> {- const policyName = `mcp-host-${host.name}-egress-llm-hooks`-- if (referencedHookIds(host).length === 0) {- // No hooks referenced → ensure the lane is closed (idempotent, ownership-gated).- await this.deleteIfHccOwned(- 'NetworkPolicy',- policyName,- host.namespace,- host.name,- () =>- this.networkingApi.readNamespacedNetworkPolicy({- name: policyName,- namespace: host.namespace,- }),- () =>- this.networkingApi.deleteNamespacedNetworkPolicy({- name: policyName,- namespace: host.namespace,- })- )- return- }-- const policy: k8s.V1NetworkPolicy = {- apiVersion: 'networking.k8s.io/v1',- kind: 'NetworkPolicy',- metadata: {- name: policyName,- namespace: host.namespace,- labels: {- [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,- [HOST_LABEL]: host.name,- 'clerum.io/policy-type': 'llm-hooks-egress',- },- },- spec: {- podSelector: {- matchLabels: {- [HOST_LABEL]: host.name,- [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,- },- },- policyTypes: ['Egress'],- egress: [- {- to: [- {- namespaceSelector: {- matchLabels: { 'kubernetes.io/metadata.name': config.llmHooksNamespace },- },- },- ],- },- ],- },- }-- await applyNetworkPolicy(- this.networkingApi,- policyName,- host.namespace,- policy,- '[HostReconciler]'- )- }-/*** Delete per-Host NetworkPolicies created by this reconciler.* 404-tolerant — safe to call even if NPs were never created or already gone.@@ -3773,7 +3689,9 @@ export class HostReconciler {try {await this.ensureMcpHostIngressNetworkPolicy(host)await this.ensureMcpHostGfsEgressNetworkPolicy(host)- await this.ensureMcpHostLlmHooksEgressNetworkPolicy(host)+ // The mcp-host→llm-hooks egress policy is now owned by LlmHookReconciler+ // (per-host, scoped to referenced hook pods — N1/N7); host-delete cleanup+ // of `mcp-host-<host>-egress-llm-hooks` stays in deleteHostNetworkPolicies.await this.ensureWorkflowApprovalReaderMcpHostIngressNetworkPolicy(host)} catch (err) {console.error(`[HostReconciler] Failed to ensure mcp-host NP for "${host.name}":`, err)diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex c1b0eef09..7ef36351a 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -2844,6 +2844,18 @@ export class McpServerWatcher implements McpServerProvider {)}}++ // Keep this Host's scoped egress-to-hooks policy in sync with its CURRENT+ // references (N1/N7) — in particular the "dropped the last hook reference"+ // case, where the policy must be removed. On DELETE the Host reconciler's+ // deleteHostNetworkPolicies removes it by name.+ if (eventType !== 'DELETED') {+ try {+ await this.llmHookReconciler.reconcileHostEgress(host)+ } catch (error) {+ console.error(`[K8s] Host egress-to-hooks reconcile for "${host.name}" failed:`, error)+ }+ }}const doneCallback = (err: Error | null) => {diff --git a/host-context-controller/src/llmHookReconciler.test.ts b/host-context-controller/src/llmHookReconciler.test.tsindex ed3272784..5475dfcd7 100644--- a/host-context-controller/src/llmHookReconciler.test.ts+++ b/host-context-controller/src/llmHookReconciler.test.ts@@ -559,9 +559,11 @@ describe('LlmHookReconciler', () => {await reconciler.reconcileNetworkPoliciesForHooks(['a'])expect(networkingApi.createNamespacedNetworkPolicy).toHaveBeenCalled()- const npCall = networkingApi.createNamespacedNetworkPolicy.mock.calls.at(-1)![0] as {- body: k8s.V1NetworkPolicy- }+ // The fan-out also refreshes the host egress NP (in mcp-host ns); select the+ // hook INGRESS policy (in llm-hooks ns, name `llmhook-<podKey>`).+ const npCall = networkingApi.createNamespacedNetworkPolicy.mock.calls+ .map(c => c[0] as { body: k8s.V1NetworkPolicy })+ .find(c => c.body.metadata?.name === podKeyResourceName(computePodKey(a)!))!const peers = (npCall.body.spec?.ingress?.[0]?._from ?? []) as Array<{podSelector?: { matchLabels?: Record<string, string> }}>@@ -648,10 +650,10 @@ describe('LlmHookReconciler', () => {await reconciler.reconcileNetworkPoliciesForHooks(['s1'])- const npCall = networkingApi.createNamespacedNetworkPolicy.mock.calls.at(-1)![0] as {- body: k8s.V1NetworkPolicy- }- expect(npCall.body.metadata?.name).toBe('llmhook-svc-s1')+ // The fan-out also refreshes the host egress NP; select the ingress one.+ const npCall = networkingApi.createNamespacedNetworkPolicy.mock.calls+ .map(c => c[0] as { body: k8s.V1NetworkPolicy })+ .find(c => c.body.metadata?.name === 'llmhook-svc-s1')!const peers = (npCall.body.spec?.ingress?.[0]?._from ?? []) as Array<{podSelector?: { matchLabels?: Record<string, string> }}>@@ -666,6 +668,78 @@ describe('LlmHookReconciler', () => {})})+ // ─── Per-host scoped egress (N1/N7) ────────────────────────────────++ describe('per-host egress (reconcileHostEgress)', () => {+ it('allows egress only to the referenced image hook pod-key + port', async () => {+ const hook = makeHook({ name: 'img1' }) // default image target, port 8080+ hooks.set('img1', hook)+ const host = makeHostRef('host-1', ['img1'])+ hosts.set('host-1', host)++ await reconciler.reconcileHostEgress(host)++ const call = networkingApi.createNamespacedNetworkPolicy.mock.calls.at(-1)![0] as {+ namespace: string+ body: k8s.V1NetworkPolicy+ }+ expect(call.namespace).toBe('mcp-host')+ expect(call.body.metadata?.name).toBe('mcp-host-host-1-egress-llm-hooks')+ expect(call.body.spec?.policyTypes).toEqual(['Egress'])+ expect(call.body.spec?.podSelector?.matchLabels).toEqual({+ 'clerum.io/host': 'host-1',+ 'clerum.io/managed-by': 'host-context-controller',+ })+ const rules = call.body.spec?.egress ?? []+ expect(rules).toHaveLength(1)+ expect(rules[0].to?.[0]?.namespaceSelector?.matchLabels).toEqual({+ 'kubernetes.io/metadata.name': 'llm-hooks',+ })+ expect(rules[0].to?.[0]?.podSelector?.matchLabels).toEqual({+ 'clerum.io/hook-pod-key': computePodKey(hook),+ })+ expect(rules[0].ports?.[0]?.port).toBe(8080)+ })++ it('uses the Service selector + port for a service-target hook', async () => {+ coreApi.readNamespacedService.mockResolvedValue({+ metadata: {},+ spec: { selector: { app: 'svc-hook' } },+ } as never)+ const hook = makeHook({+ name: 'svc1',+ spec: {+ target: { service: { name: 'svc-hook', namespace: 'llm-hooks', port: 9000 } },+ lifecyclePoints: ['preCall'],+ },+ })+ hooks.set('svc1', hook)+ const host = makeHostRef('host-1', ['svc1'])+ hosts.set('host-1', host)++ await reconciler.reconcileHostEgress(host)++ const call = networkingApi.createNamespacedNetworkPolicy.mock.calls.at(-1)![0] as {+ body: k8s.V1NetworkPolicy+ }+ const rules = call.body.spec?.egress ?? []+ expect(rules[0].to?.[0]?.podSelector?.matchLabels).toEqual({ app: 'svc-hook' })+ expect(rules[0].ports?.[0]?.port).toBe(9000)+ })++ it('removes the policy when the Host references no resolvable hooks', async () => {+ const host = makeHostRef('host-1', []) // references nothing+ hosts.set('host-1', host)++ await reconciler.reconcileHostEgress(host)++ expect(networkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'mcp-host-host-1-egress-llm-hooks' })+ )+ })+ })+it('rejects an invalid (private-range) egress binding without exposing the workload', async () => {const a = makeHook({name: 'a',diff --git a/host-context-controller/src/llmHookReconciler.ts b/host-context-controller/src/llmHookReconciler.tsindex 4bd5ace1a..cff8f6a5c 100644--- a/host-context-controller/src/llmHookReconciler.ts+++ b/host-context-controller/src/llmHookReconciler.ts@@ -268,6 +268,21 @@ export class LlmHookReconciler {await this.ensureNetworkPolicy(podKey, members, egress.failures.length ? [] : egress.rules)})}++ // Refresh the per-host scoped EGRESS for every host referencing an affected+ // hook, so a Host reference change (or an image bump that moves a pod key)+ // keeps the host's egress allowlist in sync with what it may reach (N1/N7).+ // The "host dropped its last reference" case is covered by the Host-watch+ // calling reconcileHostEgress(host) directly.+ const affectedHosts = new Map<string, HostCRD>()+ for (const name of hookNames) {+ const hook = this.hooks.get(name)+ if (!hook) continue+ for (const h of this.referencingHosts([hook])) affectedHosts.set(h.name, h)+ }+ for (const host of affectedHosts.values()) {+ await this.reconcileHostEgress(host)+ }}/**@@ -290,6 +305,11 @@ export class LlmHookReconciler {for (const podKey of imagePodKeys) {await this.runSerialized(podKey, () => this.reconcilePodKey(podKey))}+ // Converge every Host's scoped egress-to-hooks policy (N1/N7) — the periodic+ // backstop for a missed watch event or an image bump that moved a pod key.+ for (const host of this.hosts.values()) {+ await this.reconcileHostEgress(host)+ }await this.sweepOrphanedWorkloads()console.log(`${LOG} Full reconciliation complete`)}@@ -767,15 +787,13 @@ export class LlmHookReconciler {await this.applyNetworkPolicy(this.buildNetworkPolicy(podKey, members, egressRules))}- /** Idempotent create-then-409-replace of a NetworkPolicy in the llm-hooks namespace. */+ /** Idempotent create-then-409-replace of a NetworkPolicy in its own namespace. */private async applyNetworkPolicy(policy: k8s.V1NetworkPolicy): Promise<void> {const name = policy.metadata!.name!+ const namespace = policy.metadata!.namespace ?? config.llmHooksNamespacetry {- await this.networkingApi.createNamespacedNetworkPolicy({- namespace: config.llmHooksNamespace,- body: policy,- })- console.log(`${LOG} Created NetworkPolicy "${name}"`)+ await this.networkingApi.createNamespacedNetworkPolicy({ namespace, body: policy })+ console.log(`${LOG} Created NetworkPolicy "${name}" (${namespace})`)return} catch (error) {if (getErrorCode(error) !== 409) throw error@@ -785,17 +803,8 @@ export class LlmHookReconciler {logPrefix: LOG,body: policy,mergeExisting: preserveObjectAnnotations,- read: () =>- this.networkingApi.readNamespacedNetworkPolicy({- name,- namespace: config.llmHooksNamespace,- }),- replace: body =>- this.networkingApi.replaceNamespacedNetworkPolicy({- name,- namespace: config.llmHooksNamespace,- body,- }),+ read: () => this.networkingApi.readNamespacedNetworkPolicy({ name, namespace }),+ replace: body => this.networkingApi.replaceNamespacedNetworkPolicy({ name, namespace, body }),})}@@ -819,27 +828,13 @@ export class LlmHookReconciler {return}- let selector: Record<string, string> | undefined- try {- const service = await this.coreApi.readNamespacedService({- name: svc.name,- namespace: svc.namespace,- })- selector = service.spec?.selector- } catch (error) {- if (getErrorCode(error) === 404) {- console.warn(- `${LOG} service-target hook "${hook.name}": Service ${svc.namespace}/${svc.name} not found; leaving fail-closed under default-deny`- )- return- }- throw error- }- if (!selector || Object.keys(selector).length === 0) {- // An empty podSelector would select ALL pods in the namespace — refuse to- // create such an over-broad allow; leave the pods fail-closed instead.+ // A missing Service or an empty selector would leave us unable to scope the+ // ingress (an empty podSelector selects ALL pods) — refuse and leave the pods+ // fail-closed under the namespace default-deny instead.+ const selector = await this.readServiceSelector(svc.name, svc.namespace)+ if (!selector) {console.warn(- `${LOG} service-target hook "${hook.name}": Service ${svc.namespace}/${svc.name} has no selector; cannot scope ingress (fail-closed under default-deny)`+ `${LOG} service-target hook "${hook.name}": Service ${svc.namespace}/${svc.name} missing or selector-less; leaving fail-closed under default-deny`)return}@@ -900,6 +895,131 @@ export class LlmHookReconciler {}}+ /** Read a Service's selector; undefined if missing/empty (can't scope pods). */+ private async readServiceSelector(+ name: string,+ namespace: string+ ): Promise<Record<string, string> | undefined> {+ try {+ const svc = await this.coreApi.readNamespacedService({ name, namespace })+ const selector = svc.spec?.selector+ return selector && Object.keys(selector).length > 0 ? selector : undefined+ } catch (error) {+ if (getErrorCode(error) === 404) return undefined+ throw error+ }+ }++ // ─── Per-host egress reverse-index (§8.2) ───────────────────────────++ private hostEgressNpName(hostName: string): string {+ return `mcp-host-${hostName}-egress-llm-hooks`+ }++ /**+ * Scoped egress reverse-index (§8.2) — the SOURCE-side mirror of the hook+ * ingress policies. A host pod may egress ONLY to the specific hook pods its+ * Host CR references (one rule per referenced in-cluster hook), so a host now+ * reaches only its CRD's hooks from BOTH ends rather than the whole llm-hooks+ * namespace. Serialized per host so concurrent Host/LlmHook events don't race.+ */+ async reconcileHostEgress(host: HostCRD): Promise<void> {+ await this.runSerialized(`host-egress:${host.name}`, () =>+ this.ensureHostEgressNetworkPolicy(host)+ )+ }++ private async ensureHostEgressNetworkPolicy(host: HostCRD): Promise<void> {+ const rules = await this.buildHostEgressRules(host)+ if (rules.length === 0) {+ // No referenced in-cluster hooks → the host has no reason to reach+ // llm-hooks; remove the policy (DNS/control-plane egress live elsewhere).+ await this.deleteHostEgressNetworkPolicy(host.name)+ return+ }+ await this.applyNetworkPolicy({+ apiVersion: 'networking.k8s.io/v1',+ kind: 'NetworkPolicy',+ metadata: {+ name: this.hostEgressNpName(host.name),+ namespace: config.hostNamespace,+ labels: {+ [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,+ [HOST_LABEL]: host.name,+ [POLICY_TYPE_LABEL]: 'llm-hooks-egress',+ },+ },+ spec: {+ podSelector: {+ matchLabels: { [HOST_LABEL]: host.name, [MANAGED_BY_LABEL]: MANAGED_BY_VALUE },+ },+ policyTypes: ['Egress'],+ egress: rules,+ },+ })+ }++ /**+ * One egress rule per referenced in-cluster hook (deduped by pod selector ++ * port): image → `hook-pod-key` + `img.port`; service (in llm-hooks) → the+ * target Service's selector + port. Dangling refs, cross-namespace service+ * targets, and `remote` targets add no rule.+ */+ private async buildHostEgressRules(host: HostCRD): Promise<k8s.V1NetworkPolicyEgressRule[]> {+ const llmHooksNs = config.llmHooksNamespace+ const rules: k8s.V1NetworkPolicyEgressRule[] = []+ const seen = new Set<string>()+ for (const id of new Set(referencedHookIds(host))) {+ const hook = this.hooks.get(id)+ if (!hook) continue // dangling reference++ let podSelector: Record<string, string> | undefined+ let port: number | undefined+ const kind = classifyTarget(hook)+ if (kind === 'image') {+ podSelector = { [HOOK_PODKEY_LABEL]: computePodKey(hook)! }+ port = hook.spec.target!.image!.port+ } else if (kind === 'service') {+ const svc = hook.spec.target!.service!+ if (svc.namespace !== llmHooksNs) continue // only llm-hooks is scoped (matches ingress)+ const selector = await this.readServiceSelector(svc.name, svc.namespace)+ if (!selector) continue+ podSelector = selector+ port = svc.port+ } else {+ continue // remote / invalid — not an in-cluster llm-hooks destination+ }++ const dedup = `${JSON.stringify(podSelector)}:${port}`+ if (seen.has(dedup)) continue+ seen.add(dedup)+ rules.push({+ to: [+ {+ namespaceSelector: { matchLabels: { 'kubernetes.io/metadata.name': llmHooksNs } },+ podSelector: { matchLabels: podSelector },+ },+ ],+ ports: [{ port: port!, protocol: 'TCP' }],+ })+ }+ return rules+ }++ private async deleteHostEgressNetworkPolicy(hostName: string): Promise<void> {+ const name = this.hostEgressNpName(hostName)+ const ns = config.hostNamespace+ try {+ const np = await this.networkingApi.readNamespacedNetworkPolicy({ name, namespace: ns })+ if (np.metadata?.labels?.[MANAGED_BY_LABEL] === MANAGED_BY_VALUE) {+ await this.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace: ns })+ console.log(`${LOG} Deleted NetworkPolicy "${name}" (${ns})`)+ }+ } catch (error) {+ if (getErrorCode(error) !== 404) throw error+ }+ }+// ─── Reference-counted, label-owned GC (§3) ─────────────────────────private isHccOwned(diff --git a/host-context-controller/test/hostReconciler.networkpolicy.test.ts b/host-context-controller/test/hostReconciler.networkpolicy.test.tsindex 2b5123f8d..3954be422 100644--- a/host-context-controller/test/hostReconciler.networkpolicy.test.ts+++ b/host-context-controller/test/hostReconciler.networkpolicy.test.ts@@ -153,51 +153,11 @@ describe('HostReconciler.ensureChannelReaderEgressNetworkPolicy', () => {})})-describe('HostReconciler.ensureMcpHostLlmHooksEgressNetworkPolicy', () => {- const HOST_WITH_HOOKS: HostCRD = {- ...HOST,- spec: {- ...HOST.spec,- guardrails: { hooks: { preCall: [{ id: 'hook-x-v1-0-0-abcd1234' }] } },- },- }-- it('opens host→llm-hooks egress when the Host references hooks', async () => {- const { reconciler, mocks } = createReconciler()-- await (reconciler as any).ensureMcpHostLlmHooksEgressNetworkPolicy(HOST_WITH_HOOKS)-- expect(mocks.networkingApi.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)- const call = (mocks.networkingApi.createNamespacedNetworkPolicy as any).mock.calls[0][0]-- expect(call.namespace).toBe('mcp-host')- expect(call.body.metadata.name).toBe('mcp-host-chatllm-egress-llm-hooks')- expect(call.body.metadata.labels['clerum.io/managed-by']).toBe('host-context-controller')- expect(call.body.metadata.labels['clerum.io/host']).toBe('chatllm')- expect(call.body.metadata.labels['clerum.io/policy-type']).toBe('llm-hooks-egress')- // Source pod selector requires managed-by so the policy can't be spoofed.- expect(call.body.spec.podSelector.matchLabels).toEqual({- 'clerum.io/host': 'chatllm',- 'clerum.io/managed-by': 'host-context-controller',- })- expect(call.body.spec.policyTypes).toEqual(['Egress'])- expect(call.body.spec.egress).toHaveLength(1)- expect(call.body.spec.egress[0].to[0].namespaceSelector.matchLabels).toEqual({- 'kubernetes.io/metadata.name': 'llm-hooks',- })- // Not port-restricted: hook ports vary per hook; the hook-side ingress NP is- // the authoritative admission control.- expect(call.body.spec.egress[0].ports).toBeUndefined()- })-- it('does not open the lane when the Host references no hooks', async () => {- const { reconciler, mocks } = createReconciler()-- await (reconciler as any).ensureMcpHostLlmHooksEgressNetworkPolicy(HOST)-- expect(mocks.networkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()- })-})+// NOTE: the mcp-host→llm-hooks egress policy moved to LlmHookReconciler+// (per-host, scoped to referenced hook pods — N1/N7); see+// src/llmHookReconciler.test.ts "per-host egress". HostReconciler still deletes+// `mcp-host-<host>-egress-llm-hooks` on host delete (covered by the+// deleteHostNetworkPolicies test below).describe('HostReconciler.ensureMcpHostIngressNetworkPolicy', () => {it('creates the ingress NP in mcp-host namespace with correct selectors', async () => {