Skip to content

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

TypeScript

fix(control-api): provision on generic recipe writes, reserve the platform name

Jose Ramirezdc272b952665
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 6059fe77a..2f9aeda00 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.402",
+ "version": "0.1.403",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.402",
+ "version": "0.1.403",
"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 da67d9803..debd4fdbd 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.402",
+ "version": "0.1.403",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/http/k8sError.ts b/control-api/src/http/k8sError.ts
new file mode 100644
index 000000000..b8a642157
--- /dev/null
+++ b/control-api/src/http/k8sError.ts
@@ -0,0 +1,34 @@
+/**
+ * Extract HTTP status + message from K8s client errors.
+ *
+ * The @kubernetes/client-node errors carry the apiserver's explanation in `body` (a JSON
+ * string on most paths, an object on some), not in `message` — so a bare `err.message`
+ * turns "Secret is immutable" into "HTTP request failed". Lives here rather than inside a
+ * route file because more than one route module now maps these onto responses.
+ */
+export function extractK8sError(err: unknown): { status: number; message: string } | null {
+ if (err && typeof err === 'object') {
+ const e = err as {
+ code?: number
+ body?: string | { message?: string }
+ httpStatus?: number
+ statusCode?: number
+ message?: string
+ }
+ const status = e.code ?? e.statusCode ?? e.httpStatus
+ if (typeof status === 'number' && status >= 400 && status < 600) {
+ let msg = ''
+ if (typeof e.body === 'string') {
+ try {
+ msg = (JSON.parse(e.body) as { message?: string }).message ?? e.body
+ } catch {
+ msg = e.body
+ }
+ } else if (e.body && typeof e.body === 'object') {
+ msg = e.body.message ?? ''
+ }
+ return { status, message: msg || e.message || `K8s error ${status}` }
+ }
+ }
+ return null
+}
diff --git a/control-api/src/routes/admin/recipes.ts b/control-api/src/routes/admin/recipes.ts
index 6700550fe..2167d5807 100644
--- a/control-api/src/routes/admin/recipes.ts
+++ b/control-api/src/routes/admin/recipes.ts
@@ -1,5 +1,6 @@
import { Router } from 'express'
import { isWorkflowRecipeDefaultAllowedCapability } from '@clerum/workflow-recipe-capability-policy'
+import { EVENFIRE_REGISTRY_PULL_SECRET_NAME } from '@clerum/workflow-runtime-core'
import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import { CONTENT_TYPES } from '../../http/contentTypes.js'
@@ -14,6 +15,10 @@ import {
type SecretOwnership,
parseSecretOwnership,
} from '../../secretOwnership.js'
+import {
+ ensureRegistryPullSecrets,
+ platformWorkloadNamespaces,
+} from '../../services/registryPullSecretService.js'
import { K8sNotFoundError } from '../../services/resourceService.js'
import { invalidSecretDataKeyReason } from '../../services/secretKeys.js'
import {
@@ -22,6 +27,10 @@ import {
} from '../../services/workflowRecipeLimits.js'
import { buildWrcWorkflowArtifactsUrl } from '../../services/workflows/wrcClient.js'
import { signWrcDelegationToken } from '../../utils/auth/delegationToken.js'
+import {
+ pullSecretErrorResponse,
+ recipeReferencesPlatformImage,
+} from './registryPullSecretProvisioning.js'
// Timeout for the proxied artifact fetch — short enough that a hung WRC
// cannot tie up a control-api worker indefinitely, long enough that a
@@ -228,8 +237,19 @@ function sensitiveInputRefsInEnvValue(value: unknown): string[] {
return [...refs]
}
+/**
+ * Names a recipe may not reference or write.
+ *
+ * `wf-` covers the coordinator/runtime Secrets the platform materializes per recipe.
+ * `evenfire-registry-pull` is the org's registry pull credential: control-api writes it
+ * into the platform workload namespaces and WRC injects the reference itself, AFTER the
+ * #637 ownership filter — so a declared copy is stripped and re-injected anyway, and the
+ * same name in an `envSecret` would read that credential into a container's environment.
+ * Reject it here rather than appear to honor a declaration we ignore
+ * (docs/architecture/registry-pull-secret-recipe-workloads.md §6.1).
+ */
function isPlatformManagedWorkflowSecretName(name: string): boolean {
- return name.startsWith('wf-')
+ return name.startsWith('wf-') || name === EVENFIRE_REGISTRY_PULL_SECRET_NAME
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
@@ -1735,6 +1755,23 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {
return
}
const pendingCredentials = workflowSecretResult.pendingCredentials
+ // Provision the platform pull credential before the CRD that will need it.
+ //
+ // A recipe authored here is indistinguishable, at reconcile time, from one installed
+ // off the registry: WRC injects the pull-secret reference into any workload whose
+ // image is ours, so an unprovisioned Secret means ImagePullBackOff behind a 201.
+ // Recipe workloads split across all three platform namespaces by kind, hence the
+ // full set — one pass, one mint (see registryPullSecretService). Idempotent and
+ // mint-free once every namespace already holds a current credential.
+ if (recipeReferencesPlatformImage(body.spec ?? {})) {
+ try {
+ await ensureRegistryPullSecrets(gateway, platformWorkloadNamespaces())
+ } catch (err) {
+ const mapped = pullSecretErrorResponse(err)
+ res.status(mapped.status).json(mapped.body)
+ return
+ }
+ }
// The CRD always goes to RECIPE_CRD_NAMESPACE. Any namespace present in
// the author YAML is deliberately discarded here because infra owns
// placement; WorkflowRecipe YAML is not a namespace contract.
@@ -1812,6 +1849,19 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {
return
}
const pendingCredentials = workflowSecretResult.pendingCredentials
+ // Same guard as create: an update is how a recipe FIRST acquires a platform image
+ // (edit the workload's image, keep the name), and the stored CRD is what WRC
+ // reconciles. Provision before the write, never after — a failure must leave the
+ // persisted recipe as it was.
+ if (recipeReferencesPlatformImage(body.spec ?? {})) {
+ try {
+ await ensureRegistryPullSecrets(gateway, platformWorkloadNamespaces())
+ } catch (err) {
+ const mapped = pullSecretErrorResponse(err)
+ res.status(mapped.status).json(mapped.body)
+ return
+ }
+ }
// Discover the canonical recipe resource and update it in sandbox-recipes.
try {
const { ns, resource } = await findRecipeNamespace(req.params.name)
diff --git a/control-api/src/routes/admin/registry.ts b/control-api/src/routes/admin/registry.ts
index a5af92e6c..1d8587d87 100644
--- a/control-api/src/routes/admin/registry.ts
+++ b/control-api/src/routes/admin/registry.ts
@@ -5,6 +5,7 @@ import { isIP } from 'node:net'
import { parse as parseYaml } from 'yaml'
import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
+import { extractK8sError } from '../../http/k8sError.js'
import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'
import { K8sGateway } from '../../k8s.js'
import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
@@ -35,7 +36,6 @@ import {
} from '../../services/registryClient.js'
import { isRegistryAuthActive } from '../../services/registryConnectionDb.js'
import {
- PullSecretProvisionError,
ensureRegistryPullSecret,
ensureRegistryPullSecrets,
platformWorkloadNamespaces,
@@ -47,10 +47,13 @@ import {
import { SecretUpsertRequest } from '../../types.js'
import {
EVENFIRE_REGISTRY_PULL_SECRET_NAME,
- isPlatformRegistryImage,
shouldAttachEvenfirePullSecret,
} from './registryImagePullSecret.js'
import { checkEvenfireImageRefMatchesEntry } from './registryImageRefIdentity.js'
+import {
+ pullSecretErrorResponse,
+ recipeReferencesPlatformImage,
+} from './registryPullSecretProvisioning.js'
/** Validate a Kubernetes resource name (RFC 1123 DNS subdomain). */
function isValidK8sName(name: string): boolean {
@@ -307,73 +310,6 @@ async function loadRegistryCredentialSchema(entry: {
}
}
-/**
- * Map an image-pull-secret provisioning failure onto an actionable HTTP response.
- *
- * The three classes are meaningfully different to an operator, and collapsing them all to
- * a bare 500 (as a generic K8s-error mapping does — `extractK8sError` cannot read
- * `RegistryProxyError.status`) makes a deploy-ordering or connect-flow problem look like a
- * control-api bug:
- * - PullSecretProvisionError → a precondition the operator can fix (wrong namespace,
- * registry not connected, org not yet bound); carries its own status + reason code.
- * - RegistryProxyError → the registry rejected us (e.g. 403 because the
- * pull-credential endpoint has not been upgraded, or this client lacks
- * `registry:manage-keys`); surfaced as 502 with the upstream status.
- * - anything else → 500.
- */
-function pullSecretErrorResponse(err: unknown): {
- status: number
- body: Record<string, unknown>
-} {
- if (err instanceof PullSecretProvisionError) {
- return {
- status: err.status,
- body: {
- error: 'registry_pull_secret_provision_failed',
- reason: err.reason,
- detail: err.message,
- },
- }
- }
- if (err instanceof RegistryProxyError) {
- return {
- status: 502,
- body: {
- error: 'registry_pull_secret_provision_failed',
- reason: 'registry_rejected',
- upstreamStatus: err.status,
- detail: `the registry rejected the image-pull credential request (${err.status}); confirm the registry supports tenant pull-credential minting and that this deployment holds registry:manage-keys`,
- },
- }
- }
- const k8sErr = extractK8sError(err)
- return {
- status: 500,
- body: {
- error: 'registry_pull_secret_provision_failed',
- reason: 'unexpected_error',
- detail: k8sErr?.message || (err instanceof Error ? err.message : 'unknown error'),
- },
- }
-}
-
-/**
- * True when any workload in a recipe spec runs an image hosted on our own registry, and
- * therefore needs the platform pull credential.
- *
- * Uses the same shared predicate WRC applies at reconcile time
- * (`isPlatformRegistryImage`), so control-api cannot decide to provision for a workload
- * WRC will not attach the secret to, or vice versa — that mismatch would surface as an
- * ImagePullBackOff with no failing request to attribute it to.
- */
-function recipeReferencesPlatformImage(recipeSpec: Record<string, unknown>): boolean {
- const workloads = recipeSpec.workloads
- if (!Array.isArray(workloads)) return false
- return workloads.some(w =>
- isPlatformRegistryImage((w as { image?: unknown } | null)?.image, config.registryUrl)
- )
-}
-
/** Audit log for security-sensitive operations (finding #10). */
function auditLog(action: string, details: Record<string, unknown>): void {
const safe: Record<string, unknown> = { timestamp: new Date().toISOString(), action, ...details }
@@ -620,34 +556,6 @@ function deriveRegistryEgressBindings(options: {
)
}
-/** Extract HTTP status + message from K8s client errors. */
-function extractK8sError(err: unknown): { status: number; message: string } | null {
- if (err && typeof err === 'object') {
- const e = err as {
- code?: number
- body?: string | { message?: string }
- httpStatus?: number
- statusCode?: number
- message?: string
- }
- const status = e.code ?? e.statusCode ?? e.httpStatus
- if (typeof status === 'number' && status >= 400 && status < 600) {
- let msg = ''
- if (typeof e.body === 'string') {
- try {
- msg = (JSON.parse(e.body) as { message?: string }).message ?? e.body
- } catch {
- msg = e.body
- }
- } else if (e.body && typeof e.body === 'object') {
- msg = e.body.message ?? ''
- }
- return { status, message: msg || e.message || `K8s error ${status}` }
- }
- }
- return null
-}
-
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
diff --git a/control-api/src/routes/admin/registryPullSecretProvisioning.ts b/control-api/src/routes/admin/registryPullSecretProvisioning.ts
new file mode 100644
index 000000000..fb1566e83
--- /dev/null
+++ b/control-api/src/routes/admin/registryPullSecretProvisioning.ts
@@ -0,0 +1,82 @@
+/**
+ * Route-layer helpers for provisioning the platform image-pull Secret: "does this recipe
+ * need the credential?" and "how does a provisioning failure become a response?".
+ *
+ * Shared, not duplicated, because two route modules write WorkflowRecipe CRDs whose
+ * workloads WRC will inject the pull-secret reference into — the registry install path
+ * (`registry.ts`) and the generic recipe CRUD path (`recipes.ts`). Both must decide the
+ * same way and fail the same way; a second copy of either rule would let one route persist
+ * a recipe the other would have refused.
+ */
+import { config } from '../../config.js'
+import { extractK8sError } from '../../http/k8sError.js'
+import { RegistryProxyError } from '../../services/registryClient.js'
+import { PullSecretProvisionError } from '../../services/registryPullSecretService.js'
+import { isPlatformRegistryImage } from './registryImagePullSecret.js'
+
+/**
+ * True when any workload in a recipe spec runs an image hosted on our own registry, and
+ * therefore needs the platform pull credential.
+ *
+ * Uses the same shared predicate WRC applies at reconcile time
+ * (`isPlatformRegistryImage`), so control-api cannot decide to provision for a workload
+ * WRC will not attach the secret to, or vice versa — that mismatch would surface as an
+ * ImagePullBackOff with no failing request to attribute it to.
+ */
+export function recipeReferencesPlatformImage(recipeSpec: Record<string, unknown>): boolean {
+ const workloads = recipeSpec.workloads
+ if (!Array.isArray(workloads)) return false
+ return workloads.some(w =>
+ isPlatformRegistryImage((w as { image?: unknown } | null)?.image, config.registryUrl)
+ )
+}
+
+/**
+ * Map an image-pull-secret provisioning failure onto an actionable HTTP response.
+ *
+ * The three classes are meaningfully different to an operator, and collapsing them all to
+ * a bare 500 (as a generic K8s-error mapping does — `extractK8sError` cannot read
+ * `RegistryProxyError.status`) makes a deploy-ordering or connect-flow problem look like a
+ * control-api bug:
+ * - PullSecretProvisionError → a precondition the operator can fix (wrong namespace,
+ * registry not connected, org not yet bound); carries its own status + reason code.
+ * - RegistryProxyError → the registry rejected us (e.g. 403 because the
+ * pull-credential endpoint has not been upgraded, or this client lacks
+ * `registry:manage-keys`); surfaced as 502 with the upstream status.
+ * - anything else → 500.
+ */
+export function pullSecretErrorResponse(err: unknown): {
+ status: number
+ body: Record<string, unknown>
+} {
+ if (err instanceof PullSecretProvisionError) {
+ return {
+ status: err.status,
+ body: {
+ error: 'registry_pull_secret_provision_failed',
+ reason: err.reason,
+ detail: err.message,
+ },
+ }
+ }
+ if (err instanceof RegistryProxyError) {
+ return {
+ status: 502,
+ body: {
+ error: 'registry_pull_secret_provision_failed',
+ reason: 'registry_rejected',
+ upstreamStatus: err.status,
+ detail: `the registry rejected the image-pull credential request (${err.status}); confirm the registry supports tenant pull-credential minting and that this deployment holds registry:manage-keys`,
+ },
+ }
+ }
+ const k8sErr = extractK8sError(err)
+ return {
+ status: 500,
+ body: {
+ error: 'registry_pull_secret_provision_failed',
+ reason: 'unexpected_error',
+ detail: k8sErr?.message || (err instanceof Error ? err.message : 'unknown error'),
+ },
+ }
+}
diff --git a/control-api/test/routes.adminRecipes.pullSecret.test.ts b/control-api/test/routes.adminRecipes.pullSecret.test.ts
new file mode 100644
index 000000000..52783537b
--- /dev/null
+++ b/control-api/test/routes.adminRecipes.pullSecret.test.ts
@@ -0,0 +1,202 @@
+/**
+ * Route-level coverage for image-pull-secret provisioning on the GENERIC recipe routes.
+ *
+ * `POST /admin/recipes` and `PUT /admin/recipes/:name` persist the same WorkflowRecipe CRD
+ * the registry install path does, and WRC injects the platform pull-secret reference for
+ * any workload whose image is ours — it does not care which route wrote the recipe. So a
+ * recipe authored or edited here must provision too, or the pod references a Secret that
+ * was never minted: ImagePullBackOff behind a green 201.
+ *
+ * The main `routes.adminRecipes` suite runs in the default `managed` connection mode,
+ * where provisioning short-circuits to `'skipped'`; these force `self-hosted`, the only
+ * mode where the hook does anything.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { config } from '../src/config.js'
+import { createAdminRecipesRouter } from '../src/routes/admin/recipes.js'
+import { EVENFIRE_REGISTRY_PULL_SECRET_NAME } from '../src/routes/admin/registryImagePullSecret.js'
+import { mintOrgPullCredential, resolvePublishScope } from '../src/services/registryClient.js'
+import { isRegistryAuthActive } from '../src/services/registryConnectionDb.js'
+import { MockGateway } from './mockGateway.js'
+
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn(async () => [{ address: '93.184.216.34' }]),
+}))
+vi.mock('../src/services/registryClient.js', async importOriginal => ({
+ ...(await importOriginal<typeof import('../src/services/registryClient.js')>()),
+ resolvePublishScope: vi.fn(),
+ mintOrgPullCredential: vi.fn(),
+}))
+vi.mock('../src/services/registryConnectionDb.js', async importOriginal => ({
+ ...(await importOriginal<typeof import('../src/services/registryConnectionDb.js')>()),
+ isRegistryAuthActive: vi.fn(),
+}))
+
+const REGISTRY_HOST = 'registry.evenfire.ai'
+const MCP_NS = 'mcp-server'
+const SANDBOX_NS = 'sandbox-recipes'
+const PLATFORM_NAMESPACES = [MCP_NS, SANDBOX_NS, 'sandbox-ui']
+
+/** A workload image on the configured platform registry — needs the pull credential. */
+function platformRecipe(name: string) {
+ return {
+ metadata: { name },
+ spec: {
+ workloads: [{ id: 'svc', type: 'deployment', image: `${REGISTRY_HOST}/acme/plugin:1.0` }],
+ },
+ }
+}
+
+/** Same shape, third-party image — the platform credential is none of its business. */
+function foreignRecipe(name: string) {
+ return {
+ metadata: { name },
+ spec: {
+ workloads: [{ id: 'svc', type: 'deployment', image: 'ghcr.io/acme/plugin:1.0' }],
+ },
+ }
+}
+
+function makeApp(gateway: MockGateway) {
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminRecipesRouter(gateway as never))
+ return app
+}
+
+let savedMode: typeof config.registryConnectionMode
+let savedUrl: string
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ savedMode = config.registryConnectionMode
+ savedUrl = config.registryUrl
+ config.registryConnectionMode = 'self-hosted'
+ config.registryUrl = `https://${REGISTRY_HOST}`
+ vi.mocked(isRegistryAuthActive).mockResolvedValue(true)
+ vi.mocked(resolvePublishScope).mockResolvedValue({
+ curator: false,
+ orgName: 'acme',
+ scope: '@acme',
+ })
+ vi.mocked(mintOrgPullCredential).mockResolvedValue({ key: 'efrk_recipe_route_key' })
+})
+
+afterEach(() => {
+ config.registryConnectionMode = savedMode
+ config.registryUrl = savedUrl
+})
+
+describe('POST /admin/recipes — pull-secret provisioning (self-hosted)', () => {
+ it('provisions every platform namespace BEFORE persisting the CRD', async () => {
+ const gateway = new MockGateway(MCP_NS)
+ const createResource = vi.spyOn(gateway, 'createResource')
+
+ await request(makeApp(gateway)).post('/admin/recipes').send(platformRecipe('plat')).expect(201)
+
+ // Ordering is the point: a CRD persisted first would reference a Secret that does not
+ // exist yet, and a provisioning failure after the write leaves it stranded.
+ expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(mintOrgPullCredential).mock.invocationCallOrder[0]).toBeLessThan(
+ createResource.mock.invocationCallOrder[0]
+ )
+ for (const ns of PLATFORM_NAMESPACES) {
+ const secret = (await gateway.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns)) as {
+ type?: string
+ }
+ expect(secret.type).toBe('kubernetes.io/dockerconfigjson')
+ }
+ })
+
+ it('provisions nothing for a recipe with no platform-registry image', async () => {
+ const gateway = new MockGateway(MCP_NS)
+
+ await request(makeApp(gateway)).post('/admin/recipes').send(foreignRecipe('ext')).expect(201)
+
+ expect(mintOrgPullCredential).not.toHaveBeenCalled()
+ await expect(
+ gateway.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, SANDBOX_NS)
+ ).rejects.toBeTruthy()
+ })
+
+ it('maps a provisioning failure to its own status and persists NO recipe', async () => {
+ vi.mocked(resolvePublishScope).mockResolvedValue({ curator: false, orgName: null, scope: null })
+ const gateway = new MockGateway(MCP_NS)
+
+ const res = await request(makeApp(gateway)).post('/admin/recipes').send(platformRecipe('plat'))
+
+ expect(res.status).toBe(409)
+ expect(res.body).toMatchObject({
+ error: 'registry_pull_secret_provision_failed',
+ reason: 'org_unresolved',
+ })
+ await expect(gateway.getResource('workflowrecipes', 'plat', SANDBOX_NS)).rejects.toBeTruthy()
+ })
+})
+
+describe('PUT /admin/recipes/:name — pull-secret provisioning (self-hosted)', () => {
+ /** Seed a third-party-image recipe, so the update is what first pulls ours into play. */
+ async function seedForeignRecipe(gateway: MockGateway, name: string) {
+ await request(makeApp(gateway)).post('/admin/recipes').send(foreignRecipe(name)).expect(201)
+ vi.mocked(mintOrgPullCredential).mockClear()
+ }
+
+ it('provisions every platform namespace BEFORE persisting the update', async () => {
+ const gateway = new MockGateway(MCP_NS)
+ await seedForeignRecipe(gateway, 'plat')
+ const updateResource = vi.spyOn(gateway, 'updateResource')
+
+ await request(makeApp(gateway))
+ .put('/admin/recipes/plat')
+ .send({ spec: platformRecipe('plat').spec })
+ .expect(200)
+
+ expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(mintOrgPullCredential).mock.invocationCallOrder[0]).toBeLessThan(
+ updateResource.mock.invocationCallOrder[0]
+ )
+ for (const ns of PLATFORM_NAMESPACES) {
+ const secret = (await gateway.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns)) as {
+ type?: string
+ }
+ expect(secret.type).toBe('kubernetes.io/dockerconfigjson')
+ }
+ })
+
+ it('provisions nothing when the update keeps a third-party image', async () => {
+ const gateway = new MockGateway(MCP_NS)
+ await seedForeignRecipe(gateway, 'ext')
+
+ await request(makeApp(gateway))
+ .put('/admin/recipes/ext')
+ .send({ spec: foreignRecipe('ext').spec })
+ .expect(200)
+
+ expect(mintOrgPullCredential).not.toHaveBeenCalled()
+ await expect(
+ gateway.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, SANDBOX_NS)
+ ).rejects.toBeTruthy()
+ })
+
+ it('maps a provisioning failure to its own status and does NOT persist the update', async () => {
+ const gateway = new MockGateway(MCP_NS)
+ await seedForeignRecipe(gateway, 'plat')
+ vi.mocked(resolvePublishScope).mockResolvedValue({ curator: false, orgName: null, scope: null })
+
+ const res = await request(makeApp(gateway))
+ .put('/admin/recipes/plat')
+ .send({ spec: platformRecipe('plat').spec })
+
+ expect(res.status).toBe(409)
+ expect(res.body).toMatchObject({
+ error: 'registry_pull_secret_provision_failed',
+ reason: 'org_unresolved',
+ })
+ const stored = (await gateway.getResource('workflowrecipes', 'plat', SANDBOX_NS)) as {
+ spec: { workloads: Array<{ image: string }> }
+ }
+ expect(stored.spec.workloads[0].image).toBe('ghcr.io/acme/plugin:1.0')
+ })
+})
diff --git a/control-api/test/routes.adminRecipes.test.ts b/control-api/test/routes.adminRecipes.test.ts
index dc915ade1..f8e7255c5 100644
--- a/control-api/test/routes.adminRecipes.test.ts
+++ b/control-api/test/routes.adminRecipes.test.ts
@@ -5,6 +5,7 @@ import http from 'node:http'
import request from 'supertest'
import { config } from '../src/config.js'
import { createAdminRecipesRouter } from '../src/routes/admin/recipes.js'
+import { EVENFIRE_REGISTRY_PULL_SECRET_NAME } from '../src/routes/admin/registryImagePullSecret.js'
import { MockGateway } from './mockGateway.js'
vi.mock('node:dns/promises', () => ({
@@ -1631,6 +1632,28 @@ describe.sequential('routes/admin/recipes', () => {
await expect(gateway.getSecret('wf-example-coordinator-token', SANDBOX_NS)).rejects.toThrow()
})
+ it('POST /admin/recipes/secrets — rejects the platform registry pull Secret name', async () => {
+ // This endpoint writes Opaque + WORKFLOW_SECRET_LABELS, which carry the same
+ // `clerum.io/managed-by: control-api` marker the pull-secret service reads as its own
+ // ownership. Left unreserved, a request here would relabel (or shadow) the live
+ // credential; today only K8s type immutability stands in the way.
+ // Ownership is supplied so the ONLY thing that can reject this is the reserved name.
+ const res = await request(app)
+ .post('/admin/recipes/secrets')
+ .send({
+ name: EVENFIRE_REGISTRY_PULL_SECRET_NAME,
+ ownership: { kind: 'owner-recipe', recipeName: 'my-recipe' },
+ stringData: { token: 'not-a-pull-key' },
+ })
+ .expect(400)
+
+ expect(res.body.error).toMatch(/platform-managed/)
+
+ await expect(
+ gateway.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, SANDBOX_NS)
+ ).rejects.toThrow()
+ })
+
it('POST /admin/recipes/secrets — rejects invalid keys and non-string values', async () => {
await request(app)
.post('/admin/recipes/secrets')
@@ -2080,6 +2103,98 @@ describe.sequential('routes/admin/recipes', () => {
})
})
+ // ── The platform registry pull Secret is reserved, like the wf- prefix ────
+ //
+ // control-api writes `evenfire-registry-pull` into the platform workload namespaces and
+ // WRC injects the reference itself, after the #637 ownership filter. A recipe that names
+ // it is asking for something it will never legitimately get: a declared imagePullSecret
+ // is stripped as unowned (and re-injected anyway), while the same name in `envSecret` is
+ // an attempt to read the org's registry credential into a container's environment.
+ // Reject at the door — a declaration we silently ignore is worse than a 422.
+ const PLATFORM_PULL_SECRET_ENV_RECIPE = {
+ metadata: { name: 'pull-secret-env-recipe' },
+ spec: {
+ workloads: [
+ {
+ id: 'api',
+ type: 'deployment',
+ image: 'my-api:latest',
+ envSecret: {
+ name: EVENFIRE_REGISTRY_PULL_SECRET_NAME,
+ keys: [{ secretKey: '.dockerconfigjson', envVar: 'DOCKER_CONFIG' }],
+ },
+ },
+ ],
+ },
+ }
+
+ const PLATFORM_PULL_SECRET_IMAGE_RECIPE = {
+ metadata: { name: 'pull-secret-image-recipe' },
+ spec: {
+ workloads: [
+ {
+ id: 'api',
+ type: 'deployment',
+ image: 'my-api:latest',
+ imagePullSecrets: [EVENFIRE_REGISTRY_PULL_SECRET_NAME],
+ },
+ ],
+ },
+ }
+
+ it('POST /admin/recipes/validate — rejects workload envSecret naming the platform pull Secret', async () => {
+ const res = await request(app)
+ .post('/admin/recipes/validate')
+ .send(PLATFORM_PULL_SECRET_ENV_RECIPE)
+ .expect(422)
+
+ expect(res.body.valid).toBe(false)
+ expect(res.body.errors[0]).toMatchObject({
+ rule: 'workflowWorkloadSecretRefReserved',
+ field: 'spec.workloads[0].envSecret.name',
+ })
+ })
+
+ it('POST /admin/recipes/validate — rejects imagePullSecrets naming the platform pull Secret', async () => {
+ const res = await request(app)
+ .post('/admin/recipes/validate')
+ .send(PLATFORM_PULL_SECRET_IMAGE_RECIPE)
+ .expect(422)
+
+ expect(res.body.valid).toBe(false)
+ expect(res.body.errors[0]).toMatchObject({
+ rule: 'workflowWorkloadSecretRefReserved',
+ field: 'spec.workloads[0].imagePullSecrets[0]',
+ })
+ })
+
+ it('POST /admin/recipes — refuses to persist a recipe naming the platform pull Secret', async () => {
+ const res = await request(app)
+ .post('/admin/recipes')
+ .send(PLATFORM_PULL_SECRET_IMAGE_RECIPE)
+ .expect(422)
+
+ expect(res.body.errors[0]).toMatchObject({ rule: 'workflowWorkloadSecretRefReserved' })
+ await expect(
+ gateway.getResource('workflowrecipes', 'pull-secret-image-recipe', SANDBOX_NS)
+ ).rejects.toThrow()
+ })
+
+ it('PUT /admin/recipes/:name — refuses an update naming the platform pull Secret', async () => {
+ await request(app).post('/admin/recipes').send(VALID_RECIPE).expect(201)
+
+ const res = await request(app)
+ .put('/admin/recipes/my-recipe')
+ .send({ spec: PLATFORM_PULL_SECRET_ENV_RECIPE.spec })
+ .expect(422)
+
+ expect(res.body.errors[0]).toMatchObject({ rule: 'workflowWorkloadSecretRefReserved' })
+ const stored = (await gateway.getResource('workflowrecipes', 'my-recipe', SANDBOX_NS)) as {
+ spec: { workloads: Array<{ envSecret?: unknown }> }
+ }
+ expect(stored.spec.workloads[0].envSecret).toBeUndefined()
+ })
+
it('POST /admin/recipes/validate — accepts workload envSecret when Secret and keys exist', async () => {
gateway.seedSecret('workflow-api-credentials', SANDBOX_NS, {
data: { apiKey: 'dmFsdWU=', dbPassword: 'cGFzcw==' },