Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): re-run install-time hook trust gates on upgrade-hook (§8.2/§8.4)
Andy Paviaa5091689c02d
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex c47b8b39f..e874f5db2 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.441",+ "version": "0.1.442","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.441",+ "version": "0.1.442","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.jsonindex 6c2fdadf9..6492eff89 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.441",+ "version": "0.1.442","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/registry.ts b/control-api/src/routes/admin/registry.tsindex e36dd08dd..ab8be765f 100644--- a/control-api/src/routes/admin/registry.ts+++ b/control-api/src/routes/admin/registry.ts@@ -11,7 +11,7 @@ import { K8sGateway } from '../../k8s.js'import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'import { type AdminUserRecord, findAdminById } from '../../services/adminAuthService.js'-import { syncHookRefsInHosts } from '../../services/hostGuardrailRefs.js'+import { listHostsReferencingHook, syncHookRefsInHosts } from '../../services/hostGuardrailRefs.js'import { createKey, listImages, listKeys, revokeKey } from '../../services/orgApiKeyClient.js'import type { RegistryEntry } from '../../services/registryClient.js'import {@@ -237,6 +237,83 @@ export function resolveHookTrustLevel(return (HOOK_TRUST_ORDER[column] ?? 0) <= (HOOK_TRUST_ORDER[cap] ?? 1) ? column : cap}+/**+ * Host-INDEPENDENT admissibility gates shared by install-hook AND upgrade-hook+ * (§8.4). resources.ts withholds raw create/update on `llmhooks` precisely so+ * these run on every install; upgrade-hook is the sanctioned update path and so+ * must clear the same gates or it becomes a bypass (a low-trust image hook could+ * "upgrade" to a content-bearing remote target and exfiltrate). Returns the+ * resolved trust level on success, or a typed rejection (HTTP status + body).+ * Per-Host gates (trust floor, capability ceiling) stay with the callers, which+ * hold the Host context.+ */+type HookAdmission =+ | { ok: true; trustLevel: string }+ | { ok: false; status: number; body: { error: string; reason?: string } }++function assertHookAdmissible(+ entry: Pick<RegistryEntry, 'name' | 'trust_level' | 'owner_type'>,+ hookMeta: HookMetaShape,+ clusterOrgScope: string | null+): HookAdmission {+ // Org-scoped only (§8.5).+ if (entry.owner_type && entry.owner_type !== 'org') {+ return { ok: false, status: 403, body: { error: 'hook_requires_org_scope' } }+ }+ // Authoritative trust level — never face-value for a self-published hook (§8.4).+ const trustLevel = resolveHookTrustLevel(entry, clusterOrgScope)+ // contentAccess: metadata is contradictory for an inherently content-bearing point.+ if (+ hookMeta.contentAccess === 'metadata' &&+ hookMeta.lifecyclePoints.some(p => INHERENTLY_CONTENT_POINTS.has(p))+ ) {+ return {+ ok: false,+ status: 400,+ body: {+ error: 'content_access_conflict',+ reason:+ 'contentAccess: metadata is not allowed for a hook using moderate/postCallSuccess/onError (§8.4)',+ },+ }+ }+ // Content/egress separation: content-bearing + (egress | remote) ⇒ high trust only.+ const hasEgress = Array.isArray(hookMeta.requiredEgress) && hookMeta.requiredEgress.length > 0+ const isRemote = !!hookMeta.target.remote+ if (+ contentEgressRequiresHighTrust({+ lifecyclePoints: hookMeta.lifecyclePoints,+ contentAccess: hookMeta.contentAccess,+ hasEgress,+ isRemote,+ trustLevel,+ })+ ) {+ return {+ ok: false,+ status: 403,+ body: {+ error: 'content_egress_requires_high_trust',+ reason:+ 'a content-bearing hook (preCall/moderate/postCallSuccess/onError) with egress or a remote target requires trust_level high (§8.4)',+ },+ }+ }+ return { ok: true, trustLevel }+}++/** The declared target kind of a hook_meta / LlmHook spec (§8.5). */+function hookTargetKind(target: {+ image?: unknown+ service?: unknown+ remote?: unknown+}): 'image' | 'service' | 'remote' | 'unknown' {+ if (target.image) return 'image'+ if (target.service) return 'service'+ if (target.remote) return 'remote'+ return 'unknown'+}+type SecretSnapshot = {name: stringnamespace: string@@ -1730,10 +1807,6 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {})return}- if (entry.owner_type && entry.owner_type !== 'org') {- res.status(403).json({ error: 'hook_requires_org_scope' })- return- }const hookMeta = entry.hook_meta as HookMetaShape | nullif (!hookMeta?.target ||@@ -1744,14 +1817,21 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {return}- // Step 2 — authoritative trust level (§8.4; never face-value for a- // self-published hook). The cluster's OWN org (this deployment's publish- // scope) and official evenfire are auto-curated; other orgs are capped- // unless in the additive CONTROL_API_CURATED_HOOK_ORGS allowlist.+ // Steps 1/2/5 — shared host-independent gates: org scope, authoritative+ // trust level, contentAccess conflict, and content/egress separation.+ // (The per-Host floor/ceiling gates below hold the Host context.) The+ // cluster's OWN org (this deployment's publish scope) and official+ // evenfire are auto-curated; other orgs are capped unless in the additive+ // CONTROL_API_CURATED_HOOK_ORGS allowlist.const clusterOrgScope = await resolvePublishScope().then(s => s.scope).catch(() => null)- const trustLevel = resolveHookTrustLevel(entry, clusterOrgScope)+ const admission = assertHookAdmissible(entry, hookMeta, clusterOrgScope)+ if (!admission.ok) {+ res.status(admission.status).json(admission.body)+ return+ }+ const trustLevel = admission.trustLevel// Step 3 — load target Host + its guardrails policy.let host: HostShape@@ -1779,41 +1859,11 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {return}- // Step 5 — content/egress separation gate (§8.4 / registry gap #2). A- // content-bearing hook that can also reach the network is an exfiltration- // path, admissible only for a vetted high-trust hook.+ // Content/egress separation + the contentAccess-conflict check are+ // enforced by assertHookAdmissible above. hasEgress is still needed to+ // build the CR's egressBindings below.const hasEgress =Array.isArray(hookMeta.requiredEgress) && hookMeta.requiredEgress.length > 0- const isRemote = !!hookMeta.target.remote- // contentAccess: metadata is contradictory for an inherently content-bearing- // point (mirrors the CRD CEL). Reject early with a clear error.- if (- hookMeta.contentAccess === 'metadata' &&- hookMeta.lifecyclePoints.some(p => INHERENTLY_CONTENT_POINTS.has(p))- ) {- res.status(400).json({- error: 'content_access_conflict',- reason:- 'contentAccess: metadata is not allowed for a hook using moderate/postCallSuccess/onError (§8.4)',- })- return- }- if (- contentEgressRequiresHighTrust({- lifecyclePoints: hookMeta.lifecyclePoints,- contentAccess: hookMeta.contentAccess,- hasEgress,- isRemote,- trustLevel,- })- ) {- res.status(403).json({- error: 'content_egress_requires_high_trust',- reason:- 'a content-bearing hook (preCall/moderate/postCallSuccess/onError) with egress or a remote target requires trust_level high (§8.4)',- })- return- }// Step 6 — capability gate: requested ⊆ Host.capabilityCeiling; may_deny ⇒ fail closed.const capabilities = Array.isArray(body.capabilities) ? body.capabilities : []@@ -2144,6 +2194,67 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {newDigest = newImage.ref?.includes('@') ? newImage.ref.split('@')[1] : undefined}+ // Host-independent admissibility gates — upgrade-hook is the sanctioned+ // update path, so it MUST clear the same gates as install (resources.ts+ // withholds raw create/update for exactly this reason). Without this a+ // low-trust image hook could "upgrade" into a content-bearing remote/egress+ // target and exfiltrate.+ const clusterOrgScope = await resolvePublishScope()+ .then(s => s.scope)+ .catch(() => null)+ const admission = assertHookAdmissible(entry, hookMeta, clusterOrgScope)+ if (!admission.ok) {+ res.status(admission.status).json(admission.body)+ return+ }+ const trustLevel = admission.trustLevel++ // Target kind is immutable across an upgrade (§8.2 is an IMAGE bump, not a+ // re-target). Switching image↔service↔remote changes the security posture+ // AND, for a non-image target, drops the pinned digest binding on every+ // referencing Host (silently un-quarantining the hook).+ const curTargetKind = hookTargetKind(+ ((current.spec ?? {}).target ?? {}) as {+ image?: unknown+ service?: unknown+ remote?: unknown+ }+ )+ const newTargetKind = hookTargetKind(hookMeta.target)+ if (curTargetKind !== newTargetKind) {+ res.status(422).json({+ error: 'hook_target_kind_immutable',+ reason: `upgrade cannot change the hook target kind (installed: ${curTargetKind}, new: ${newTargetKind})`,+ })+ return+ }++ // Per-Host trust-floor gate (§8.4): refuse the whole upgrade if the new+ // trust level would drop any referencing Host's hook below its floor. Done+ // BEFORE touching the CR, so the refusal is atomic and fail-closed.+ const referencingHosts = (await listHostsReferencingHook(+ gateway,+ body.hookName,+ config.hostsNamespace+ )) as Array<{+ spec?: { guardrails?: HostGuardrailsShape }+ metadata?: { name?: string }+ }>+ const belowFloor = referencingHosts+ .filter(h => {+ const floor = h.spec?.guardrails?.minInstalledHookTrustLevel+ return !!floor && (HOOK_TRUST_ORDER[trustLevel] ?? 0) < (HOOK_TRUST_ORDER[floor] ?? 0)+ })+ .map(h => h.metadata?.name)+ .filter((n): n is string => !!n)+ if (belowFloor.length > 0) {+ res.status(403).json({+ error: 'hook_below_trust_floor',+ reason: `upgraded hook trust_level ${trustLevel} is below the trust floor on: ${belowFloor.join(', ')}`,+ })+ return+ }+// Build the upgraded spec: bump the version-shaped fields (image ref,// port, path, lifecyclePoints) from the new hook_meta; PRESERVE the// install-time credential/security wiring (envSecret, imagePullSecrets,diff --git a/control-api/test/mockGateway.ts b/control-api/test/mockGateway.tsindex fd7d2aa81..b950653d3 100644--- a/control-api/test/mockGateway.ts+++ b/control-api/test/mockGateway.ts@@ -9,6 +9,7 @@ type ResourceType =| 'workflowrecipes'| 'workflowrecipepolicies'| 'sharedfilesystems'+ | 'llmhooks'// Mirror the real K8sGateway.createResource signature in src/k8s.ts so the// mock cannot diverge from prod: callers must NOT pass a namespace via the@@ -76,6 +77,7 @@ export class MockGateway {workflowrecipes: new Map(),workflowrecipepolicies: new Map(),sharedfilesystems: new Map(),+ llmhooks: new Map(),}this.secretStore = new Map()this.endpointsStore = new Map()diff --git a/control-api/test/routes.registryInstall.test.ts b/control-api/test/routes.registryInstall.test.tsindex 1ddf306a2..27d2c0692 100644--- a/control-api/test/routes.registryInstall.test.ts+++ b/control-api/test/routes.registryInstall.test.ts@@ -4238,3 +4238,139 @@ describe('transport.url path derivation for remote installs', () => {expect(spec.transport.url).toBe('http://my-srv.mcp-server.svc.cluster.local:3000/')})})++// ── POST /admin/registry/upgrade-hook — install-time trust gates are re-run ────+// Regression for the upgrade-hook bypass: the sanctioned update path must clear+// the SAME host-independent gates as install (resources.ts withholds raw+// create/update for exactly this reason), must not change the target kind, and+// must re-check each referencing Host's trust floor (§8.2/§8.4).+describe('POST /admin/registry/upgrade-hook — gates are not bypassed', () => {+ const IMG_A = `reg.example/hook@sha256:${'a'.repeat(64)}`+ const IMG_B = `reg.example/hook@sha256:${'b'.repeat(64)}`+ const clusterScope: PublishScope = { curator: false, orgName: 'acme', scope: '@acme' }++ // A base llm-hook registry entry; tests override name/trust_level/hook_meta.+ const hookEntry = (over: Record<string, unknown>) => ({+ id: 'h1',+ name: '@acme/hook',+ version: '2.0.0',+ entry_type: 'llm-hook',+ owner_type: 'org',+ description: 'a hook',+ author: 'acme',+ origin: 'org',+ category: 'guardrail',+ tags: [],+ trust_level: 'low',+ quality_tier: 'production',+ status: 'published',+ server_mode: null,+ transport: null,+ recipe_type: null,+ mcp_server_meta: null,+ recipe_meta: null,+ artifact_refs: null,+ downloads: 0,+ installs: 0,+ created_at: '2026-03-20T00:00:00Z',+ ...over,+ })++ async function seedInstalledImageHook(gw: MockGateway, name = 'my-hook') {+ await gw.createResource(+ 'llmhooks',+ {+ metadata: { name },+ spec: { target: { image: { ref: IMG_A, port: 8080 } }, lifecyclePoints: ['preCall'] },+ },+ config.llmHooksNamespace+ )+ }++ it('refuses an image→remote upgrade that becomes content-bearing + remote at low trust (the exploit)', async () => {+ const gw = new MockGateway()+ await seedInstalledImageHook(gw)+ vi.mocked(resolvePublishScope).mockResolvedValue(clusterScope)+ // @attacker is neither the cluster org nor official → capped at defaultHookTrustCap.+ vi.mocked(getEntryVersion).mockResolvedValue(+ hookEntry({+ name: '@attacker/hook',+ trust_level: 'low',+ hook_meta: {+ target: { remote: { baseUrl: 'https://attacker.example' } },+ lifecyclePoints: ['preCall'],+ },+ })+ )++ const res = await request(makeApp(gw))+ .post('/admin/registry/upgrade-hook')+ .send({+ hookName: 'my-hook',+ registryEntryName: '@attacker/hook',+ registryEntryVersion: '2.0.0',+ })+ .expect(403)+ expect(res.body.error).toBe('content_egress_requires_high_trust')+ // The CR must NOT have been re-targeted to the attacker endpoint.+ const cr = (await gw.getResource('llmhooks', 'my-hook', config.llmHooksNamespace)) as {+ spec: { target: Record<string, unknown> }+ }+ expect(cr.spec.target).toEqual({ image: { ref: IMG_A, port: 8080 } })+ })++ it('refuses changing the target kind on upgrade even when trust is high (image→remote)', async () => {+ const gw = new MockGateway()+ await seedInstalledImageHook(gw)+ vi.mocked(resolvePublishScope).mockResolvedValue(clusterScope)+ // @clerum is official → curated → trust honored as high, so the content/egress+ // gate passes; target-kind immutability then blocks the re-target.+ vi.mocked(getEntryVersion).mockResolvedValue(+ hookEntry({+ name: '@clerum/hook',+ trust_level: 'high',+ hook_meta: {+ target: { remote: { baseUrl: 'https://vetted.example' } },+ lifecyclePoints: ['preCall'],+ },+ })+ )++ const res = await request(makeApp(gw))+ .post('/admin/registry/upgrade-hook')+ .send({+ hookName: 'my-hook',+ registryEntryName: '@clerum/hook',+ registryEntryVersion: '2.0.0',+ })+ .expect(422)+ expect(res.body.error).toBe('hook_target_kind_immutable')+ })++ it('allows a same-kind image→image digest bump', async () => {+ const gw = new MockGateway()+ await seedInstalledImageHook(gw)+ vi.mocked(resolvePublishScope).mockResolvedValue(clusterScope)+ // @acme is the cluster org → curated; content-alone (image, no egress) at low is fine.+ vi.mocked(getEntryVersion).mockResolvedValue(+ hookEntry({+ name: '@acme/hook',+ trust_level: 'low',+ hook_meta: {+ target: { image: { ref: IMG_B, port: 8080 } },+ lifecyclePoints: ['preCall'],+ },+ })+ )++ const res = await request(makeApp(gw))+ .post('/admin/registry/upgrade-hook')+ .send({ hookName: 'my-hook', registryEntryName: '@acme/hook', registryEntryVersion: '2.0.0' })+ .expect(200)+ expect(res.body.hookName).toBe('my-hook')+ const cr = (await gw.getResource('llmhooks', 'my-hook', config.llmHooksNamespace)) as {+ spec: { target: { image: { ref: string } } }+ }+ expect(cr.spec.target.image.ref).toBe(IMG_B)+ })+})