Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(guardrails): admission control for service-target hooks (llm-hooks ingress)
Andy Pavia3e748b4f3c18
diff --git a/deploy/base/llm-hooks/kustomization.yaml b/deploy/base/llm-hooks/kustomization.yamlindex b5633ece3..2483fcd52 100644--- a/deploy/base/llm-hooks/kustomization.yaml+++ b/deploy/base/llm-hooks/kustomization.yaml@@ -2,3 +2,4 @@ apiVersion: kustomize.config.k8s.io/v1beta1kind: Kustomizationresources:- rbac.yaml+ - networkpolicies.yamldiff --git a/deploy/base/llm-hooks/networkpolicies.yaml b/deploy/base/llm-hooks/networkpolicies.yamlnew file mode 100644index 000000000..b66c0fba2--- /dev/null+++ b/deploy/base/llm-hooks/networkpolicies.yaml@@ -0,0 +1,28 @@+# Baseline default-deny-INGRESS for the llm-hooks namespace (guardrails §8.2).+#+# Without this, a hook pod that no NetworkPolicy selects is default-ALLOW ingress+# — which is the case for `service`-target hooks (host-context-controller only+# emits per-podKey ingress policies for `image` targets). With this baseline in+# place, an un-covered hook pod is fail-CLOSED: it accepts traffic only from what+# an explicit allow-policy admits.+#+# This composes additively with the controller-managed allow-policies:+# - image targets: `llmhook-<podKey>` admits the referencing mcp-hosts.+# - service targets: `llmhook-svc-<crName>` admits the referencing mcp-hosts.+# Kubelet health/readiness probes originate from the node and are not affected+# (the existing per-podKey policies already coexist with pod probes).+#+# INGRESS only — hook egress (DNS, image-target egressBindings) is governed+# separately and is not constrained here.+apiVersion: networking.k8s.io/v1+kind: NetworkPolicy+metadata:+ name: default-deny-ingress+ namespace: llm-hooks+ labels:+ clerum.io/managed-by: host-context-controller+ clerum.io/policy-type: infrastructure+spec:+ podSelector: {}+ policyTypes:+ - Ingressdiff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 30215a324..52c68406d 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.165",+ "version": "0.1.166","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.165",+ "version": "0.1.166","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 2b9bf2c0f..bb5b441d4 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.165",+ "version": "0.1.166","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/llmHookReconciler.test.ts b/host-context-controller/src/llmHookReconciler.test.tsindex c5f31c175..ed3272784 100644--- a/host-context-controller/src/llmHookReconciler.test.ts+++ b/host-context-controller/src/llmHookReconciler.test.ts@@ -568,6 +568,104 @@ describe('LlmHookReconciler', () => {expect(peers.map(p => p.podSelector?.matchLabels?.[HOST_LABEL])).toContain('host-1')})+ // ─── Service-target ingress reverse-index (§8.2) ────────────────────++ describe('service-target NetworkPolicy', () => {+ function makeServiceHook(name: string, svcName = 'ref-hook'): LlmHookCRD {+ return makeHook({+ name,+ spec: {+ target: { service: { name: svcName, namespace: 'llm-hooks', port: 8080 } },+ lifecyclePoints: ['preCall'],+ },+ })+ }++ function withSelector(selector: Record<string, string>) {+ coreApi.readNamespacedService.mockResolvedValue({+ metadata: { resourceVersion: '1' },+ spec: { selector },+ } as never)+ }++ it('creates an ingress NP selecting the Service pods and admitting only referencing hosts', async () => {+ withSelector({ app: 'ref-hook' })+ const s = makeServiceHook('s1')+ hooks.set('s1', s)+ hosts.set('host-1', makeHostRef('host-1', ['s1']))+ hosts.set('host-2', makeHostRef('host-2', ['other']))++ await reconciler.reconcile(s)++ const npCall = networkingApi.createNamespacedNetworkPolicy.mock.calls.at(-1)![0] as {+ body: k8s.V1NetworkPolicy+ }+ expect(npCall.body.metadata?.name).toBe('llmhook-svc-s1')+ expect(npCall.body.metadata?.labels?.[MANAGED_BY_LABEL]).toBe(MANAGED_BY_VALUE)+ expect(npCall.body.metadata?.labels?.['clerum.io/policy-type']).toBe('service-hook-ingress')+ expect(npCall.body.spec?.podSelector?.matchLabels).toEqual({ app: 'ref-hook' })+ const peers = (npCall.body.spec?.ingress?.[0]?._from ?? []) as Array<{+ podSelector?: { matchLabels?: Record<string, string> }+ }>+ const hostNames = peers.map(p => p.podSelector?.matchLabels?.[HOST_LABEL])+ expect(hostNames).toContain('host-1')+ expect(hostNames).not.toContain('host-2')+ expect(npCall.body.spec?.ingress?.[0]?.ports?.[0]?.port).toBe(8080)+ })++ it('creates a deny-all (empty ingress) NP when no Host references the hook', async () => {+ withSelector({ app: 'ref-hook' })+ const s = makeServiceHook('s1')+ hooks.set('s1', s)++ await reconciler.reconcile(s)++ const npCall = networkingApi.createNamespacedNetworkPolicy.mock.calls.at(-1)![0] as {+ body: k8s.V1NetworkPolicy+ }+ expect(npCall.body.spec?.ingress ?? []).toEqual([])+ })++ it('does NOT create an NP when the Service has no selector (fail-closed under default-deny)', async () => {+ coreApi.readNamespacedService.mockResolvedValue({+ metadata: {},+ spec: {},+ } as never)+ const s = makeServiceHook('s1')+ hooks.set('s1', s)+ hosts.set('host-1', makeHostRef('host-1', ['s1']))++ await reconciler.reconcile(s)++ expect(networkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ it('refreshes the admitted hosts on a Host reference change (fan-out)', async () => {+ withSelector({ app: 'ref-hook' })+ const s = makeServiceHook('s1')+ hooks.set('s1', s)+ hosts.set('host-9', makeHostRef('host-9', ['s1']))++ 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')+ const peers = (npCall.body.spec?.ingress?.[0]?._from ?? []) as Array<{+ podSelector?: { matchLabels?: Record<string, string> }+ }>+ expect(peers.map(p => p.podSelector?.matchLabels?.[HOST_LABEL])).toContain('host-9')+ })++ it('deletes the service-target NP on hook delete', async () => {+ await reconciler.reconcileDelete('s1', null)+ expect(networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'llmhook-svc-s1' })+ )+ })+ })+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 7f0c365d7..4bd5ace1a 100644--- a/host-context-controller/src/llmHookReconciler.ts+++ b/host-context-controller/src/llmHookReconciler.ts@@ -27,7 +27,14 @@ import * as dns from 'node:dns/promises'import { isIP } from 'node:net'import { isWorkflowRecipeDefaultAllowedCapability } from '@clerum/workflow-recipe-capability-policy'import { config } from './config'-import { HOOK_PODKEY_LABEL, HOST_LABEL, MANAGED_BY_LABEL, MANAGED_BY_VALUE } from './constants'+import {+ HOOK_PODKEY_LABEL,+ HOST_LABEL,+ LLMHOOK_LABEL,+ MANAGED_BY_LABEL,+ MANAGED_BY_VALUE,+ POLICY_TYPE_LABEL,+} from './constants'import { isAllowedExternalEgressCidr, isPublicDnsHostname } from './networkPolicyReconciler'import { HostCRD, LlmHookCRD, LlmHookCondition, LlmHookImageTarget, LlmHookStatus } from './types'import {@@ -126,6 +133,11 @@ export function podKeyResourceName(podKey: string): string {return `llmhook-${podKey}`}+/** NetworkPolicy name for a service-target hook's per-CR ingress policy (§8.2). */+export function serviceTargetNpName(crName: string): string {+ return `llmhook-svc-${crName}`+}+type TargetKind = 'image' | 'service' | 'remote' | 'invalid'function classifyTarget(hook: LlmHookCRD): TargetKind {@@ -198,6 +210,8 @@ export class LlmHookReconciler {await this.runSerialized(`name:${hook.name}`, () => this.reconcileNonImage(hook, kind))return}+ // Clean any stale service-target ingress NP left by a prior service→image flip.+ await this.deleteServiceTargetNetworkPolicy(hook.name)const podKey = computePodKey(hook)!if (previousPodKey && previousPodKey !== podKey) {// The image target changed pod keys: tear down the stale one (if it now@@ -215,8 +229,9 @@ export class LlmHookReconciler {*/async reconcileDelete(name: string, formerPodKey?: string | null): Promise<void> {if (!formerPodKey) {- // service/remote (or unknown) — nothing was deployed.- await this.runSerialized(`name:${name}`, async () => {})+ // service/remote (or unknown) — no workload was deployed, but a service+ // target may have left an ingress NP; remove it.+ await this.runSerialized(`name:${name}`, () => this.deleteServiceTargetNetworkPolicy(name))return}await this.runSerialized(formerPodKey, () => this.reconcilePodKey(formerPodKey))@@ -232,6 +247,12 @@ export class LlmHookReconciler {for (const name of hookNames) {const hook = this.hooks.get(name)if (!hook) continue+ // Service targets: refresh the per-CR ingress NP so the admitted-host set+ // tracks the Host reference change (image targets handled by pod key below).+ if (classifyTarget(hook) === 'service') {+ await this.runSerialized(`name:${name}`, () => this.ensureServiceTargetNetworkPolicy(hook))+ continue+ }const key = computePodKey(hook)if (key) podKeys.add(key)}@@ -386,6 +407,14 @@ export class LlmHookReconciler {)return}+ // A service target gets an ingress NP admitting only referencing hosts; a+ // remote target has no in-cluster pod, so clear any stale NP (e.g. after a+ // service→remote target flip).+ if (kind === 'service') {+ await this.ensureServiceTargetNetworkPolicy(hook)+ } else {+ await this.deleteServiceTargetNetworkPolicy(hook.name)+ }await this.writeStatus(hook,condition('True', 'NoWorkload', 'No workload deployed for service/remote target'),@@ -735,7 +764,11 @@ export class LlmHookReconciler {members: LlmHookCRD[],egressRules: k8s.V1NetworkPolicyEgressRule[]): Promise<void> {- const policy = this.buildNetworkPolicy(podKey, members, egressRules)+ await this.applyNetworkPolicy(this.buildNetworkPolicy(podKey, members, egressRules))+ }++ /** Idempotent create-then-409-replace of a NetworkPolicy in the llm-hooks namespace. */+ private async applyNetworkPolicy(policy: k8s.V1NetworkPolicy): Promise<void> {const name = policy.metadata!.name!try {await this.networkingApi.createNamespacedNetworkPolicy({@@ -766,6 +799,107 @@ export class LlmHookReconciler {})}+ /**+ * Per-service-target ingress NP (§8.2). A `service` target deploys no workload,+ * so it never gets a per-podKey policy — with the namespace default-deny that+ * leaves its pods fail-closed. This admits EXACTLY the referencing mcp-hosts to+ * the target Service's pods (empty `ingress` ⇒ deny-all), the service-target+ * analog of the image reverse-index (`buildNetworkPolicy`). Scoped to Services+ * in the llm-hooks namespace, where HCC has RBAC + the default-deny baseline; a+ * Service elsewhere is left to that namespace's own policy (warned), and a+ * missing/selector-less Service is left fail-closed under the default-deny.+ */+ private async ensureServiceTargetNetworkPolicy(hook: LlmHookCRD): Promise<void> {+ const svc = hook.spec.target?.service+ if (!svc?.name || !svc.namespace || !svc.port) return+ if (svc.namespace !== config.llmHooksNamespace) {+ console.warn(+ `${LOG} service-target hook "${hook.name}" → Service ${svc.namespace}/${svc.name} outside ${config.llmHooksNamespace}; ingress not enforced by HCC`+ )+ 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.+ console.warn(+ `${LOG} service-target hook "${hook.name}": Service ${svc.namespace}/${svc.name} has no selector; cannot scope ingress (fail-closed under default-deny)`+ )+ return+ }++ const hosts = this.referencingHosts([hook])+ const labels: Record<string, string> = {+ [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,+ [POLICY_TYPE_LABEL]: 'service-hook-ingress',+ }+ // Per-CR traceability label — omit if the CR name is not a valid label value.+ if (hook.name.length <= 63) labels[LLMHOOK_LABEL] = hook.name++ const ingress: k8s.V1NetworkPolicyIngressRule[] =+ hosts.length > 0+ ? [+ {+ _from: hosts.map(h => ({+ namespaceSelector: {+ matchLabels: { 'kubernetes.io/metadata.name': config.hostNamespace },+ },+ podSelector: { matchLabels: { [HOST_LABEL]: h.name } },+ })),+ ports: [{ port: svc.port, protocol: 'TCP' as const }],+ },+ ]+ : []++ await this.applyNetworkPolicy({+ apiVersion: 'networking.k8s.io/v1',+ kind: 'NetworkPolicy',+ metadata: {+ name: serviceTargetNpName(hook.name),+ namespace: config.llmHooksNamespace,+ labels,+ },+ spec: {+ podSelector: { matchLabels: selector },+ policyTypes: ['Ingress'],+ ingress,+ },+ })+ }++ /** Delete a service-target hook's ingress NP (CR delete / target-kind change). */+ private async deleteServiceTargetNetworkPolicy(crName: string): Promise<void> {+ const name = serviceTargetNpName(crName)+ const ns = config.llmHooksNamespace+ 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}"`)+ } else {+ console.warn(`${LOG} Skipping NetworkPolicy "${name}" delete — not HCC-owned`)+ }+ } catch (error) {+ if (getErrorCode(error) !== 404) throw error+ }+ }+// ─── Reference-counted, label-owned GC (§3) ─────────────────────────private isHccOwned(