Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc): fence the recovery-triggered Host delete against recreation (TOCTOU)
Alfredo Lopez15bdfb793f3c
diff --git a/host-context-controller/src/hostReconciler.test.ts b/host-context-controller/src/hostReconciler.test.tsindex 76440acdb..c6d258c89 100644--- a/host-context-controller/src/hostReconciler.test.ts+++ b/host-context-controller/src/hostReconciler.test.ts@@ -12,6 +12,7 @@ import {} from '../test/__fixtures__/testMocks'import { HostFleetReconcileError, HostReconciler, destructiveCleanupAllowed } from './hostReconciler'import { HostK8sRequestTimeoutError } from './k8s/hostK8sApiClient'+import { registry } from './metrics'import { HostCRD } from './types'function deferred<T = void>(): {@@ -384,6 +385,19 @@ describe('HostReconciler fleet failure isolation', () => {})})+/**+ * Current value of clerum_hcc_host_delete_cleanup_total for one `outcome`+ * label. Read from the live HCC registry (metrics are NOT mocked here), so a+ * skip that fails to record is caught rather than passing silently.+ */+async function readHostDeleteCleanupOutcome(outcome: string): Promise<number> {+ const metric = registry.getSingleMetric('clerum_hcc_host_delete_cleanup_total')+ if (!metric) throw new Error('clerum_hcc_host_delete_cleanup_total is not registered')+ const snapshot = await metric.get()+ const match = snapshot.values.find(entry => entry.labels.outcome === outcome)+ return match?.value ?? 0+}+function makeCleanupReconciler(customApi: { getNamespacedCustomObject: ReturnType<typeof vi.fn> }) {return new HostReconciler({} as k8s.KubeConfig, {appsApi: asAppsApi(createMockAppsApi()),@@ -718,6 +732,60 @@ describe('HostReconciler delete serialization', () => {await Promise.all([reconcilePromise, deletePromise])expect(order).toEqual(['reconcile:start', 'reconcile:end', 'delete:start', 'delete:end'])})++ // Recovery-path TOCTOU parity with the F2 fence in collectHostCleanupFailures.+ // The recovery delete (k8sClient.dispatchRecoveredHostDelete) diffs LIST-time+ // names only; a same-name Host recreated AFTER that diff and admitted to the+ // per-Host chain FIRST would otherwise have its freshly-reconciled bundle —+ // workspace PVC, per-Host RBAC, runtime-token Secret, channel-reader+ // resources, NetworkPolicies — wiped by the stale delete queued behind it.+ it('suppresses the delete when skipIf reports a recreation inside the admission window', async () => {+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: vi.fn() })+ const internals = reconciler as unknown as {+ deleteHostRuntimeResources(name: string, namespace: string): Promise<void>+ }+ const del = vi.spyOn(internals, 'deleteHostRuntimeResources').mockResolvedValue()+ const before = await readHostDeleteCleanupOutcome('superseded')++ // The fence is evaluated INSIDE the serializer, so it observes the cache as+ // of admission — not as of enqueue. Here it reports "recreated".+ let evaluatedInsideSerializer = false+ await reconciler.reconcileDelete('recreated-in-window', 'mcp-host', {+ skipIf: () => {+ evaluatedInsideSerializer = true+ return true+ },+ })++ expect(evaluatedInsideSerializer).toBe(true)+ expect(del).not.toHaveBeenCalled()+ // The skip is observable, not silent, and reuses the watch path's vocabulary.+ expect(await readHostDeleteCleanupOutcome('superseded')).toBe(before + 1)+ })++ it('still deletes the bundle when skipIf reports the Host really is gone', async () => {+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: vi.fn() })+ const internals = reconciler as unknown as {+ deleteHostRuntimeResources(name: string, namespace: string): Promise<void>+ }+ const del = vi.spyOn(internals, 'deleteHostRuntimeResources').mockResolvedValue()++ await reconciler.reconcileDelete('really-gone', 'mcp-host', { skipIf: () => false })++ expect(del).toHaveBeenCalledWith('really-gone', 'mcp-host')+ })++ it('keeps the existing unconditional behavior for callers that pass no options', async () => {+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: vi.fn() })+ const internals = reconciler as unknown as {+ deleteHostRuntimeResources(name: string, namespace: string): Promise<void>+ }+ const del = vi.spyOn(internals, 'deleteHostRuntimeResources').mockResolvedValue()++ await reconciler.reconcileDelete('no-opts', 'mcp-host')++ expect(del).toHaveBeenCalledWith('no-opts', 'mcp-host')+ })})describe('HostReconciler destructiveCleanupAllowed property', () => {diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex 57c6f56ae..1d03f1719 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -52,6 +52,7 @@ import {} from './utils'import {hostCleanupDeferredTotal,+ hostDeleteCleanupTotal,hostReconcileDurationSeconds,hostReconcileInFlight,hostReconcileQueueWaitSeconds,@@ -3791,11 +3792,38 @@ export class HostReconciler {)}- async reconcileDelete(name: string, namespace: string): Promise<void> {+ /**+ * Delete a Host's runtime bundle.+ *+ * `opts.skipIf` is an OPTIONAL fence evaluated INSIDE the per-Host serializer,+ * immediately before anything destructive runs. Callers whose "this Host is+ * gone" decision was made BEFORE admission (the watch-recovery diff, which+ * compares LIST-time names) pass it so a same-name Host recreated during the+ * admission window is not wiped: the recreation's ADDED sets the cache and+ * enters this Host's chain FIRST, its reconcile rebuilds the bundle, and only+ * then does the stale delete reach the front of the strict-FIFO queue.+ * Ownership labels cannot discriminate here — the rebuilt bundle carries+ * identical `clerum.io/host` + managed-by labels — and no uid is available on+ * that path, so cache presence at admission is the correct fence. This+ * mirrors the F2/#827 in-serializer re-check in collectHostCleanupFailures.+ *+ * Callers that omit `opts` keep the previous unconditional behavior exactly.+ */+ async reconcileDelete(+ name: string,+ namespace: string,+ opts?: { skipIf?: () => boolean }+ ): Promise<void> {// A DELETED event must not race an in-flight create/update for the same// Host: route it through the same per-Host serializer as reconcile(). The// global convergence tail no longer provides this ordering.await this.lifecycle.serializeByHost(name, async () => {+ if (opts?.skipIf?.()) {+ // Same vocabulary the watch path already reports for this condition+ // (reconcileHostWatchEvent), so the skip is observable, not silent.+ hostDeleteCleanupTotal.inc({ outcome: 'superseded' })+ return+ }await this.deleteHostRuntimeResources(name, namespace)this.clearStatus(name)this.desktopHosts.delete(name)diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 71510b360..281d44568 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -3195,9 +3195,60 @@ describe('McpServerWatcher Host watch generation', () => {[{ name: 'live-host', namespace: 'mcp-host', uid: 'u1', spec: { host: 'live-host' } }],new Set(['live-host', 'gone-host']))- await vi.waitFor(() => expect(reconcileDelete).toHaveBeenCalledWith('gone-host', 'mcp-host'))+ await vi.waitFor(() =>+ expect(reconcileDelete).toHaveBeenCalledWith('gone-host', 'mcp-host', expect.anything())+ )// A Host still present in the fresh snapshot is never deleted.- expect(reconcileDelete).not.toHaveBeenCalledWith('live-host', 'mcp-host')+ expect(reconcileDelete).not.toHaveBeenCalledWith(+ 'live-host',+ 'mcp-host',+ expect.anything()+ )+ watcher.stop()+ })++ // The recovery diff resolves absence at LIST time. Between that diff and the+ // moment the delete is admitted to the per-Host serializer, the recreation's+ // ADDED can land: the watch callback sets `this.hosts` SYNCHRONOUSLY and+ // enters the per-Host chain FIRST, while the fire-and-forget dispatch queues+ // the delete SECOND. serializeByHost is strict FIFO, so without a fence the+ // new bundle is created and then wiped. The fence must therefore read the+ // LIVE cache at admission, not a value captured at enqueue time.+ //+ // This is the case the sibling recreation test does NOT cover: there the+ // recreated Host is present in the snapshot, so enqueueRecoveredHostDeletes+ // short-circuits on snapshotNames.has(name) and never dispatches at all.+ it('recovery delete carries a live-cache fence for a Host recreated during admission (#827 F2 parity)', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcileDelete = vi+ .spyOn(watcher.getHostReconciler(), 'reconcileDelete')+ .mockResolvedValue(undefined)+ // "ghost" is absent from the fresh authoritative snapshot → genuinely+ // disappeared → dispatched for delete.+ ;(watcher as any).enqueueRecoveredHostDeletes([], new Set(['ghost']))+ await vi.waitFor(() => expect(reconcileDelete).toHaveBeenCalled())++ const [, , opts] = reconcileDelete.mock.calls[0] as [+ string,+ string,+ { skipIf?: () => boolean } | undefined,+ ]+ expect(opts?.skipIf, 'the recovery delete must carry a skipIf fence').toBeTypeOf('function')++ // Cache does not hold the name → the Host really is gone → do NOT skip.+ expect(opts!.skipIf!()).toBe(false)++ // The recreation lands in the live cache during the admission window.+ ;(watcher as any).hosts.set('ghost', {+ name: 'ghost',+ namespace: 'mcp-host',+ uid: 'uid-recreated',+ generation: 1,+ spec: { host: 'ghost' },+ })+ // Same fence, re-evaluated at admission → skip the destructive delete.+ expect(opts!.skipIf!()).toBe(true)watcher.stop()})diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex 09effb0e1..e850c29ae 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -1033,7 +1033,20 @@ export class McpServerWatcher implements McpServerProvider {// cleanup.hostDeleteCleanupTotal.inc({ outcome: 'confirmed' })try {- await this.hostReconciler.reconcileDelete(name, config.hostNamespace)+ // F2/#827 TOCTOU parity: absence was resolved at LIST time, but the+ // recreation's ADDED can be delivered while the watch replays from the+ // snapshot's resourceVersion — that callback sets `this.hosts`+ // SYNCHRONOUSLY and enters this Host's chain FIRST, while this+ // fire-and-forget dispatch queues the delete SECOND. serializeByHost is+ // strict FIFO, so without this fence the rebuilt bundle (workspace PVC,+ // per-Host RBAC, runtime-token Secret, channel-reader resources,+ // NetworkPolicies) would be created and then wiped. Ownership labels+ // cannot discriminate — the rebuilt bundle carries identical labels — and+ // a name absent from the snapshot has no uid to compare, so live-cache+ // presence AT ADMISSION is the fence, exactly as in the F2 orphan sweep.+ await this.hostReconciler.reconcileDelete(name, config.hostNamespace, {+ skipIf: () => this.hosts.has(name),+ })hostDeleteCleanupTotal.inc({ outcome: 'completed' })} catch (error) {hostDeleteCleanupTotal.inc({ outcome: 'retried' })