Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(guardrails): referential integrity on hook uninstall (§8.2/N11)

Andy Paviacff961d7ec1e
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 9b40bbd85..fe8a44aa0 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.437",
+ "version": "0.1.438",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.437",
+ "version": "0.1.438",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-api/package.json b/control-api/package.json
index 513de4d55..8d342b02d 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.437",
+ "version": "0.1.438",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.ts
index 941ae84b1..d96901a86 100644
--- a/control-api/src/routes/admin/resources.ts
+++ b/control-api/src/routes/admin/resources.ts
@@ -5,6 +5,7 @@ import { enforceNamespace } from '../../http/namespaceAudit.js'
import { validateCommunicationChannelSpec } from '../../http/validateCommunicationChannelSpec.js'
import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'
import { K8sGateway } from '../../k8s.js'
+import { stripHookRefFromHosts } from '../../services/hostGuardrailRefs.js'
import { K8sConflictError } from '../../services/resourceService.js'
import { ClerumResourceType } from '../../types.js'
import {
@@ -685,16 +686,22 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {
})
)
- // Uninstall. Deletes the LlmHook CR; host-context-controller garbage-collects
- // the shared pod once the last referencing hook is gone. Removing the {id}
- // reference from any Host.spec.guardrails.hooks is owned by the install/uninstall
- // saga (registry.ts) alongside the credential-Secret lifecycle.
+ // Uninstall. Referential integrity (§8.2): strip the `{id}` reference from every
+ // referencing Host's guardrails.hooks FIRST, so no dangling ref is ever visible
+ // (mcp-host can't fail-closed on a vanished CR — N11), THEN delete the LlmHook
+ // CR; host-context-controller garbage-collects the shared pod once the last
+ // referencing hook is gone.
router.delete(
`${LLMHOOK_PATTERN}/:name`,
asyncHandler(async (req, res) => {
const { plural, ns } = resolveResource(req.params.resource)!
+ const unlinkedHosts = await stripHookRefFromHosts(
+ gateway,
+ req.params.name,
+ config.hostsNamespace
+ )
const deleted = await gateway.deleteResource(plural, req.params.name, ns)
- res.status(200).json(deleted)
+ res.status(200).json({ ...(deleted as object), unlinkedHosts })
})
)
diff --git a/control-api/src/services/__tests__/hostGuardrailRefs.test.ts b/control-api/src/services/__tests__/hostGuardrailRefs.test.ts
new file mode 100644
index 000000000..9815b4967
--- /dev/null
+++ b/control-api/src/services/__tests__/hostGuardrailRefs.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest'
+import type { K8sGateway } from '../../k8s.js'
+import {
+ listHostsReferencingHook,
+ stripHookRefFromHosts,
+ syncHookRefsInHosts,
+} from '../hostGuardrailRefs.js'
+
+type Host = {
+ metadata: { name: string }
+ spec: { guardrails?: { hooks?: Record<string, Array<{ id: string; digest?: string }>> } }
+}
+
+function gatewayWith(hosts: Host[]) {
+ const store = new Map<string, Host>(hosts.map(h => [h.metadata.name, structuredClone(h)]))
+ const gateway = {
+ listResource: async (plural: string) => (plural === 'hosts' ? [...store.values()] : []),
+ updateResource: async (_p: string, name: string, body: { spec: Host['spec'] }) => {
+ const cur = store.get(name)!
+ store.set(name, { ...cur, spec: body.spec })
+ return store.get(name)
+ },
+ } as unknown as K8sGateway
+ return { gateway, store }
+}
+
+const host = (
+ name: string,
+ hooks: Record<string, Array<{ id: string; digest?: string }>>
+): Host => ({
+ metadata: { name },
+ spec: { guardrails: { hooks } },
+})
+
+describe('hostGuardrailRefs', () => {
+ it('listHostsReferencingHook returns only Hosts that reference the id', async () => {
+ const { gateway } = gatewayWith([
+ host('a', { preCall: [{ id: 'hook-x' }] }),
+ host('b', { moderate: [{ id: 'hook-y' }] }),
+ host('c', {}),
+ ])
+ const hosts = await listHostsReferencingHook(gateway, 'hook-x', 'mcp-host')
+ expect(hosts.map(h => h.metadata?.name)).toEqual(['a'])
+ })
+
+ it('stripHookRefFromHosts removes the ref from every phase + host, keeping others', async () => {
+ const { gateway, store } = gatewayWith([
+ host('a', { preCall: [{ id: 'hook-x' }, { id: 'keep' }], moderate: [{ id: 'hook-x' }] }),
+ host('b', { postCallSuccess: [{ id: 'hook-x' }] }),
+ ])
+ const touched = await stripHookRefFromHosts(gateway, 'hook-x', 'mcp-host')
+ expect(touched.sort()).toEqual(['a', 'b'])
+ // host a: hook-x gone from both phases; 'keep' stays; empty moderate removed.
+ expect(store.get('a')!.spec.guardrails?.hooks).toEqual({ preCall: [{ id: 'keep' }] })
+ // host b: the only ref removed → empty hooks map.
+ expect(store.get('b')!.spec.guardrails?.hooks).toEqual({})
+ })
+
+ it('syncHookRefsInHosts sets the ref to exactly the new phases + digest', async () => {
+ const { gateway, store } = gatewayWith([
+ // referenced today in preCall+moderate at the old digest.
+ host('a', {
+ preCall: [{ id: 'hook-x', digest: 'sha256:OLD' }],
+ moderate: [{ id: 'hook-x', digest: 'sha256:OLD' }],
+ }),
+ ])
+ await syncHookRefsInHosts(
+ gateway,
+ 'hook-x',
+ ['preCall', 'postCallSuccess'],
+ 'sha256:NEW',
+ 'mcp-host'
+ )
+ const hooks = store.get('a')!.spec.guardrails?.hooks
+ // moderate dropped, postCallSuccess added, new digest everywhere.
+ expect(hooks).toEqual({
+ preCall: [{ id: 'hook-x', digest: 'sha256:NEW' }],
+ postCallSuccess: [{ id: 'hook-x', digest: 'sha256:NEW' }],
+ })
+ })
+})
diff --git a/control-api/src/services/hostGuardrailRefs.ts b/control-api/src/services/hostGuardrailRefs.ts
new file mode 100644
index 000000000..d441b9190
--- /dev/null
+++ b/control-api/src/services/hostGuardrailRefs.ts
@@ -0,0 +1,117 @@
+/**
+ * Host↔LlmHook referential-integrity helpers (spec §8.2).
+ *
+ * A hook is referenced from `Host.spec.guardrails.hooks[phase]` as `{ id, digest }`.
+ * These keep those references consistent with the hook's lifecycle so mcp-host
+ * never sees an inconsistent state:
+ * - uninstall → strip the ref from every referencing Host (no dangling ref,
+ * which mcp-host can't fail-closed on — N11).
+ * - upgrade → move the CR image bump and the admin-pinned Host-ref digests
+ * together (an uncoordinated bump trips the digest pin and quarantines the
+ * hook).
+ */
+import { K8sGateway } from '../k8s.js'
+
+type HookRef = { id: string; digest?: string }
+type HostGuardrails = { hooks?: Record<string, HookRef[]>; [k: string]: unknown }
+interface HostResource {
+ metadata?: { name?: string }
+ spec?: { guardrails?: HostGuardrails; [k: string]: unknown }
+}
+
+function referencesHook(host: HostResource, hookId: string): boolean {
+ const hooks = host.spec?.guardrails?.hooks
+ return (
+ !!hooks &&
+ Object.values(hooks).some(arr => Array.isArray(arr) && arr.some(r => r?.id === hookId))
+ )
+}
+
+/** Hosts (in `hostsNamespace`) whose `guardrails.hooks` reference the LlmHook id. */
+export async function listHostsReferencingHook(
+ gateway: K8sGateway,
+ hookId: string,
+ hostsNamespace: string
+): Promise<HostResource[]> {
+ const items = (await gateway.listResource('hosts', hostsNamespace)) as HostResource[]
+ return (items ?? []).filter(h => referencesHook(h, hookId))
+}
+
+async function writeHostHooks(
+ gateway: K8sGateway,
+ host: HostResource,
+ hooks: Record<string, HookRef[]>,
+ hostsNamespace: string
+): Promise<void> {
+ const name = host.metadata?.name
+ if (!name) return
+ const guardrails = { ...(host.spec?.guardrails ?? {}), hooks }
+ await gateway.updateResource(
+ 'hosts',
+ name,
+ { spec: { ...host.spec, guardrails } },
+ hostsNamespace
+ )
+}
+
+/** Drop `hookId` from every phase (removing now-empty phases). */
+function withoutHook(hooks: Record<string, HookRef[]>, hookId: string): Record<string, HookRef[]> {
+ const next: Record<string, HookRef[]> = { ...hooks }
+ for (const phase of Object.keys(next)) {
+ const filtered = next[phase].filter(r => r.id !== hookId)
+ if (filtered.length > 0) next[phase] = filtered
+ else delete next[phase]
+ }
+ return next
+}
+
+/**
+ * Referential integrity on uninstall: remove every `{ id: hookId }` reference
+ * from all referencing Hosts. Call this BEFORE deleting the LlmHook CR so a
+ * dangling ref never exists. Returns the Host names touched.
+ */
+export async function stripHookRefFromHosts(
+ gateway: K8sGateway,
+ hookId: string,
+ hostsNamespace: string
+): Promise<string[]> {
+ const hosts = await listHostsReferencingHook(gateway, hookId, hostsNamespace)
+ const touched: string[] = []
+ for (const host of hosts) {
+ await writeHostHooks(
+ gateway,
+ host,
+ withoutHook(host.spec?.guardrails?.hooks ?? {}, hookId),
+ hostsNamespace
+ )
+ if (host.metadata?.name) touched.push(host.metadata.name)
+ }
+ return touched
+}
+
+/**
+ * Coordinated upgrade: set the hook's reference on every referencing Host to
+ * EXACTLY `lifecyclePoints` with the new `digest`, so the CR image bump and the
+ * admin-pinned Host-ref digests move together. Returns the Host names touched.
+ */
+export async function syncHookRefsInHosts(
+ gateway: K8sGateway,
+ hookId: string,
+ lifecyclePoints: string[],
+ digest: string | undefined,
+ hostsNamespace: string
+): Promise<string[]> {
+ const hosts = await listHostsReferencingHook(gateway, hookId, hostsNamespace)
+ const touched: string[] = []
+ for (const host of hosts) {
+ const hooks = withoutHook(host.spec?.guardrails?.hooks ?? {}, hookId)
+ for (const phase of lifecyclePoints) {
+ const arr = hooks[phase] ? [...hooks[phase]] : []
+ arr.push({ id: hookId, ...(digest ? { digest } : {}) })
+ hooks[phase] = arr
+ }
+ await writeHostHooks(gateway, host, hooks, hostsNamespace)
+ if (host.metadata?.name) touched.push(host.metadata.name)
+ }
+ return touched
+}