Skip to content

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

TypeScript

fix(control-api): close the four P1 review findings on pull-secret provisioning

Jose Ramirez0626aa7fa3af
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 29fd2274d..5931d6f98 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.406",
+ "version": "0.1.407",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.406",
+ "version": "0.1.407",
"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 7d51e6fb2..3c16cbba4 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.406",
+ "version": "0.1.407",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/config.ts b/control-api/src/config.ts
index 86c02e143..240f0d6d2 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -102,6 +102,7 @@ type Config = {
usageRollupDailyIntervalMs: number
usageRetentionIntervalMs: number
budgetReservationSweepIntervalMs: number
+ registryPullSecretReconcileIntervalMs: number
budgetReservationTtlSeconds: number
approvalRetentionDays: number
userApprovalRequestArchiveCronEnabled: boolean
@@ -599,6 +600,15 @@ export const config: Config = {
budgetReservationSweepIntervalMs: Number(
process.env.BUDGET_RESERVATION_SWEEP_INTERVAL_MS || 60_000
),
+ // How often to re-assert the platform image-pull credential. This is a standing
+ // invariant, not a fast path: a WorkflowRecipe created by `kubectl apply` or the WRC
+ // `deploy_recipe` tool never touches control-api, so the credential has to be there
+ // already. Installs still provision synchronously, so this interval only bounds how long
+ // a CRD created OUTSIDE control-api waits. Coarse (10 min) on purpose — each tick is a
+ // few reads and no mint once the cluster is healthy.
+ registryPullSecretReconcileIntervalMs: Number(
+ process.env.REGISTRY_PULL_SECRET_RECONCILE_INTERVAL_MS || 600_000
+ ),
// Danger-zone reservation TTL (§9.8a: ~2-3× the rollup lag, ~5 min). Short
// enough that a hung reservation auto-frees; long enough that real spend has
// reached the rollups before it expires (no double-count on the next check).
diff --git a/control-api/src/main.ts b/control-api/src/main.ts
index 76c7b08ae..b1183e1c0 100644
--- a/control-api/src/main.ts
+++ b/control-api/src/main.ts
@@ -18,6 +18,10 @@ import {
stopPluginWorkloadSdkMaintenanceCron,
} from './services/pluginWorkloadSdkMaintenanceCron.js'
import { startRateLimiterCleanup, stopRateLimiterCleanup } from './services/rateLimiterService.js'
+import {
+ reconcileRegistryPullSecret,
+ startRegistryPullSecretReconcileCron,
+} from './services/registryPullSecretReconcileCron.js'
import {
startWorkflowApprovalTraceProjector,
stopWorkflowApprovalTraceProjector,
@@ -88,6 +92,13 @@ async function main(): Promise<void> {
const gateway = new K8sGateway(config.namespace)
+ // Assert the platform image-pull credential up front and then on a timer. WRC injects
+ // the reference for ANY WorkflowRecipe, including ones created by `kubectl apply` or the
+ // `deploy_recipe` tool that control-api never sees — so provisioning cannot only happen
+ // on our own install routes. Non-fatal: an unconnected cluster logs and retries.
+ void reconcileRegistryPullSecret(gateway)
+ startRegistryPullSecretReconcileCron(gateway, config.registryPullSecretReconcileIntervalMs)
+
if (config.workflowRunsArchiveCronEnabled) {
startWorkflowRunsArchiveCron({
gateway,
diff --git a/control-api/src/routes/admin/registry.ts b/control-api/src/routes/admin/registry.ts
index 1d8587d87..22f2b0004 100644
--- a/control-api/src/routes/admin/registry.ts
+++ b/control-api/src/routes/admin/registry.ts
@@ -2144,6 +2144,20 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {
body.registryEntryVersion
)
+ // Ensure the platform pull credential before the CRD that will reference it.
+ // Keyed on the INCOMING spec: an upgrade is exactly how a recipe moves from a
+ // public image to a private one, and without this the new CRD persists and then
+ // fails at pull time while the request returns 200.
+ if (recipeReferencesPlatformImage(recipeSpec)) {
+ try {
+ await ensureRegistryPullSecrets(gateway, platformWorkloadNamespaces())
+ } catch (err) {
+ const mapped = pullSecretErrorResponse(err)
+ res.status(mapped.status).json(mapped.body)
+ return
+ }
+ }
+
await updateResourceWithConflictRetry(
gateway,
'workflowrecipes',
diff --git a/control-api/src/services/registryPullSecretReconcileCron.ts b/control-api/src/services/registryPullSecretReconcileCron.ts
new file mode 100644
index 000000000..ca600041b
--- /dev/null
+++ b/control-api/src/services/registryPullSecretReconcileCron.ts
@@ -0,0 +1,92 @@
+/**
+ * Keeps the platform image-pull credential present as a STANDING INVARIANT, rather than
+ * as a side effect of control-api's own install routes.
+ *
+ * Why this exists (see docs/architecture/registry-pull-secret-recipe-workloads.md §13.1):
+ * the two halves of the feature have different triggers. WRC injects the
+ * `evenfire-registry-pull` reference on every reconcile, for ANY WorkflowRecipe whose
+ * workload image is ours — but control-api only provisions the Secret on its own
+ * install/upgrade routes. A WorkflowRecipe has three documented creation paths
+ * (docs/crds/workflowrecipe.md): control-api, `kubectl apply`, and the WRC `deploy_recipe`
+ * MCP tool. For the latter two, control-api never sees the CRD, so without this loop the
+ * pod would reference a credential nobody created.
+ *
+ * FAILURE SEMANTICS ARE DELIBERATELY DIFFERENT FROM THE INSTALL PATH.
+ * An install THROWS on a precondition failure, because a user asked for something we
+ * cannot deliver and must be told. This loop LOGS and retries on the next tick: a cluster
+ * that has not finished the registry connect flow is in a normal, expected state, and must
+ * not emit an error every interval or crash-loop. `ensureRegistryPullSecrets` already
+ * distinguishes the two — legitimate no-ops return `skipped`, everything else throws — so
+ * this file's only job is to swallow the throw and try again later.
+ *
+ * Serialization across replicas is handled inside the service by a per-org advisory lock.
+ * That lock is what makes a PERIODIC loop safe at all: without it, two pods on a timer do
+ * not race occasionally, they fight continuously — each pod's mint revokes the other's key
+ * and the fingerprint check then sees divergence, forever.
+ */
+import type { K8sGateway } from '../k8s.js'
+import { rootLogger } from '../observability/logger.js'
+import {
+ ensureRegistryPullSecrets,
+ platformWorkloadNamespaces,
+} from './registryPullSecretService.js'
+
+const log = rootLogger.child({ service: 'registry_pull_secret_reconcile' })
+
+/**
+ * Run one reconcile pass. Never throws — a failure here is a logged warning, because the
+ * cluster may legitimately not be ready to provision yet (no connect flow completed, no
+ * org bound). Returns true when the pass completed without error.
+ */
+export async function reconcileRegistryPullSecret(gateway: K8sGateway): Promise<boolean> {
+ try {
+ const results = await ensureRegistryPullSecrets(gateway, platformWorkloadNamespaces())
+ const changed = [...results.entries()].filter(([, r]) => r === 'created' || r === 'repaired')
+ if (changed.length > 0) {
+ log.info(
+ {
+ event: 'registry_pull_secret_reconciled',
+ namespaces: changed.map(([ns]) => ns),
+ },
+ 'provisioned the registry pull secret outside an install'
+ )
+ }
+ return true
+ } catch (err) {
+ // Expected while a cluster is unconnected or has no org bound yet. Warn, do not throw:
+ // this loop must not turn a normal pre-connect state into recurring errors.
+ log.warn(
+ {
+ event: 'registry_pull_secret_reconcile_skipped',
+ reason: (err as { reason?: string })?.reason,
+ err: err instanceof Error ? err.message : String(err),
+ },
+ 'registry pull secret reconcile did not complete; will retry on the next tick'
+ )
+ return false
+ }
+}
+
+let intervalHandle: ReturnType<typeof setInterval> | null = null
+
+export function startRegistryPullSecretReconcileCron(
+ gateway: K8sGateway,
+ intervalMs: number
+): void {
+ if (intervalHandle) return
+ intervalHandle = setInterval(() => {
+ void reconcileRegistryPullSecret(gateway)
+ }, intervalMs)
+ // Never hold the process open for this.
+ intervalHandle.unref()
+ log.info(
+ { event: 'registry_pull_secret_reconcile_started', intervalMs },
+ 'registry pull secret reconcile cron started'
+ )
+}
+
+export function stopRegistryPullSecretReconcileCron(): void {
+ if (!intervalHandle) return
+ clearInterval(intervalHandle)
+ intervalHandle = null
+}
diff --git a/control-api/src/services/registryPullSecretService.ts b/control-api/src/services/registryPullSecretService.ts
index 449fafb2d..b34017f89 100644
--- a/control-api/src/services/registryPullSecretService.ts
+++ b/control-api/src/services/registryPullSecretService.ts
@@ -53,6 +53,7 @@
*/
import { createHash } from 'node:crypto'
import { config } from '../config.js'
+import { withTransaction } from '../db.js'
import type { K8sGateway } from '../k8s.js'
import { rootLogger } from '../observability/logger.js'
import {
@@ -385,6 +386,33 @@ function classify(current: SecretView | null, host: string): TargetState {
return { kind: 'valid', fingerprint }
}
+/**
+ * Serialize the read->mint->write pass ACROSS PROCESSES.
+ *
+ * The in-process dedupe map only covers one replica, and `replicas: 1` with the default
+ * RollingUpdate means two control-api pods coexist on every deploy. Without this, their
+ * mints interleave: A mints k1, B mints k2 (revoking k1), and whichever writes last leaves
+ * some namespaces holding a revoked key. The fingerprint check makes that self-healing,
+ * but only on the NEXT pass — pulls fail until then.
+ *
+ * `pg_advisory_xact_lock` blocks rather than failing, which is what we want: the second
+ * pod waits, then re-reads and finds a valid, agreeing credential, so it returns
+ * `exists-ours` without minting at all. The lock auto-releases on commit/rollback, so it
+ * cannot leak — the same mechanism the registry uses inside `mintPullKey`, and that
+ * `traceMaintenance` uses for cross-replica dedup.
+ *
+ * The transaction is held across the K8s and registry calls inside `work`. That is
+ * deliberate and bounded: the mint carries a timeout and the K8s calls are few.
+ */
+async function withPullSecretLock<T>(orgName: string, work: () => Promise<T>): Promise<T> {
+ return withTransaction(async db => {
+ await db.query('SELECT pg_advisory_xact_lock(hashtext($1))', [
+ `registry-pull-secret:${orgName}`,
+ ])
+ return work()
+ })
+}
+
async function ensureInner(gateway: K8sGateway, targets: string[]): Promise<EnsurePass> {
const out = new Map<string, EnsurePullSecretResult>()
const unusable = new Map<string, string>()
@@ -430,6 +458,26 @@ async function ensureInner(gateway: K8sGateway, targets: string[]): Promise<Ensu
)
}
+ // Everything from here — read, classify, mint, write — must be serialized across
+ // replicas, not just within this process (see withPullSecretLock).
+ return withPullSecretLock(orgName, () =>
+ ensureLocked(gateway, targets, host, orgName as string, out, unusable, blocked)
+ )
+}
+
+/**
+ * The read -> classify -> mint -> write pass. Runs while holding the cross-process lock,
+ * so it may assume no other replica is minting for this org concurrently.
+ */
+async function ensureLocked(
+ gateway: K8sGateway,
+ targets: string[],
+ host: string,
+ orgName: string,
+ out: Map<string, EnsurePullSecretResult>,
+ unusable: Map<string, string>,
+ blocked: Map<string, string>
+): Promise<EnsurePass> {
// ── Read + classify every target BEFORE minting anything ──────────────────
const states = new Map<string, TargetState>()
for (const ns of targets) {
diff --git a/control-api/test/registryPullSecretReconcileCron.test.ts b/control-api/test/registryPullSecretReconcileCron.test.ts
new file mode 100644
index 000000000..39c49273e
--- /dev/null
+++ b/control-api/test/registryPullSecretReconcileCron.test.ts
@@ -0,0 +1,102 @@
+/**
+ * The reconcile loop that makes the platform pull credential a standing invariant.
+ *
+ * The property under test is the one that differs from the install path: a precondition
+ * failure here must be LOGGED AND RETRIED, never thrown. An install throws because a user
+ * asked for something we cannot deliver; this loop runs unprompted on every cluster,
+ * including ones that have not finished the registry connect flow, and must not turn that
+ * normal state into recurring errors or a crash loop.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { K8sGateway } from '../src/k8s.js'
+import {
+ reconcileRegistryPullSecret,
+ startRegistryPullSecretReconcileCron,
+ stopRegistryPullSecretReconcileCron,
+} from '../src/services/registryPullSecretReconcileCron.js'
+
+const ensureRegistryPullSecrets = vi.hoisted(() => vi.fn())
+vi.mock('../src/services/registryPullSecretService.js', () => ({
+ ensureRegistryPullSecrets,
+ platformWorkloadNamespaces: () => ['mcp-server', 'sandbox-recipes', 'sandbox-ui'],
+}))
+
+const gateway = {} as K8sGateway
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+afterEach(() => {
+ stopRegistryPullSecretReconcileCron()
+ vi.useRealTimers()
+})
+
+describe('reconcileRegistryPullSecret', () => {
+ it('provisions across every platform namespace', async () => {
+ ensureRegistryPullSecrets.mockResolvedValue(
+ new Map([
+ ['mcp-server', 'created'],
+ ['sandbox-recipes', 'created'],
+ ['sandbox-ui', 'created'],
+ ])
+ )
+ await expect(reconcileRegistryPullSecret(gateway)).resolves.toBe(true)
+ expect(ensureRegistryPullSecrets).toHaveBeenCalledWith(gateway, [
+ 'mcp-server',
+ 'sandbox-recipes',
+ 'sandbox-ui',
+ ])
+ })
+
+ it('does NOT throw when the cluster is not connected yet — it retries next tick', async () => {
+ // The exact state a freshly-deployed, unconnected cluster is in. Throwing here would
+ // crash-loop the process or spam an error every interval.
+ const err = Object.assign(new Error('registry connection is not active'), {
+ reason: 'registry_not_connected',
+ })
+ ensureRegistryPullSecrets.mockRejectedValue(err)
+ await expect(reconcileRegistryPullSecret(gateway)).resolves.toBe(false)
+ })
+
+ it('does NOT throw when no org is bound yet', async () => {
+ ensureRegistryPullSecrets.mockRejectedValue(
+ Object.assign(new Error('no org'), { reason: 'org_unresolved' })
+ )
+ await expect(reconcileRegistryPullSecret(gateway)).resolves.toBe(false)
+ })
+
+ it('swallows an unexpected error rather than escaping the timer callback', async () => {
+ ensureRegistryPullSecrets.mockRejectedValue(new Error('boom'))
+ await expect(reconcileRegistryPullSecret(gateway)).resolves.toBe(false)
+ })
+
+ it('reports success without provisioning when everything is already in place', async () => {
+ ensureRegistryPullSecrets.mockResolvedValue(new Map([['mcp-server', 'exists-ours']]))
+ await expect(reconcileRegistryPullSecret(gateway)).resolves.toBe(true)
+ })
+})
+
+describe('startRegistryPullSecretReconcileCron', () => {
+ it('runs on the interval and is idempotent to start', async () => {
+ vi.useFakeTimers()
+ ensureRegistryPullSecrets.mockResolvedValue(new Map())
+
+ startRegistryPullSecretReconcileCron(gateway, 1000)
+ // A second start must not install a second timer (which would double the mint rate).
+ startRegistryPullSecretReconcileCron(gateway, 1000)
+
+ await vi.advanceTimersByTimeAsync(3000)
+ expect(ensureRegistryPullSecrets).toHaveBeenCalledTimes(3)
+ })
+
+ it('stops cleanly', async () => {
+ vi.useFakeTimers()
+ ensureRegistryPullSecrets.mockResolvedValue(new Map())
+ startRegistryPullSecretReconcileCron(gateway, 1000)
+ await vi.advanceTimersByTimeAsync(1000)
+ stopRegistryPullSecretReconcileCron()
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(ensureRegistryPullSecrets).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/control-api/test/registryPullSecretService.test.ts b/control-api/test/registryPullSecretService.test.ts
index f8eb5d516..38b656811 100644
--- a/control-api/test/registryPullSecretService.test.ts
+++ b/control-api/test/registryPullSecretService.test.ts
@@ -12,6 +12,19 @@ import {
} from '../src/services/registryPullSecretService.js'
import { MockGateway } from './mockGateway.js'
+// Records every SQL the service issues, so the cross-process advisory lock is asserted
+// rather than mocked into invisibility. Passthrough otherwise, to stay Postgres-free.
+const dbCalls = vi.hoisted(() => ({ queries: [] as Array<{ text: string; values?: unknown[] }> }))
+vi.mock('../src/db.js', () => ({
+ withTransaction: (work: (db: unknown) => unknown) =>
+ work({
+ query: async (text: string, values?: unknown[]) => {
+ dbCalls.queries.push({ text, values })
+ return { rows: [], rowCount: 0 }
+ },
+ }),
+}))
+
vi.mock('../src/services/registryConnectionDb.js', () => ({
isRegistryAuthActive: vi.fn(),
}))
@@ -100,6 +113,7 @@ let savedUrl: string
beforeEach(() => {
vi.clearAllMocks()
+ dbCalls.queries.length = 0
savedMode = config.registryConnectionMode
savedUrl = config.registryUrl
config.registryConnectionMode = 'self-hosted'
@@ -696,3 +710,26 @@ describe('ensureRegistryPullSecrets — fan-out across platform namespaces', ()
expect(new Set(seen.map(s => s.fingerprint))).toEqual(new Set([fingerprintOf('efrk_test_key')]))
})
})
+
+describe('ensureRegistryPullSecrets — cross-process serialization', () => {
+ it('takes a per-org advisory lock BEFORE minting', async () => {
+ const { gateway } = gw()
+ await ensureRegistryPullSecrets(gateway, ALL)
+
+ // Two replicas coexist on every RollingUpdate; without this lock their mints
+ // interleave and some namespaces end up holding a revoked key.
+ const lock = dbCalls.queries.find(q => q.text.includes('pg_advisory_xact_lock'))
+ expect(lock).toBeDefined()
+ expect(lock?.values?.[0]).toBe('registry-pull-secret:acme')
+ // An xact lock auto-releases on commit, so there is no explicit unlock to leak.
+ expect(dbCalls.queries.some(q => q.text.includes('pg_advisory_unlock'))).toBe(false)
+ })
+
+ it('does not reach the lock when the pass is a legitimate no-op', async () => {
+ config.registryConnectionMode = 'managed'
+ const { gateway } = gw()
+ await ensureRegistryPullSecrets(gateway, ALL)
+ // Managed clusters must not touch Postgres (or anything else) on this path.
+ expect(dbCalls.queries).toHaveLength(0)
+ })
+})
diff --git a/control-api/test/routes.adminRecipes.pullSecret.test.ts b/control-api/test/routes.adminRecipes.pullSecret.test.ts
index adab100c1..363797d2f 100644
--- a/control-api/test/routes.adminRecipes.pullSecret.test.ts
+++ b/control-api/test/routes.adminRecipes.pullSecret.test.ts
@@ -25,6 +25,14 @@ import {
import { isRegistryAuthActive } from '../src/services/registryConnectionDb.js'
import { MockGateway } from './mockGateway.js'
+vi.mock('../src/db.js', () => ({
+ // The provisioner takes a cross-process advisory lock; without this the suite reaches a
+ // real Postgres and every test times out. The lock itself is asserted in
+ // registryPullSecretService.test.ts.
+ withTransaction: (work: (db: unknown) => unknown) =>
+ work({ query: async () => ({ rows: [], rowCount: 0 }) }),
+}))
+
vi.mock('node:dns/promises', () => ({
lookup: vi.fn(async () => [{ address: '93.184.216.34' }]),
}))
diff --git a/control-api/test/routes.registryInstall.pullSecret.test.ts b/control-api/test/routes.registryInstall.pullSecret.test.ts
index 43e38f6ca..538287b73 100644
--- a/control-api/test/routes.registryInstall.pullSecret.test.ts
+++ b/control-api/test/routes.registryInstall.pullSecret.test.ts
@@ -28,6 +28,13 @@ import {
import { isRegistryAuthActive } from '../src/services/registryConnectionDb.js'
import { MockGateway } from './mockGateway.js'
+vi.mock('../src/db.js', () => ({
+ // The cross-process advisory lock is exercised for real in the integration suite; here
+ // it is a passthrough so the unit tests stay Postgres-free.
+ withTransaction: (work: (db: unknown) => unknown) =>
+ work({ query: async () => ({ rows: [], rowCount: 0 }) }),
+}))
+
vi.mock('node:dns/promises', () => ({
lookup: vi.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),
}))
@@ -327,3 +334,98 @@ describe('POST /admin/registry/install-recipe — pull-secret provisioning (self
expect(persisted.map(r => r.metadata.name)).toEqual([])
})
})
+
+describe('POST /admin/registry/upgrade-recipe — pull-secret provisioning (self-hosted)', () => {
+ const PLATFORM_NAMESPACES = ['mcp-server', 'sandbox-recipes', 'sandbox-ui']
+
+ /** An upgrade target whose NEW spec runs `image`. */
+ function upgradeEntry(image: string) {
+ return {
+ id: 'r2',
+ name: 'workflow-template',
+ version: '2.0.0',
+ entry_type: 'recipe',
+ description: 'Workflow template',
+ author: 'acme',
+ recipe_meta: {
+ recipeYaml: JSON.stringify({
+ spec: {
+ description: 'Workflow template',
+ steps: [{ id: 's1', instruction: 'Run step' }],
+ workloads: [{ id: 'w1', type: 'deployment', image }],
+ },
+ }),
+ },
+ }
+ }
+
+ function makeUpgradeApp() {
+ const gw = new MockGateway(NS)
+ gw.createResource(
+ 'workflowrecipes',
+ {
+ metadata: { name: 'existing-recipe' },
+ spec: { steps: [{ id: 's1', instruction: 'Run step' }] },
+ },
+ 'sandbox-recipes'
+ )
+ return { app: makeApp(gw), gw }
+ }
+
+ function upgradeBody() {
+ return {
+ recipeName: 'existing-recipe',
+ registryEntryName: 'workflow-template',
+ registryEntryVersion: '2.0.0',
+ }
+ }
+
+ it('provisions when an upgrade moves a recipe from a PUBLIC to a PRIVATE image', async () => {
+ // The regression this guards: the pre-existing CRD is public, so nothing was ever
+ // provisioned; the upgrade introduces a platform image. Without a hook here the new
+ // CRD persists, returns 200, and then fails at pull time.
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(
+ upgradeEntry(`${REGISTRY_HOST}/acme/plugin:2.0`) as never
+ )
+ const { app, gw } = makeUpgradeApp()
+
+ await request(app).post('/admin/registry/upgrade-recipe').send(upgradeBody()).expect(200)
+
+ expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)
+ for (const ns of PLATFORM_NAMESPACES) {
+ const secret = (await gw.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns)) as {
+ type?: string
+ }
+ expect(secret.type).toBe('kubernetes.io/dockerconfigjson')
+ }
+ })
+
+ it('does not provision when the upgraded recipe stays on a public image', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(
+ upgradeEntry('ghcr.io/acme/plugin:2.0') as never
+ )
+ const { app, gw } = makeUpgradeApp()
+
+ await request(app).post('/admin/registry/upgrade-recipe').send(upgradeBody()).expect(200)
+
+ expect(mintOrgPullCredential).not.toHaveBeenCalled()
+ await expect(
+ gw.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, 'sandbox-recipes')
+ ).rejects.toBeTruthy()
+ })
+
+ it('fails the upgrade loudly when provisioning fails', async () => {
+ vi.mocked(getEntryVersion).mockResolvedValueOnce(
+ upgradeEntry(`${REGISTRY_HOST}/acme/plugin:2.0`) as never
+ )
+ vi.mocked(mintOrgPullCredential).mockRejectedValueOnce(new Error('registry unavailable'))
+ const { app, gw } = makeUpgradeApp()
+ const updateSpy = vi.spyOn(gw, 'updateResource')
+
+ const res = await request(app).post('/admin/registry/upgrade-recipe').send(upgradeBody())
+ expect(res.status).toBeGreaterThanOrEqual(500)
+ expect(res.body.error).toBe('registry_pull_secret_provision_failed')
+ // The CRD must not be updated to reference a credential that does not exist.
+ expect(updateSpy).not.toHaveBeenCalled()
+ })
+})
diff --git a/docs/architecture/registry-pull-secret-recipe-workloads.md b/docs/architecture/registry-pull-secret-recipe-workloads.md
index e0e0f1608..24be1250f 100644
--- a/docs/architecture/registry-pull-secret-recipe-workloads.md
+++ b/docs/architecture/registry-pull-secret-recipe-workloads.md
@@ -1,10 +1,11 @@
# Platform image-pull credentials for recipe workloads
-**Status:** Implemented in PR #243 — **not approved; five blocking review findings open**
-(§13), four of them P1. The most consequential (§13.1) reverses this document's
-install-time trigger decision: provisioning must become a standing invariant, because a
+**Status:** Implemented in PR #243. Five blocking review findings were raised against it
+(§13); **the four P1s are fixed** — including §13.1, which reversed this document's
+install-time trigger decision (provisioning is now a standing invariant, because a
`WorkflowRecipe` can be created without control-api while WRC injects the pull-secret
-reference regardless. Two earlier carve-outs also remain recorded in place: WRC injection
+reference regardless). **§13.5 — end-to-end runtime evidence — remains open and is the
+last acceptance gate.** Two earlier carve-outs also remain recorded in place: WRC injection
is deliberately **not** mode-gated, so the operator contract changes on managed clusters
too (§9), and the `POST /admin/recipes/secrets` `Opaque` fix (§6.5) did **not** ship.
**Date:** 2026-08-04
@@ -598,7 +599,7 @@ accepted; none is dismissed. **§13.1 is the important one** — it invalidates
recorded in §12 and changes the shape of the feature from an install-time side effect into
a standing cluster invariant.
-### 13.1 [P1] Provisioning must be a standing invariant, not an install-time hook
+### 13.1 [P1] ✅ SHIPPED — Provisioning is a standing invariant, not an install-time hook
**The mismatch.** As shipped, the two halves of this feature are triggered by different
things:
@@ -664,7 +665,7 @@ a credential that does not exist, but the pod still cannot pull, so it trades on
failure for another. The presence-*surfacing* idea (§12-3 / #243 §7.7 — emit a condition
instead of a bare `ImagePullBackOff`) is complementary and still worth doing.
-### 13.2 [P1] Minting can revoke a valid foreign copy
+### 13.2 [P1] ✅ SHIPPED — Minting can revoke a valid foreign copy
The "never touch a foreign Secret" rule protects the **Secret object**; it does not protect
the **credential inside it**. `mintPullKey` revokes `WHERE org_id = $1 AND kind = 'pull'`
@@ -685,7 +686,7 @@ actionable error (`foreign_secret_present`: remove it, or provision every namesp
same way) rather than silently invalidating it. Reading the credential out of a foreign
Secret and reusing it is explicitly rejected — that is someone else's credential.
-### 13.3 [P1] Serialization is per-process only
+### 13.3 [P1] ✅ SHIPPED — Serialization is per-process only
`replicas: 1` in `deploy/base/control-plane/control-api.yaml:15` with no explicit
`strategy` takes the default `RollingUpdate`, so two pods coexist on every deploy. The
@@ -702,7 +703,7 @@ control-api already has Postgres, so `pg_advisory_lock` is the natural mechanism
no dependency — mirroring what the registry itself does inside `mintPullKey`. The
in-process map stays as a cheap first-level dedupe.
-### 13.4 [P1] `upgrade-recipe` has no provisioning hook
+### 13.4 [P1] ✅ SHIPPED — `upgrade-recipe` has no provisioning hook
`POST /admin/registry/upgrade-recipe` (`control-api/src/routes/admin/registry.ts:2001`)
never calls `ensureRegistryPullSecret(s)`. The three existing hooks are at `:1206`
@@ -716,7 +717,7 @@ fails at pull time, with a `200` on the API call.
install-recipe placement. Fix it explicitly even once §13.1 lands: the reconcile is a
safety net, not a substitute for failing the request that introduced the problem.
-### 13.5 [Acceptance] No end-to-end runtime evidence
+### 13.5 [Acceptance] ⏳ OPEN — No end-to-end runtime evidence
Coverage is unit- and route-level against `MockGateway`. Nothing exercises
`Secret → WRC → McpServer/HCC → Pod Ready → private image pull`.
@@ -733,7 +734,31 @@ MCP-server plugin, (b) a recipe plugin with a non-transport workload, (c) a reci
by `kubectl apply` (the §13.1 path), each asserting `Pod Ready` rather than just Secret
contents.
-### 13.6 Sequencing
+### 13.7 As-built
+
+| # | Status | Where |
+| --- | --- | --- |
+| 13.1 | ✅ | `services/registryPullSecretReconcileCron.ts` (boot pass + timer, wired in `main.ts`); interval via `REGISTRY_PULL_SECRET_RECONCILE_INTERVAL_MS` (default 10 min) |
+| 13.2 | ✅ | `registryPullSecretService.ts` — `foreign_secret_would_be_revoked`, all-or-nothing refusal |
+| 13.3 | ✅ | `withPullSecretLock` — `pg_advisory_xact_lock(hashtext('registry-pull-secret:<org>'))` around read→mint→write |
+| 13.4 | ✅ | `registry.ts` — hook on `upgrade-recipe`, keyed on the INCOMING spec |
+| 13.5 | ⏳ | still open — the only remaining acceptance gate |
+
+Notes worth carrying forward:
+
+- **The reconcile is why 13.3 was not optional.** A periodic loop without the lock does not
+ race occasionally, it fights continuously. The lock blocks rather than fails, so the
+ second replica waits, re-reads, finds an agreeing credential, and returns `exists-ours`
+ without minting — which is the convergence property the whole design wants.
+- **Failure semantics are split as specified**: `ensureRegistryPullSecrets` throws, the
+ install path surfaces that as a 4xx/5xx, and the cron swallows it into a warning and
+ retries. Both directions are mutation-tested (letting the error escape the cron fails 3
+ tests; removing the install-path throw fails the route tests).
+- **The unit suites now mock `../src/db.js`.** The advisory lock made them reach Postgres
+ and hang. The lock itself is still asserted — the mock records the SQL, so a test checks
+ the lock is taken, is keyed on the org, and is taken *before* the mint.
+
+### 13.6 Sequencing (as planned)
```
§13.3 lock ──┬──> §13.1 periodic reconcile ──> §13.5 e2e