Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(guardrails): live guardrail re-resolution on Host/LlmHook change (§8.2)
Andy Pavia7d25ec5a9951
diff --git a/deploy/base/llm-hooks/rbac.yaml b/deploy/base/llm-hooks/rbac.yamlindex f755bfc5e..76e5c1fe4 100644--- a/deploy/base/llm-hooks/rbac.yaml+++ b/deploy/base/llm-hooks/rbac.yaml@@ -99,12 +99,15 @@ metadata:name: mcp-host-hook-readernamespace: llm-hooksrules:- # `get` only — mcp-host resolves each referenced hook by name (getLlmHook); it- # never lists/watches. Withholding list/watch prevents a host SA from- # enumerating other tenants' hooks (it must already know the name).+ # get/list/watch — mcp-host resolves referenced hooks and re-resolves live on+ # LlmHook changes (§8.2). This namespace is tenant-scoped (multi-tenant uses a+ # per-tenant `<tenant>-llm-hooks` namespace via the namespace prefix), so+ # list/watch here exposes only THIS tenant's own hooks — no cross-tenant+ # enumeration. The runtime remains read-only (no write verbs): it can never+ # mutate hook specs or status (N10).- apiGroups: ["clerum.io"]resources: ["llmhooks"]- verbs: ["get"]+ verbs: ["get", "list", "watch"]- apiGroups: ["clerum.io"]resources: ["llmhooks/status"]verbs: ["get"]diff --git a/docs/features/mcp-host-guardrails/mcp-host-guardrails-spec-v3.md b/docs/features/mcp-host-guardrails/mcp-host-guardrails-spec-v3.mdindex f6bd55701..178e58bd8 100644--- a/docs/features/mcp-host-guardrails/mcp-host-guardrails-spec-v3.md+++ b/docs/features/mcp-host-guardrails/mcp-host-guardrails-spec-v3.md@@ -1208,7 +1208,7 @@ implemented; *In progress* = being wired; *Planned* = agreed, not yet implemente| N7 | **Least-privilege scoped policies** | All mcp-host↔`llm-hooks` communication rides narrowly-scoped, HCC-generated NetworkPolicies — never a namespace-wide or wildcard allow. Ingress policies are scoped to a specific hook pod (by pod-key or Service selector) and the exact port; egress policies are scoped to the specific hook pods a host references. The interim namespace-wide egress policy is being replaced by this per-host scoped version. | ingress Enforced; egress In progress || N8 | **Hardened, unprivileged hook pods** | Every hook container runs **non-root** with a **read-only root filesystem**, drops all Linux capabilities, forbids privilege escalation, uses the `RuntimeDefault` seccomp profile, and mounts **no** ServiceAccount token. HCC stamps these on the pod/container `securityContext` — they are not left to the image. This hardening is what makes pod-level (rather than strict per-hook) isolation acceptable under co-location (§12.5). | non-root/caps/seccomp/no-token Enforced; read-only-fs Planned || N9 | **Secret isolation** | A hook's `envSecret` is resolved only within `llm-hooks` and can never name the mcp-host LLM key or any Host secret. Because hooks and their secrets are confined to their own namespace under scoped RBAC, one hook cannot read another hook's — or the platform's — credentials. Secret material never crosses the namespace boundary into a hook. | Enforced |-| N10 | **Runtime can't widen its own reach** | The per-Host mcp-host ServiceAccount is read-only (`get`) on `LlmHook` CRs and cannot list/watch them, mutate any `Host`/`LlmHook` CR, or touch any NetworkPolicy. A compromised mcp-host pod therefore cannot rewrite guardrail policy, enumerate other tenants' hooks, or open new network paths for itself. Policy authorship stays entirely in the trusted control plane (control-api / HCC). | Enforced |+| N10 | **Runtime can't widen its own reach** | The per-Host mcp-host ServiceAccount may **read** (`get`/`list`/`watch`) `LlmHook` CRs only within its own **tenant-scoped** `llm-hooks` namespace — so it sees only its tenant's hooks (multi-tenant uses a per-tenant namespace prefix; cross-tenant isolation comes from that namespace boundary, not from withholding read) — and has **no write** verbs, so it cannot mutate any `Host`/`LlmHook` CR or touch any NetworkPolicy. A compromised mcp-host pod therefore cannot rewrite guardrail policy or open new network paths for itself; policy authorship stays entirely in the trusted control plane (control-api / HCC). | Enforced || N11 | **Fail-closed provisioning** | If HCC cannot build a correct scoped policy for a hook — e.g. the referenced Service has no selector, or a reference can't be resolved — it declines to create an over-broad allow and leaves the hook unreachable under the default-deny baseline. Reachability only appears when a precise allow is successfully provisioned; a provisioning failure fails **closed**, not open. (The separate hook-resolution fail-posture at load time is still open — see §12.4.) | NP-provisioning Enforced; resolution open || N12 | **No internal reach via broad egress** | The broad *external* egress lanes — mcp-host's `0.0.0.0/0:443\|80` LLM / `http_request` lane, and each hook's `egressBindings` — exclude the cluster pod/service/node CIDRs and all private/link-local/metadata/reserved ranges, so neither mcp-host nor a hook can reach a cluster-internal or metadata IP through them. Enforced by `ipBlock.except` on the mcp-host lane (the network mirror of the app-layer `isPrivateIp` guard, §8.3) and by `isAllowedExternalEgressCidr` validation of hook `egressBindings` at reconcile. Cluster-internal destinations stay reachable only through the narrow, explicit per-destination lanes. | hook `egressBindings` Enforced; mcp-host `except` Planned |diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex b27e10992..49fc1af44 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.251",+ "version": "0.1.252","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.251",+ "version": "0.1.252","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 85149ea3b..94b0ac1a5 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.251",+ "version": "0.1.252","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/k8sClient.ts b/mcp-host/src/k8sClient.tsindex 1ab714733..04e525479 100644--- a/mcp-host/src/k8sClient.ts+++ b/mcp-host/src/k8sClient.ts@@ -174,3 +174,48 @@ export class HostWatcher {}}}++/**+ * Watch LlmHook CRs in the (tenant-scoped) llm-hooks namespace so a hook-CR edit+ * (capabilities/path/failMode/target) is re-resolved live (§8.2), without a pod+ * restart. Namespace-scoped, so it only surfaces this tenant's own hooks.+ */+export class LlmHookWatcher {+ private watch: k8s.Watch+ private watchRequest: { abort: () => void } | null = null++ constructor() {+ this.watch = new k8s.Watch(kc)+ }++ async start(onChange: (name: string) => void): Promise<void> {+ const path = `/apis/${GROUP}/${VERSION}/namespaces/${config.llmHooksNamespace}/${LLMHOOKS_PLURAL}`+ console.log(`[K8s] Starting watch on LlmHooks (namespace ${config.llmHooksNamespace})`)++ const watchCallback = (type: string, apiObj: { metadata?: { name?: string } }) => {+ const name = apiObj?.metadata?.name+ if (!name) return+ if (type === 'ADDED' || type === 'MODIFIED' || type === 'DELETED') {+ console.log(`[K8s] LlmHook watch event: ${type} for ${name}`)+ onChange(name)+ }+ }++ const doneCallback = (err: Error | null) => {+ if (err) {+ console.error('[K8s] LlmHook watch error:', err)+ setTimeout(() => this.start(onChange), 5000)+ }+ }++ this.watchRequest = await this.watch.watch(path, {}, watchCallback, doneCallback)+ }++ stop(): void {+ if (this.watchRequest) {+ console.log('[K8s] Stopping LlmHook watch')+ this.watchRequest.abort()+ this.watchRequest = null+ }+ }+}diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex 0feff9ba1..c3c3f872d 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -54,7 +54,7 @@ import {resolveGuardrailHookDescriptors,withResolvedHookDescriptors,} from './guardrailHookResolver'-import { HostWatcher, getHost, getLlmHook } from './k8sClient'+import { HostWatcher, LlmHookWatcher, getHost, getLlmHook } from './k8sClient'import { StatelessHeartbeat } from './lifecycle/statelessHeartbeat'import { TaskLifecycle } from './lifecycle/taskLifecycle'import { isTerminal } from './lifecycle/types'@@ -167,7 +167,13 @@ let currentPolicy: LlmPolicy | null = nulllet failoverEngine: FailoverEngine | null = nulllet bootFallbackEntry: FallbackEntry | null = nulllet hostWatcher: HostWatcher | null = null+let llmHookWatcher: LlmHookWatcher | null = nulllet contextMapperPollTimer: ReturnType<typeof setInterval> | null = null+// Periodic guardrail re-resolve — a backstop for dropped LlmHook/Host watch+// events (the LlmHookWatcher is the primary, immediate path). Host edits also+// apply immediately via onHostChange.+let guardrailResolveTimer: ReturnType<typeof setInterval> | null = null+const GUARDRAIL_RESOLVE_INTERVAL_MS = 300_000let contextMapperPollRunner: { trigger(): void; stop(): void } | null = nulllet mcpStatusHeartbeatTimer: ReturnType<typeof setInterval> | null = nulllet lastServerState: Map<string, string> = new Map()@@ -996,6 +1002,26 @@ function stopMcpStatusHeartbeat(): void {/*** Handle host configuration change.*/+/**+ * Resolve the current Host's installed-hook references (§8.2) into runtime+ * descriptors and apply them to the agent. Live-callable: run at boot, on every+ * Host change (onHostChange), on a referenced-LlmHook change (LlmHookWatcher),+ * and on a periodic backstop tick — so an admin edit takes effect without a pod+ * restart.+ */+async function applyResolvedGuardrails(): Promise<void> {+ if (!agent) return+ const hostGuardrails = currentHost?.spec.guardrails ?? config.guardrailsConfig+ const resolved = await resolveGuardrailHookDescriptors(hostGuardrails, {+ getLlmHook,+ llmHooksNamespace: config.llmHooksNamespace,+ }).catch(err => {+ console.error('[Main] Guardrail hook resolution failed; running without installed hooks:', err)+ return []+ })+ agent.setGuardrailsConfig(withResolvedHookDescriptors(hostGuardrails, resolved))+}+async function onHostChange(host: HostCRD): Promise<void> {console.log(`[Main] Host configuration changed: ${host.name}`)@@ -1049,6 +1075,11 @@ async function onHostChange(host: HostCRD): Promise<void> {console.error('[Main] Failed to apply identity files:', err)}}++ // Re-resolve guardrails so a Host.spec.guardrails edit (added/removed hook,+ // changed digest, capability/failMode change) takes effect without a restart+ // (§8.2 "resolution is live").+ await applyResolvedGuardrails()}/**@@ -1262,18 +1293,15 @@ async function initializeAgent(): Promise<void> {const approvalCfg = currentHost?.spec.approval || config.approvalConfigagent.setApprovalConfig(approvalCfg)- // Guardrails (spec §5/§6) — Host block, dev-env fallback. Absent = today.- // Resolve installed-hook references (§8.2) into runtime descriptors so the- // LLM lane actually calls the hook pods; dangling/invalid refs degrade to skip.- const hostGuardrails = currentHost?.spec.guardrails ?? config.guardrailsConfig- const resolvedHookDescriptors = await resolveGuardrailHookDescriptors(hostGuardrails, {- getLlmHook,- llmHooksNamespace: config.llmHooksNamespace,- }).catch(err => {- console.error('[Main] Guardrail hook resolution failed; running without installed hooks:', err)- return []- })- agent.setGuardrailsConfig(withResolvedHookDescriptors(hostGuardrails, resolvedHookDescriptors))+ // Guardrails (spec §5/§6) — resolve installed-hook references (§8.2) into+ // runtime descriptors so the LLM lane actually calls the hook pods.+ await applyResolvedGuardrails()+ if (!guardrailResolveTimer) {+ guardrailResolveTimer = setInterval(+ () => void applyResolvedGuardrails(),+ GUARDRAIL_RESOLVE_INTERVAL_MS+ )+ }validateApprovalConfig(approvalCfg, knownNativeToolNames, config.nativeTool.httpAllowlist)console.log(`[Main] Approval system: ${config.enableApproval ? 'ENABLED' : 'DISABLED'} (policy: ${approvalCfg?.defaultPolicy || 'none/cli_only'})`@@ -2494,10 +2522,15 @@ async function shutdown(signal: string): Promise<void> {// Stop components in orderstopRuntimeAuthProactiveRefresh()hostWatcher?.stop()+ llmHookWatcher?.stop()configStore?.stop()stopContextMapperPolling()stopMcpStatusHeartbeat()statelessHeartbeat?.stop()+ if (guardrailResolveTimer) {+ clearInterval(guardrailResolveTimer)+ guardrailResolveTimer = null+ }if (agent) {await agent.stop()@@ -2676,6 +2709,23 @@ async function startProductionMode(): Promise<void> {hostWatcher = new HostWatcher(config.hostName)await hostWatcher.start(onHostChange, onHostDelete)+ // Watch this tenant's LlmHook CRs so a hook-CR edit (caps/path/failMode/target)+ // that the current Host references re-resolves guardrails live (§8.2), without+ // a restart. Namespace-scoped, so only this tenant's hooks are surfaced.+ llmHookWatcher = new LlmHookWatcher()+ await llmHookWatcher.start(name => {+ const hooks = (+ currentHost?.spec.guardrails as { hooks?: Record<string, Array<{ id?: string }>> } | undefined+ )?.hooks+ const referenced =+ !!hooks &&+ Object.values(hooks).some(refs => Array.isArray(refs) && refs.some(r => r?.id === name))+ if (referenced) {+ console.log(`[Main] Referenced LlmHook ${name} changed — re-resolving guardrails`)+ void applyResolvedGuardrails()+ }+ })+// Start MCP status heartbeat (keeps observedAt fresh for the desktop poll;// each tick no-ops until the MCP manager exists)startMcpStatusHeartbeat()