Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat: platform image-pull credentials for recipe workloads
Jose Ramirez0c381f5fc411
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 64b831807..bb7007cdb 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.400",+ "version": "0.1.401","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.400",+ "version": "0.1.401","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 377f347ea..4099c1caa 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.400",+ "version": "0.1.401","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/recipes.ts b/control-api/src/routes/admin/recipes.tsindex 58a83f81f..6700550fe 100644--- a/control-api/src/routes/admin/recipes.ts+++ b/control-api/src/routes/admin/recipes.ts@@ -1609,6 +1609,22 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {res.status(400).json({ error: 'at least one secret key/value is required' })return}+ // This endpoint writes `type: Opaque` (below). The kubelet only honors+ // `kubernetes.io/dockerconfigjson` / `dockercfg` Secrets for image pulls, so a+ // pull-secret-shaped payload written here would be accepted, stored, and then+ // SILENTLY ignored at pull time — surfacing much later as an unexplained+ // ImagePullBackOff. Refuse it instead of writing an object that cannot work.+ if (Object.keys(stringData).some(k => k === '.dockerconfigjson' || k === '.dockercfg')) {+ res.status(400).json({+ error:+ 'this endpoint creates Opaque secrets, which Kubernetes ignores for image pulls. ' ++ 'Images on the evenfire registry are handled automatically — no pull secret is ' ++ 'needed. For a third-party registry, create a kubernetes.io/dockerconfigjson ' ++ 'Secret in the workload namespace and label it clerum.io/owner-recipe=<recipe>.',+ key: '.dockerconfigjson',+ })+ return+ }const ownershipParse = parseWorkflowSecretOwnershipBody(body)if (!ownershipParse.ok) {res.status(400).json({ error: ownershipParse.error })diff --git a/control-api/src/routes/admin/registry.ts b/control-api/src/routes/admin/registry.tsindex 3ee84c9b6..a5af92e6c 100644--- a/control-api/src/routes/admin/registry.ts+++ b/control-api/src/routes/admin/registry.ts@@ -37,6 +37,8 @@ import { isRegistryAuthActive } from '../../services/registryConnectionDb.js'import {PullSecretProvisionError,ensureRegistryPullSecret,+ ensureRegistryPullSecrets,+ platformWorkloadNamespaces,} from '../../services/registryPullSecretService.js'import {validateWorkflowRecipeEgressPreflight,@@ -45,6 +47,7 @@ import {import { SecretUpsertRequest } from '../../types.js'import {EVENFIRE_REGISTRY_PULL_SECRET_NAME,+ isPlatformRegistryImage,shouldAttachEvenfirePullSecret,} from './registryImagePullSecret.js'import { checkEvenfireImageRefMatchesEntry } from './registryImageRefIdentity.js'@@ -354,6 +357,23 @@ function pullSecretErrorResponse(err: unknown): {}}+/**+ * 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 }@@ -1581,6 +1601,24 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {body.registryEntryVersion)+ // Ensure the platform pull credential before the CRD that will need it.+ //+ // Recipe workloads do NOT all land in the plugin namespace — they split by kind+ // (transport -> mcp-server, spec.ui.workloadRef -> sandbox-ui, rest ->+ // sandbox-recipes) — and WRC injects the pull-secret reference at reconcile time+ // for any workload whose image is ours. So provision the whole platform set: the+ // credential is per-org and the mint is rotate-on-call, so one pass covers every+ // namespace with a single mint (see registryPullSecretService).+ if (recipeReferencesPlatformImage(recipeSpec)) {+ try {+ await ensureRegistryPullSecrets(gateway, platformWorkloadNamespaces())+ } catch (err) {+ const mapped = pullSecretErrorResponse(err)+ res.status(mapped.status).json(mapped.body)+ return+ }+ }+// Step 4: Apply WorkflowRecipe CRDtry {await gateway.createResource('workflowrecipes', {diff --git a/control-api/src/routes/admin/registryImagePullSecret.ts b/control-api/src/routes/admin/registryImagePullSecret.tsindex d7ff20188..67d935dde 100644--- a/control-api/src/routes/admin/registryImagePullSecret.ts+++ b/control-api/src/routes/admin/registryImagePullSecret.ts@@ -1,54 +1,31 @@/*** evenfire pull-secret attach classification.*- * Pure, dependency-free helpers deciding whether an installed local-mode- * McpServer image should carry the `evenfire-registry-pull` imagePullSecret,- * i.e. when the image lives on the configured evenfire registry host. The Secret- * itself is self-provisioned by control-api in self-hosted mode- * (`registryPullSecretService`) and may also be pre-provisioned by an external- * operator; this file only decides when to reference it by name.- */--/**- * Name of the dockerconfigjson Secret referenced by local-mode McpServers whose- * image lives on the evenfire registry. The single source of truth for the name —- * `registryPullSecretService` writes it, this file references it. Never inline.- */-export const EVENFIRE_REGISTRY_PULL_SECRET_NAME = 'evenfire-registry-pull'--/**- * Extract the host (including any :port) from the configured registry URL.- * The registry URL always carries a scheme, so `new URL()` is correct here.- * Returns null when unset/whitespace/unparseable.+ * Decides whether an installed local-mode McpServer image should carry the+ * `evenfire-registry-pull` imagePullSecret — i.e. when the image lives on the configured+ * evenfire registry host. The Secret itself is self-provisioned by control-api in+ * self-hosted mode (`registryPullSecretService`) and may also be pre-provisioned by an+ * external operator; this file only decides when to reference it by name.+ *+ * The identity primitives now live in `@clerum/workflow-runtime-core`, because WRC asks+ * the same question of recipe workloads and a second copy would drift. They are+ * re-exported here so existing imports keep working against one definition.*/-export function registryHostFromUrl(registryUrl: string): string | null {- if (!registryUrl || !registryUrl.trim()) return null- try {- return new URL(registryUrl).host || null- } catch {- return null- }-}+import { isPlatformRegistryImage } from '@clerum/workflow-runtime-core'-/**- * Parse the registry host of a BARE OCI image reference (no scheme). Splits on- * the first `/`; the first component is a registry host only if it contains- * `.` or `:` (mirrors Docker/OCI semantics that distinguish a host from a- * docker-hub library/org path). Returns null when the ref has no explicit host- * (docker-hub `org/name` or a single-segment `name[:tag]`).- */-export function imageRefHost(image: string): string | null {- const trimmed = (image ?? '').trim()- if (!trimmed) return null- const slash = trimmed.indexOf('/')- if (slash === -1) return null- const first = trimmed.slice(0, slash)- return first.includes('.') || first.includes(':') ? first : null-}+export {+ EVENFIRE_REGISTRY_PULL_SECRET_NAME,+ imageRefHost,+ isPlatformRegistryImage,+ registryHostFromUrl,+} from '@clerum/workflow-runtime-core'/*** True when a built McpServer spec should carry the evenfire pull secret:* a local-mode entry whose image host equals the configured registry host.+ *+ * Remote-mode entries run a fixed egress-proxy image, never a registry-hosted one, so the+ * `isLocal` term is what keeps this narrower than the shared predicate.*/export function shouldAttachEvenfirePullSecret(params: {isLocal: boolean@@ -56,8 +33,5 @@ export function shouldAttachEvenfirePullSecret(params: {registryUrl: string}): boolean {if (!params.isLocal) return false- if (typeof params.image !== 'string') return false- const registryHost = registryHostFromUrl(params.registryUrl)- if (!registryHost) return false- return imageRefHost(params.image) === registryHost+ return isPlatformRegistryImage(params.image, params.registryUrl)}diff --git a/control-api/src/services/registryPullSecretService.ts b/control-api/src/services/registryPullSecretService.tsindex 158c461a0..b8614c057 100644--- a/control-api/src/services/registryPullSecretService.ts+++ b/control-api/src/services/registryPullSecretService.ts@@ -22,6 +22,7 @@* key — so a mint that is followed by a failed write strands every other namespace's* Secret on a revoked credential.*/+import { createHash } from 'node:crypto'import { config } from '../config.js'import type { K8sGateway } from '../k8s.js'import { rootLogger } from '../observability/logger.js'@@ -49,6 +50,7 @@ const MANAGED_BY_LABEL = 'clerum.io/managed-by'const MANAGED_BY_VALUE = 'control-api'const DOCKERCONFIG_KEY = '.dockerconfigjson'const DOCKERCONFIG_TYPE = 'kubernetes.io/dockerconfigjson'+const FINGERPRINT_ANNOTATION = 'clerum.io/pull-key-fingerprint'export type EnsurePullSecretResult =| 'created'@@ -115,79 +117,154 @@ function dockerconfigMatchesHost(blob: string | undefined, host: string): booleainterface SecretView {labels: Record<string, string>+ annotations: Record<string, string>type: string | undefineddockerconfig: string | undefined}function readSecret(raw: unknown): SecretView {const s = (raw ?? {}) as {- metadata?: { labels?: Record<string, string> }+ metadata?: { labels?: Record<string, string>; annotations?: Record<string, string> }type?: stringdata?: Record<string, string>}return {labels: s.metadata?.labels ?? {},+ annotations: s.metadata?.annotations ?? {},type: s.type,dockerconfig: s.data?.[DOCKERCONFIG_KEY],}}-function buildSecretReq(targetNs: string, dockerconfigjson: string): SecretUpsertRequest {+function buildSecretReq(targetNs: string, cred: MintedCredential): SecretUpsertRequest {return {name: EVENFIRE_REGISTRY_PULL_SECRET_NAME,namespace: targetNs,type: DOCKERCONFIG_TYPE,labels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE },- data: { [DOCKERCONFIG_KEY]: dockerconfigjson },+ annotations: { [FINGERPRINT_ANNOTATION]: cred.fingerprint },+ data: { [DOCKERCONFIG_KEY]: cred.dockerconfigjson },}}-async function mintAndBuild(orgName: string, host: string): Promise<string> {+interface MintedCredential {+ dockerconfigjson: string+ /** Short digest of the key, so copies in different namespaces can be compared. */+ fingerprint: string+}++/**+ * Mint ONE credential. Call this at most once per ensure pass: the registry's mint is+ * rotate-on-call, so a second mint revokes the first and would strand any namespace+ * already written with it.+ */+async function mintCredential(orgName: string, host: string): Promise<MintedCredential> {const { key } = await mintOrgPullCredential(orgName)- return buildDockerconfigjson(host, key)+ return {+ dockerconfigjson: buildDockerconfigjson(host, key),+ fingerprint: createHash('sha256').update(key).digest('hex').slice(0, 12),+ }}-// Collapse concurrent ensures for the same (namespace, secret) WITHIN this replica so two-// in-flight installs cannot both mint. Cross-replica races are bounded by the registry's-// rotate-on-call (<=1 active pull key per org) plus the read-before-mint discipline below:-// the loser of a create race re-reads and adopts the winner's Secret instead of minting.-const inflight = new Map<string, Promise<EnsurePullSecretResult>>()+// Collapse concurrent ensure passes WITHIN this replica so two in-flight installs cannot+// both mint. Keyed on the whole target set, since a pass is atomic over its namespaces.+const inflight = new Map<string, Promise<Map<string, EnsurePullSecretResult>>>()++/** The platform workload namespaces a pull credential may legitimately be written into. */+export function platformWorkloadNamespaces(): string[] {+ return [+ ...new Set([config.mcpServersNamespace, config.sandboxNamespace, config.sandboxUiNamespace]),+ ]+}/**- * Ensure the `evenfire-registry-pull` Secret exists in `targetNs`, minting a fresh- * pull-only credential only when it is absent or verifiably broken.+ * Ensure the `evenfire-registry-pull` Secret exists, and is current, in EVERY given+ * namespace — minting at most ONE credential for the whole pass.+ *+ * The credential is per-ORG but the Secret is per-NAMESPACE, and the registry's mint is+ * rotate-on-call (it revokes the org's previous key). Minting per namespace would+ * therefore have each mint invalidate the namespaces already written. So: read all, mint+ * once if any target needs it, then write that single credential to every target we own.+ *+ * Post-condition: every non-foreign target holds the same, current credential.*- * Returns `'skipped'` ONLY when provisioning is legitimately not our job (managed mode,- * where the operator owns the Secret) or when no registry host is configured. Every other- * "cannot provision" condition THROWS `PullSecretProvisionError` so the caller fails the- * install loudly instead of attaching an unresolvable imagePullSecrets reference.+ * Returns `'skipped'` for all targets ONLY when provisioning is legitimately not our job+ * (managed mode, or no registry configured). Every other "cannot provision" condition+ * THROWS `PullSecretProvisionError`, so a caller about to attach an imagePullSecrets+ * reference fails the install loudly instead of persisting an unresolvable one.*/-export function ensureRegistryPullSecret(+export function ensureRegistryPullSecrets(gateway: K8sGateway,- targetNs: string-): Promise<EnsurePullSecretResult> {- const dedupeKey = `${targetNs}/${EVENFIRE_REGISTRY_PULL_SECRET_NAME}`+ namespaces: string[]+): Promise<Map<string, EnsurePullSecretResult>> {+ const targets = [...new Set(namespaces)].sort()+ const dedupeKey = targets.join(',')const existing = inflight.get(dedupeKey)if (existing) return existing- const run = ensureInner(gateway, targetNs).finally(() => inflight.delete(dedupeKey))+ const run = ensureInner(gateway, targets).finally(() => inflight.delete(dedupeKey))inflight.set(dedupeKey, run)return run}-async function ensureInner(gateway: K8sGateway, targetNs: string): Promise<EnsurePullSecretResult> {+/**+ * Single-namespace convenience wrapper, for the McpServer install/upgrade paths that+ * provision exactly the namespace their workload lands in.+ */+export async function ensureRegistryPullSecret(+ gateway: K8sGateway,+ targetNs: string+): Promise<EnsurePullSecretResult> {+ const results = await ensureRegistryPullSecrets(gateway, [targetNs])+ return results.get(targetNs) ?? 'skipped'+}++/** Classification of one namespace's current Secret, decided before anything is minted. */+type TargetState =+ | { kind: 'foreign' }+ | { kind: 'valid'; fingerprint: string }+ | { kind: 'absent' }+ | { kind: 'broken'; wrongType: boolean }++function classify(current: SecretView | null, host: string): TargetState {+ if (!current) return { kind: 'absent' }+ // INVARIANT 1: never write a Secret we do not own — even a broken one. Adopting it would+ // seize an external operator's credential; repairing it in place would rotate the org+ // key out from under them.+ if (current.labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) return { kind: 'foreign' }+ const wrongType = current.type !== DOCKERCONFIG_TYPE+ // Presence alone is not enough: a blob keyed on a previous registry host can never be+ // selected by the kubelet, and a copy with no fingerprint cannot be compared across+ // namespaces.+ const fingerprint = current.annotations[FINGERPRINT_ANNOTATION]+ if (wrongType || !dockerconfigMatchesHost(current.dockerconfig, host) || !fingerprint) {+ return { kind: 'broken', wrongType }+ }+ return { kind: 'valid', fingerprint }+}++async function ensureInner(+ gateway: K8sGateway,+ targets: string[]+): Promise<Map<string, EnsurePullSecretResult>> {+ const out = new Map<string, EnsurePullSecretResult>()+// ── Legitimate no-ops ─────────────────────────────────────────────────────// Managed clusters: the operator owns this Secret; never contend with it.- if (config.registryConnectionMode !== 'self-hosted') return 'skipped'const host = registryHostFromUrl(config.registryUrl)- if (!host) return 'skipped' // no registry configured; the attach predicate is false too+ if (config.registryConnectionMode !== 'self-hosted' || !host) {+ for (const ns of targets) out.set(ns, 'skipped')+ return out+ }// ── Hard preconditions: from here on we MUST provision or fail loudly ─────- // The pull Secret is a registry credential. Confine writes to the namespace this- // deployment actually serves so a caller-supplied `body.namespace` cannot plant it- // in an unrelated namespace (and cannot rotate the org key as a side effect).- if (targetNs !== config.mcpServersNamespace) {+ // The pull Secret is a registry credential. Confine writes to the platform workload+ // namespaces so a caller-supplied `body.namespace` can never plant it elsewhere (and+ // can never rotate the org key as a side effect).+ const allowed = new Set(platformWorkloadNamespaces())+ const rogue = targets.filter(ns => !allowed.has(ns))+ if (rogue.length > 0) {throw new PullSecretProvisionError(- `refusing to provision the registry pull secret outside the configured plugin namespace (got "${targetNs}", expected "${config.mcpServersNamespace}")`,+ `refusing to provision the registry pull secret outside the platform workload namespaces (got ${rogue.map(n => `"${n}"`).join(', ')}, allowed ${[...allowed].map(n => `"${n}"`).join(', ')})`,'unsupported_namespace',400)@@ -211,66 +288,107 @@ async function ensureInner(gateway: K8sGateway, targetNs: string): Promise<Ensur)}- // ── Read (getSecret re-throws 404; any other error aborts before minting) ──- const current = await readCurrent(gateway, targetNs)+ // ── Read + classify every target BEFORE minting anything ──────────────────+ const states = new Map<string, TargetState>()+ for (const ns of targets) {+ states.set(ns, classify(await readCurrent(gateway, ns), host))+ }- if (current) {- const ours = current.labels[MANAGED_BY_LABEL] === MANAGED_BY_VALUE- // INVARIANT 1: never write a Secret we do not own — even a broken one. Adopting it- // would seize an external operator's credential; repairing it in place would rotate- // the org key out from under them.- if (!ours) {- if (!dockerconfigMatchesHost(current.dockerconfig, host)) {- logger.warn(- { targetNs, host },- 'externally-owned evenfire-registry-pull Secret is missing or mis-keyed; leaving it untouched (remove it to let control-api provision one)'- )- }- return 'exists-foreign'- }- // Ours and genuinely usable → reuse. Presence alone is not enough: a blob keyed on a- // previous registry host can never be selected by the kubelet.- if (current.type === DOCKERCONFIG_TYPE && dockerconfigMatchesHost(current.dockerconfig, host)) {- return 'exists-ours'+ const ours = targets.filter(ns => states.get(ns)!.kind !== 'foreign')+ for (const ns of targets) {+ if (states.get(ns)!.kind === 'foreign') {+ logger.warn(+ { namespace: ns },+ 'externally-owned evenfire-registry-pull Secret present; leaving it untouched (remove it to let control-api manage this namespace)'+ )+ out.set(ns, 'exists-foreign')}- // Ours but broken. `Secret.type` is immutable, so a wrong-typed Secret must be- // recreated. Delete FIRST so a failed delete cannot strand a freshly-minted key.- if (current.type !== DOCKERCONFIG_TYPE) {- await gateway.deleteSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, targetNs)- await gateway.createSecret(buildSecretReq(targetNs, await mintAndBuild(orgName, host)))- } else {- await gateway.updateSecret(buildSecretReq(targetNs, await mintAndBuild(orgName, host)))+ }+ if (ours.length === 0) return out++ // A mint is needed when any namespace we own lacks a usable credential, OR when the+ // copies have diverged — divergence means an earlier pass wrote some namespaces and+ // failed on others, and we cannot recover the live key from a fingerprint.+ const valid = ours.filter(ns => states.get(ns)!.kind === 'valid')+ const fingerprints = new Set(+ valid.map(ns => (states.get(ns) as { fingerprint: string }).fingerprint)+ )+ const diverged = fingerprints.size > 1+ const needsMint = valid.length !== ours.length || diverged++ if (!needsMint) {+ for (const ns of ours) out.set(ns, 'exists-ours')+ return out+ }+ if (diverged) {+ logger.warn(+ { namespaces: ours },+ 'registry pull secret copies diverged across namespaces; re-minting to converge'+ )+ }++ // `Secret.type` is immutable, so a wrong-typed Secret must be deleted and recreated.+ // Do every delete BEFORE minting: a delete that fails must not leave us holding a+ // freshly-minted key that has already revoked the credential the cluster was using.+ const recreate = new Set<string>()+ for (const ns of ours) {+ const state = states.get(ns)!+ if (state.kind === 'broken' && state.wrongType) {+ await gateway.deleteSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns)+ recreate.add(ns)}- logger.info({ targetNs, orgName }, 'registry pull secret repaired')- auditPullSecret('registry_pull_secret_provisioned', {- namespace: targetNs,- org: orgName,- outcome: 'repaired',- })- return 'repaired'}- // ── Absent → mint + create ────────────────────────────────────────────────- try {- await gateway.createSecret(buildSecretReq(targetNs, await mintAndBuild(orgName, host)))- } catch (err) {- if (k8sStatus(err) !== 409) throw err- // Lost a concurrent create race. Do NOT mint again — a second mint would revoke the- // key the winner just stored. Re-read and adopt whatever is now there.- const winner = await readCurrent(gateway, targetNs)- if (!winner) throw err // vanished again; surface rather than loop- const winnerOurs = winner.labels[MANAGED_BY_LABEL] === MANAGED_BY_VALUE- if (!winnerOurs) return 'exists-foreign'- logger.info({ targetNs, orgName }, 'registry pull secret already created concurrently')- return 'exists-ours'+ // ── Mint ONCE, then fan the same credential out to every namespace we own ──+ // Namespaces that were already valid are rewritten too: the mint just revoked the key+ // they were holding.+ const cred = await mintCredential(orgName, host)+ for (const ns of ours) {+ const state = states.get(ns)!+ const outcome = await writeCredential(gateway, ns, state, cred, recreate.has(ns))+ out.set(ns, outcome)}- logger.info({ targetNs, orgName }, 'registry pull secret created')+auditPullSecret('registry_pull_secret_provisioned', {- namespace: targetNs,+ namespaces: ours,org: orgName,- outcome: 'created',+ fingerprint: cred.fingerprint,})- return 'created'+ logger.info({ namespaces: ours, orgName }, 'registry pull secret provisioned')+ return out+}++/** Write `cred` into one namespace, choosing create/update/recreate from its prior state. */+async function writeCredential(+ gateway: K8sGateway,+ ns: string,+ state: TargetState,+ cred: MintedCredential,+ alreadyDeleted: boolean+): Promise<EnsurePullSecretResult> {+ // Wrong-typed Secrets were deleted before the mint (see ensureInner), so they are now+ // absent and must be created, not updated.+ if (alreadyDeleted) {+ await gateway.createSecret(buildSecretReq(ns, cred))+ return 'repaired'+ }+ if (state.kind === 'absent') {+ try {+ await gateway.createSecret(buildSecretReq(ns, cred))+ return 'created'+ } catch (err) {+ if (k8sStatus(err) !== 409) throw err+ // Lost a create race. The winner's Secret is authoritative for its own content, but+ // OUR mint has already revoked whatever key it holds — so overwrite it with ours+ // rather than adopting a now-dead credential. Skip if the winner is foreign.+ const winner = await readCurrent(gateway, ns)+ if (winner && winner.labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) return 'exists-foreign'+ await gateway.updateSecret(buildSecretReq(ns, cred))+ return 'created'+ }+ }+ await gateway.updateSecret(buildSecretReq(ns, cred))+ return state.kind === 'valid' ? 'exists-ours' : 'repaired'}/** Read the Secret, mapping 404 to null. Any other error propagates (e.g. 403 = wrong ns). */diff --git a/control-api/test/registryPullSecretService.test.ts b/control-api/test/registryPullSecretService.test.tsindex 78d789d8c..247ac32ce 100644--- a/control-api/test/registryPullSecretService.test.ts+++ b/control-api/test/registryPullSecretService.test.ts@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { createHash } from 'node:crypto'import { config } from '../src/config.js'import type { K8sGateway } from '../src/k8s.js'import { EVENFIRE_REGISTRY_PULL_SECRET_NAME } from '../src/routes/admin/registryImagePullSecret.js'@@ -7,6 +8,7 @@ import { isRegistryAuthActive } from '../src/services/registryConnectionDb.js'import {PullSecretProvisionError,ensureRegistryPullSecret,+ ensureRegistryPullSecrets,} from '../src/services/registryPullSecretService.js'import { MockGateway } from './mockGateway.js'@@ -22,6 +24,12 @@ const NS = 'mcp-server'const HOST = 'registry.evenfire.ai'const DOCKERCONFIG_KEY = '.dockerconfigjson'const OURS = { 'clerum.io/managed-by': 'control-api' }+const FINGERPRINT_ANNOTATION = 'clerum.io/pull-key-fingerprint'++/** Mirrors the service's fingerprint derivation so seeds can look already-provisioned. */+function fingerprintOf(key: string): string {+ return createHash('sha256').update(key).digest('hex').slice(0, 12)+}function gw(): { gateway: K8sGateway; mock: MockGateway } {const mock = new MockGateway(NS)@@ -36,15 +44,23 @@ function encodeDockercfg(host: string, key: string): string {).toString('base64')}-async function readStored(- mock: MockGateway-): Promise<{ type?: string; labels: Record<string, string>; blob?: string }> {+async function readStored(mock: MockGateway): Promise<{+ type?: string+ labels: Record<string, string>+ annotations: Record<string, string>+ blob?: string+}> {const raw = (await mock.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)) as {- metadata?: { labels?: Record<string, string> }+ metadata?: { labels?: Record<string, string>; annotations?: Record<string, string> }type?: stringdata?: Record<string, string>}- return { type: raw.type, labels: raw.metadata?.labels ?? {}, blob: raw.data?.[DOCKERCONFIG_KEY] }+ return {+ type: raw.type,+ labels: raw.metadata?.labels ?? {},+ annotations: raw.metadata?.annotations ?? {},+ blob: raw.data?.[DOCKERCONFIG_KEY],+ }}function decodeHosts(blob: string | undefined): string[] {@@ -167,6 +183,7 @@ describe('ensureRegistryPullSecret — provisioning', () => {mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {type: 'kubernetes.io/dockerconfigjson',labels: OURS,+ annotations: { [FINGERPRINT_ANNOTATION]: fingerprintOf('efrk_live') },data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_live') },})await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-ours')@@ -205,7 +222,8 @@ describe('ensureRegistryPullSecret — provisioning', () => {const deleteSpy = vi.spyOn(mock, 'deleteSecret')await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('repaired')// An in-place update of `type` would 422, so it must delete first — and the delete- // must precede the mint so a failed delete cannot strand a freshly-rotated key.+ // must still precede the (now single, up-front) mint, so a failed delete cannot+ // strand a freshly-rotated key that has already revoked the cluster's credential.expect(deleteSpy).toHaveBeenCalledWith(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)expect(deleteSpy.mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(mintOrgPullCredential).mock.invocationCallOrder[0]@@ -249,9 +267,128 @@ describe('ensureRegistryPullSecret — concurrent create race', () => {})throw Object.assign(new Error('already exists'), { statusCode: 409, code: 409 })})- await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-ours')- // Exactly ONE mint — a second would revoke the key the winner just stored.+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('created')+ // Exactly ONE mint. Our mint already revoked whatever the winner stored, so we+ // overwrite with ours rather than adopting a now-dead credential.expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)- expect(decodeHosts((await readStored(mock)).blob)).toEqual([HOST])+ const stored = await readStored(mock)+ expect(decodeHosts(stored.blob)).toEqual([HOST])+ expect(stored.annotations[FINGERPRINT_ANNOTATION]).toBe(fingerprintOf('efrk_test_key'))+ })+})++describe('ensureRegistryPullSecrets — fan-out across platform namespaces', () => {+ const SANDBOX = 'sandbox-recipes'+ const UI = 'sandbox-ui'+ const ALL = [NS, SANDBOX, UI]++ async function blobIn(mock: MockGateway, ns: string) {+ const raw = (await mock.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns)) as {+ metadata?: { annotations?: Record<string, string> }+ data?: Record<string, string>+ }+ return {+ blob: raw.data?.[DOCKERCONFIG_KEY],+ fingerprint: raw.metadata?.annotations?.[FINGERPRINT_ANNOTATION],+ }+ }++ it('mints EXACTLY ONCE and writes the same credential to every namespace', async () => {+ const { gateway, mock } = gw()+ const res = await ensureRegistryPullSecrets(gateway, ALL)++ // The registry mint is rotate-on-call: a second mint would revoke the key the first+ // namespaces were just given. One mint, N copies, is the whole invariant.+ expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)+ expect([...res.values()]).toEqual(['created', 'created', 'created'])++ const seen = await Promise.all(ALL.map(ns => blobIn(mock, ns)))+ expect(new Set(seen.map(s => s.blob)).size).toBe(1)+ expect(new Set(seen.map(s => s.fingerprint)).size).toBe(1)+ expect(seen[0].fingerprint).toBe(fingerprintOf('efrk_test_key'))+ })++ it('re-mints once and rewrites ALL namespaces when only one is missing', async () => {+ const { gateway, mock } = gw()+ // Two namespaces already hold a valid, matching credential; the third is absent.+ for (const ns of [NS, SANDBOX]) {+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: OURS,+ annotations: { [FINGERPRINT_ANNOTATION]: fingerprintOf('efrk_old') },+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_old') },+ })+ }+ await ensureRegistryPullSecrets(gateway, ALL)++ expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)+ // The already-valid namespaces MUST be rewritten: minting for the third revoked the+ // key they were holding. Leaving them alone is the cross-namespace corruption bug.+ const seen = await Promise.all(ALL.map(ns => blobIn(mock, ns)))+ expect(new Set(seen.map(s => s.fingerprint))).toEqual(new Set([fingerprintOf('efrk_test_key')]))+ })++ it('does not mint when every namespace already agrees', async () => {+ const { gateway, mock } = gw()+ for (const ns of ALL) {+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: OURS,+ annotations: { [FINGERPRINT_ANNOTATION]: fingerprintOf('efrk_live') },+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_live') },+ })+ }+ const res = await ensureRegistryPullSecrets(gateway, ALL)+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ expect([...res.values()]).toEqual(['exists-ours', 'exists-ours', 'exists-ours'])+ })++ it('re-mints to converge when copies have DIVERGED', async () => {+ const { gateway, mock } = gw()+ // A previous pass minted and then failed partway: two namespaces carry one key, the+ // third a different one. Only one can still be active registry-side.+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: OURS,+ annotations: { [FINGERPRINT_ANNOTATION]: fingerprintOf('efrk_a') },+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_a') },+ })+ for (const ns of [SANDBOX, UI]) {+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: OURS,+ annotations: { [FINGERPRINT_ANNOTATION]: fingerprintOf('efrk_b') },+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_b') },+ })+ }+ await ensureRegistryPullSecrets(gateway, ALL)++ expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)+ const seen = await Promise.all(ALL.map(ns => blobIn(mock, ns)))+ expect(new Set(seen.map(s => s.fingerprint)).size).toBe(1)+ })++ it('skips a foreign namespace but still provisions the others', async () => {+ const { gateway, mock } = gw()+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, SANDBOX, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: 'operator-provisioned' },+ })+ const res = await ensureRegistryPullSecrets(gateway, ALL)++ expect(res.get(SANDBOX)).toBe('exists-foreign')+ expect(res.get(NS)).toBe('created')+ expect(res.get(UI)).toBe('created')+ // Untouched, byte for byte.+ expect((await blobIn(mock, SANDBOX)).blob).toBe('operator-provisioned')+ })++ it('refuses a namespace outside the platform set, before minting', async () => {+ const { gateway } = gw()+ await expect(ensureRegistryPullSecrets(gateway, [NS, 'channels'])).rejects.toMatchObject({+ reason: 'unsupported_namespace',+ status: 400,+ })+ expect(mintOrgPullCredential).not.toHaveBeenCalled()})})diff --git a/control-api/test/routes.registryInstall.pullSecret.test.ts b/control-api/test/routes.registryInstall.pullSecret.test.tsindex 761e71a4d..019af230b 100644--- a/control-api/test/routes.registryInstall.pullSecret.test.ts+++ b/control-api/test/routes.registryInstall.pullSecret.test.ts@@ -218,3 +218,85 @@ describe('POST /admin/registry/install — pull-secret provisioning (self-hostedexpect(mcp.spec.imagePullSecrets).toBeUndefined()})})++describe('POST /admin/registry/install-recipe — pull-secret provisioning (self-hosted)', () => {+ const PLATFORM_NAMESPACES = ['mcp-server', 'sandbox-recipes', 'sandbox-ui']++ function recipeEntry(image: string) {+ return {+ id: 'r1',+ name: 'intel-report',+ version: '1.0.0',+ entry_type: 'recipe',+ description: 'Research + PDF report',+ author: 'acme',+ server_mode: null,+ transport: null,+ recipe_type: 'workflow',+ mcp_server_meta: null,+ recipe_meta: {+ recipeYaml: JSON.stringify({+ spec: {+ description: 'Intel',+ steps: [{ id: 'research', description: 'Research step' }],+ workloads: [{ id: 'w1', type: 'deployment', image }],+ },+ }),+ stepCount: 1,+ hasAgent: true,+ },+ }+ }++ function recipeBody() {+ return { registryEntryName: 'intel-report', registryEntryVersion: '1.0.0' }+ }++ it('provisions the credential in EVERY platform namespace, minting once', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(+ recipeEntry(`${REGISTRY_HOST}/acme/plugin:1.0`) as never+ )+ const { app, gw } = makeInstallApp()++ await request(app).post('/admin/registry/install-recipe').send(recipeBody()).expect(201)++ // Recipe workloads split across namespaces by kind, and WRC injects the reference at+ // reconcile time — so all three must hold the credential, from ONE mint (the registry+ // mint is rotate-on-call; a second would revoke the first).+ 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 for a recipe with no platform-registry image', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(+ recipeEntry('ghcr.io/acme/plugin:1.0') as never+ )+ const { app, gw } = makeInstallApp()++ await request(app).post('/admin/registry/install-recipe').send(recipeBody()).expect(201)++ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ await expect(+ gw.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, 'sandbox-recipes')+ ).rejects.toBeTruthy()+ })++ it('fails the recipe install loudly when provisioning fails', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(+ recipeEntry(`${REGISTRY_HOST}/acme/plugin:1.0`) as never+ )+ vi.mocked(mintOrgPullCredential).mockRejectedValueOnce(new Error('registry unavailable'))+ const { app, gw } = makeInstallApp()++ const res = await request(app).post('/admin/registry/install-recipe').send(recipeBody())+ expect(res.status).toBeGreaterThanOrEqual(500)+ expect(res.body.error).toBe('registry_pull_secret_provision_failed')+ // No WorkflowRecipe may be persisted referencing a credential that does not exist.+ await expect(gw.getResource('workflowrecipes', 'intel-report', NS)).rejects.toBeTruthy()+ })+})diff --git a/docs/architecture/registry-pull-secret-recipe-workloads.md b/docs/architecture/registry-pull-secret-recipe-workloads.mdindex 1cbbe1771..6fd427ad1 100644--- a/docs/architecture/registry-pull-secret-recipe-workloads.md+++ b/docs/architecture/registry-pull-secret-recipe-workloads.md@@ -1,6 +1,6 @@# Platform image-pull credentials for recipe workloads-**Status:** Draft / proposed+**Status:** Implemented (see PR #243)**Date:** 2026-08-04**Area:** control-api · workflow-recipes (WRC) · workflow-runtime-core · image pull · self-hosted**Follows:** [`registry-pull-secret-self-provisioning.md`](registry-pull-secret-self-provisioning.md)@@ -344,6 +344,21 @@ kubelet ignores is the one outcome that must not remain.## 7. Implementation+> **As-built note.** Shipped in PR #243 alongside the MCP-server slice. Two deviations+> from the plan below, both deliberate:+> - **`buildSecretReq` carries a key fingerprint annotation**+> (`clerum.io/pull-key-fingerprint`), and a copy *without* one is treated as broken. This+> is what makes cross-namespace divergence detectable — and it means Secrets written by+> the pre-fan-out code are re-minted once on upgrade, converging the cluster onto the+> annotated form.+> - **Wrong-typed Secrets are deleted BEFORE the single mint**, not during the per-namespace+> write. A delete that fails must not leave us holding a freshly-minted key that has+> already revoked the credential the cluster was using.+>+> WRC reads the registry URL via `loadConfig().registryUrl` at the point of use, matching+> the existing pattern in `restEndpoints.ts` rather than threading a new parameter through+> every builder call site.+**`packages/workflow-runtime-core`**- Add `registry-image.ts`: the name constant + `registryHostFromUrl` / `imageRefHost` /`isPlatformRegistryImage`, moved (not copied) fromdiff --git a/packages/workflow-runtime-core/src/index.ts b/packages/workflow-runtime-core/src/index.tsindex fc545665f..bbcefe2bb 100644--- a/packages/workflow-runtime-core/src/index.ts+++ b/packages/workflow-runtime-core/src/index.ts@@ -52,3 +52,10 @@ export type { PromptContext } from './injection/prompt'export type { SignalCallback } from './signal-poller/poller'export type { RuntimeTokenProvider } from './runtime-token-provider/provider'export type { ModelInjectionRequest } from './injection/model'++export {+ EVENFIRE_REGISTRY_PULL_SECRET_NAME,+ registryHostFromUrl,+ imageRefHost,+ isPlatformRegistryImage,+} from './registry-image'diff --git a/packages/workflow-runtime-core/src/registry-image.ts b/packages/workflow-runtime-core/src/registry-image.tsnew file mode 100644index 000000000..3db5a16c3--- /dev/null+++ b/packages/workflow-runtime-core/src/registry-image.ts@@ -0,0 +1,69 @@+// Platform image-pull identity — the SINGLE source of truth for "is this image hosted on+// our own registry, and therefore covered by the platform pull credential?", shared by+// every place that decides it: control-api (McpServer install/upgrade + recipe install)+// and the WRC reconciler (pod templates + McpServer delegation).+//+// This lives in @clerum/workflow-runtime-core, not copied per service, for the same reason+// the recipe/Secret ownership rule does (see secret-ownership.ts): two services answering+// the same question from two copies is exactly how they drift. Here the drift would be+// silent and ugly — WRC would decline to attach the pull secret to a workload whose image+// control-api considers ours, producing an ImagePullBackOff with no failing request to+// attribute it to.++/**+ * Name of the dockerconfigjson Secret carrying the platform registry pull credential.+ *+ * A cross-service contract: control-api WRITES it (one per platform workload namespace),+ * WRC and control-api REFERENCE it in `imagePullSecrets`, and HCC materializes that+ * reference verbatim onto the pod. Never inline the literal.+ */+export const EVENFIRE_REGISTRY_PULL_SECRET_NAME = 'evenfire-registry-pull'++/**+ * Extract the host (including any :port) from the configured registry URL.+ * The registry URL always carries a scheme, so `new URL()` is correct here.+ * Returns null when unset/whitespace/unparseable.+ */+export function registryHostFromUrl(registryUrl: string): string | null {+ if (!registryUrl || !registryUrl.trim()) return null+ try {+ return new URL(registryUrl).host || null+ } catch {+ return null+ }+}++/**+ * Parse the registry host of a BARE OCI image reference (no scheme). Splits on the first+ * `/`; the first component is a registry host only if it contains `.` or `:` (mirroring+ * Docker/OCI semantics, which distinguish a host from a docker-hub library/org path).+ * Returns null when the ref has no explicit host (docker-hub `org/name`, or a+ * single-segment `name[:tag]`).+ */+export function imageRefHost(image: string): string | null {+ const trimmed = (image ?? '').trim()+ if (!trimmed) return null+ const slash = trimmed.indexOf('/')+ if (slash === -1) return null+ const first = trimmed.slice(0, slash)+ return first.includes('.') || first.includes(':') ? first : null+}++/**+ * True when `image` is hosted on the configured platform registry — i.e. the kubelet will+ * need the platform pull credential to fetch it.+ *+ * Deliberately keyed on the IMAGE host matching the configured registry host, because that+ * is what the kubelet matches on when selecting an entry from a dockerconfigjson `auths`+ * map. The registry's own token-issuer hostname is independent config and must never be+ * substituted here.+ *+ * Non-string images and an unset/unparseable `registryUrl` are false: with no registry+ * configured there is no platform credential to attach.+ */+export function isPlatformRegistryImage(image: unknown, registryUrl: string): boolean {+ if (typeof image !== 'string') return false+ const registryHost = registryHostFromUrl(registryUrl)+ if (!registryHost) return false+ return imageRefHost(image) === registryHost+}diff --git a/packages/workflow-runtime-core/tests/unit/registry-image.test.ts b/packages/workflow-runtime-core/tests/unit/registry-image.test.tsnew file mode 100644index 000000000..6ff7b1cc6--- /dev/null+++ b/packages/workflow-runtime-core/tests/unit/registry-image.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from 'vitest'+import {+ EVENFIRE_REGISTRY_PULL_SECRET_NAME,+ imageRefHost,+ isPlatformRegistryImage,+ registryHostFromUrl,+} from '../../src/registry-image'++const REGISTRY_URL = 'https://registry.evenfire.ai'++describe('EVENFIRE_REGISTRY_PULL_SECRET_NAME', () => {+ // Cross-service contract: control-api writes it, WRC/control-api reference it, HCC+ // materializes it. A rename here silently breaks image pulls everywhere.+ it('is the frozen pull-secret name', () => {+ expect(EVENFIRE_REGISTRY_PULL_SECRET_NAME).toBe('evenfire-registry-pull')+ })+})++describe('registryHostFromUrl', () => {+ it('extracts host, preserving a port', () => {+ expect(registryHostFromUrl('https://registry.evenfire.ai')).toBe('registry.evenfire.ai')+ expect(registryHostFromUrl('http://registry-api.registry.svc:5000')).toBe(+ 'registry-api.registry.svc:5000'+ )+ })++ it('returns null for unset, blank, or unparseable input', () => {+ expect(registryHostFromUrl('')).toBeNull()+ expect(registryHostFromUrl(' ')).toBeNull()+ expect(registryHostFromUrl('not a url')).toBeNull()+ })+})++describe('imageRefHost', () => {+ it('reads an explicit host', () => {+ expect(imageRefHost('registry.evenfire.ai/acme/img:1.0')).toBe('registry.evenfire.ai')+ expect(imageRefHost('localhost:5000/img')).toBe('localhost:5000')+ })++ it('returns null when there is no explicit host (docker-hub style)', () => {+ // First component is a host only if it carries a '.' or ':' — otherwise it is a+ // docker-hub org/library path, not a registry.+ expect(imageRefHost('library/postgres:16')).toBeNull()+ expect(imageRefHost('postgres:16')).toBeNull()+ expect(imageRefHost('')).toBeNull()+ })+})++describe('isPlatformRegistryImage', () => {+ it('is true only when the image host equals the configured registry host', () => {+ expect(isPlatformRegistryImage('registry.evenfire.ai/acme/img:1', REGISTRY_URL)).toBe(true)+ expect(isPlatformRegistryImage('ghcr.io/acme/img:1', REGISTRY_URL)).toBe(false)+ expect(isPlatformRegistryImage('postgres:16', REGISTRY_URL)).toBe(false)+ })++ it('is false when no registry is configured — there is no credential to attach', () => {+ expect(isPlatformRegistryImage('registry.evenfire.ai/acme/img:1', '')).toBe(false)+ expect(isPlatformRegistryImage('registry.evenfire.ai/acme/img:1', 'not a url')).toBe(false)+ })++ it('is false for a non-string image', () => {+ expect(isPlatformRegistryImage(undefined, REGISTRY_URL)).toBe(false)+ expect(isPlatformRegistryImage(null, REGISTRY_URL)).toBe(false)+ expect(isPlatformRegistryImage(42, REGISTRY_URL)).toBe(false)+ })++ it('does not match on a host suffix or a lookalike host', () => {+ // A naive `endsWith`/`includes` would wrongly accept an attacker-controlled host.+ expect(isPlatformRegistryImage('evil-registry.evenfire.ai/x/y:1', REGISTRY_URL)).toBe(false)+ expect(isPlatformRegistryImage('registry.evenfire.ai.evil.com/x/y:1', REGISTRY_URL)).toBe(false)+ })++ it('distinguishes a port difference', () => {+ expect(isPlatformRegistryImage('localhost:5000/img:1', 'http://localhost:5001')).toBe(false)+ expect(isPlatformRegistryImage('localhost:5000/img:1', 'http://localhost:5000')).toBe(true)+ })+})diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex f73e6fb39..a4d0a0b62 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.256",+ "version": "0.1.257","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.256",+ "version": "0.1.257","license": "SEE LICENSE IN LICENSE","dependencies": {"@aws-sdk/client-s3": "^3.1009.0",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex c618b11d4..e225b0095 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.256",+ "version": "0.1.257","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/config.ts b/workflow-recipes/src/config.tsindex 282145c5b..fdaa7e534 100644--- a/workflow-recipes/src/config.ts+++ b/workflow-recipes/src/config.ts@@ -36,6 +36,14 @@ export interface OperatorConfig {*/sandboxUiNamespace: stringhostNamespace: string+ /**+ * Base URL of the evenfire registry. Deliberately the SAME variable control-api reads+ * (`CLERUM_REGISTRY_URL`), because both services must agree on which images are ours:+ * control-api provisions the platform pull credential for those images, WRC attaches it.+ * A divergence here means recipe pods silently get no credential while MCP servers do.+ * Empty (the default) disables platform pull-secret injection entirely.+ */+ registryUrl: stringselfName: stringinternalControlJwtWrcHmacSecret: stringenableCustomCoordinatorImage: boolean@@ -248,6 +256,7 @@ export function loadConfig(): OperatorConfig {sandboxNamespace: getEnv('CLERUM_SANDBOX_NAMESPACE', 'sandbox-recipes'),sandboxUiNamespace: getEnv('CLERUM_SANDBOX_UI_NAMESPACE', 'sandbox-ui'),hostNamespace: getEnv('CLERUM_HOST_NAMESPACE', 'mcp-host'),+ registryUrl: getEnv('CLERUM_REGISTRY_URL', ''),selfName: getEnv('CLERUM_OPERATOR_NAME', 'workflow-recipes'),internalControlJwtWrcHmacSecret: getEnv('INTERNAL_CONTROL_JWT_WRC_HMAC_SECRET', ''),enableCustomCoordinatorImage: getEnvBool('WRC_ENABLE_CUSTOM_COORDINATOR_IMAGE', false),diff --git a/workflow-recipes/src/reconciler/mcpDelegation.ts b/workflow-recipes/src/reconciler/mcpDelegation.tsindex 9a7e4b00a..06a65e8c5 100644--- a/workflow-recipes/src/reconciler/mcpDelegation.ts+++ b/workflow-recipes/src/reconciler/mcpDelegation.ts@@ -10,6 +10,11 @@* - stdio workloads: managed: true — HCC owns Deployment (stdio-bridge sidecar)*/import * as k8s from '@kubernetes/client-node'+import {+ EVENFIRE_REGISTRY_PULL_SECRET_NAME,+ isPlatformRegistryImage,+} from '@clerum/workflow-runtime-core'+import { loadConfig } from '../config'import { WorkflowRecipeCRD, WorkloadDef } from '../types'import { CRD_GROUP, CRD_VERSION } from './crdConstants'import { getErrorCode } from './k8sErrors'@@ -231,6 +236,16 @@ export function buildMcpServerManifest(const projectableImagePullSecrets = (workload.imagePullSecrets ?? []).filter(secretName =>transportSecretProjectable(secretAccess, secretName))+ // The PLATFORM pull credential is injected AFTER the ownership filter for any workload+ // whose image is hosted on our own registry (see resourceBuilder for the full rationale:+ // control-api provisions it, it is intentionally unlabeled to the #637 model, and making+ // it recipe-referencable would either deny it or expose it as an envSecret).+ if (+ isPlatformRegistryImage(workload.image, loadConfig().registryUrl) &&+ !projectableImagePullSecrets.includes(EVENFIRE_REGISTRY_PULL_SECRET_NAME)+ ) {+ projectableImagePullSecrets.push(EVENFIRE_REGISTRY_PULL_SECRET_NAME)+ }return {apiVersion: `${CRD_GROUP}/${CRD_VERSION}`,diff --git a/workflow-recipes/src/reconciler/platformPullSecret.test.ts b/workflow-recipes/src/reconciler/platformPullSecret.test.tsnew file mode 100644index 000000000..4b843d096--- /dev/null+++ b/workflow-recipes/src/reconciler/platformPullSecret.test.ts@@ -0,0 +1,127 @@+/**+ * Platform image-pull credential injection.+ *+ * control-api provisions `evenfire-registry-pull` and labels it+ * `clerum.io/managed-by=control-api` only — which is *unlabeled* to the Issue #637+ * ownership model. That is deliberate: it means a recipe can neither project it nor mount+ * it as an envSecret. WRC therefore INJECTS the reference itself, after the ownership+ * filter, for any workload whose image is hosted on our own registry.+ *+ * These tests pin both halves: the injection happens for our images, and the credential+ * stays unreachable to recipe-authored references.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { EVENFIRE_REGISTRY_PULL_SECRET_NAME } from '@clerum/workflow-runtime-core'+import type { DeploymentDef, WorkflowRecipeCRD, WorkloadDef } from '../types'+import { buildMcpServerManifest } from './mcpDelegation'+import { type SecretAccess, buildDeployment } from './resourceBuilder'++const REGISTRY_HOST = 'registry.evenfire.ai'+const PLATFORM_IMAGE = `${REGISTRY_HOST}/acme/plugin:1.0`+const FOREIGN_IMAGE = 'ghcr.io/acme/plugin:1.0'++const recipe = {+ apiVersion: 'clerum.io/v1alpha1',+ kind: 'WorkflowRecipe',+ metadata: { name: 'demo', namespace: 'sandbox-recipes' },+ spec: { workloads: [] },+} as unknown as WorkflowRecipeCRD++function workload(over: Partial<WorkloadDef> = {}): WorkloadDef {+ return { id: 'w1', type: 'deployment', image: PLATFORM_IMAGE, ...over } as WorkloadDef+}++/** Pull-secret names on a built Deployment's pod spec. */+function podPullNames(+ w: Partial<WorkloadDef> = {},+ access?: ReadonlyMap<string, SecretAccess>+): string[] {+ const dep = buildDeployment(workload(w) as DeploymentDef, recipe, 'minimal', access)+ return (dep.spec?.template.spec?.imagePullSecrets ?? []).map(s => s.name as string)+}++/** Pull-secret names on a built McpServer manifest. */+function mcpPullNames(+ w: Partial<WorkloadDef> = {},+ access?: ReadonlyMap<string, SecretAccess>+): string[] {+ const m = buildMcpServerManifest(+ workload({ transport: { type: 'stdio' } as never, ...w }),+ recipe,+ 'mcp-server',+ access+ ) as { spec?: { imagePullSecrets?: Array<{ name: string }> } } | null+ return (m?.spec?.imagePullSecrets ?? []).map(s => s.name)+}++let saved: string | undefined++beforeEach(() => {+ saved = process.env.CLERUM_REGISTRY_URL+ process.env.CLERUM_REGISTRY_URL = `https://${REGISTRY_HOST}`+})++afterEach(() => {+ if (saved === undefined) delete process.env.CLERUM_REGISTRY_URL+ else process.env.CLERUM_REGISTRY_URL = saved+})++describe('pod template — platform pull secret injection', () => {+ it('injects the credential for an image on our registry', () => {+ expect(podPullNames()).toEqual([EVENFIRE_REGISTRY_PULL_SECRET_NAME])+ })++ it('does not inject for a third-party image', () => {+ expect(podPullNames({ image: FOREIGN_IMAGE })).not.toContain(EVENFIRE_REGISTRY_PULL_SECRET_NAME)+ })++ it('does not inject when no registry is configured', () => {+ process.env.CLERUM_REGISTRY_URL = ''+ expect(podPullNames()).not.toContain(EVENFIRE_REGISTRY_PULL_SECRET_NAME)+ })++ it("preserves a recipe's own third-party pull secrets alongside the injected one", () => {+ expect(podPullNames({ imagePullSecrets: ['my-ghcr-creds'] })).toEqual([+ 'my-ghcr-creds',+ EVENFIRE_REGISTRY_PULL_SECRET_NAME,+ ])+ })++ it('injects even though the #637 filter would DENY a recipe-declared reference', () => {+ // The credential is unlabeled to the ownership model, so a recipe naming it is denied.+ // Injection happens after that filter, so the workload still gets a working pull —+ // and exactly once.+ const access = new Map<string, SecretAccess>([+ [EVENFIRE_REGISTRY_PULL_SECRET_NAME, { state: 'denied' }],+ ])+ expect(+ podPullNames({ imagePullSecrets: [EVENFIRE_REGISTRY_PULL_SECRET_NAME] }, access)+ ).toEqual([EVENFIRE_REGISTRY_PULL_SECRET_NAME])+ })++ it('drops a denied third-party secret while still injecting ours', () => {+ const access = new Map<string, SecretAccess>([['victim-pull', { state: 'denied' }]])+ expect(podPullNames({ imagePullSecrets: ['victim-pull'] }, access)).toEqual([+ EVENFIRE_REGISTRY_PULL_SECRET_NAME,+ ])+ })+})++describe('McpServer delegation — platform pull secret injection', () => {+ it('injects for a transport workload on our registry', () => {+ expect(mcpPullNames()).toEqual([EVENFIRE_REGISTRY_PULL_SECRET_NAME])+ })++ it('does not inject for a third-party transport image', () => {+ expect(mcpPullNames({ image: FOREIGN_IMAGE })).not.toContain(EVENFIRE_REGISTRY_PULL_SECRET_NAME)+ })++ it('injects past a denied recipe-declared reference', () => {+ const access = new Map<string, SecretAccess>([+ [EVENFIRE_REGISTRY_PULL_SECRET_NAME, { state: 'denied' }],+ ])+ expect(+ mcpPullNames({ imagePullSecrets: [EVENFIRE_REGISTRY_PULL_SECRET_NAME] }, access)+ ).toEqual([EVENFIRE_REGISTRY_PULL_SECRET_NAME])+ })+})diff --git a/workflow-recipes/src/reconciler/resourceBuilder.ts b/workflow-recipes/src/reconciler/resourceBuilder.tsindex 95ce79116..98bb5ace7 100644--- a/workflow-recipes/src/reconciler/resourceBuilder.ts+++ b/workflow-recipes/src/reconciler/resourceBuilder.ts@@ -1,5 +1,10 @@import * as k8s from '@kubernetes/client-node'import { createHash, randomBytes } from 'node:crypto'+import {+ EVENFIRE_REGISTRY_PULL_SECRET_NAME,+ isPlatformRegistryImage,+} from '@clerum/workflow-runtime-core'+import { loadConfig } from '../config'import {ConfigMapResourceDef,CronJobDef,@@ -879,8 +884,22 @@ function buildPodTemplate(const st = secretKeys?.get(name)?.statereturn st !== 'denied' && st !== 'error'})+ // The PLATFORM pull credential is injected here, AFTER the ownership filter, for any+ // workload whose image is hosted on our own registry. It is deliberately not something+ // a recipe declares: control-api provisions it and labels it `managed-by=control-api`+ // only, which is *unlabeled* to the #637 model — so a recipe naming it would be denied,+ // and making it `shared` would let any recipe mount it as an envSecret and read the+ // credential. Injecting it means the recipe never references it, so it is never+ // classified, and there is no path for a recipe to reach its contents.+ const pullSecretNames = [...allowedPullSecrets]+ if (+ isPlatformRegistryImage(workload.image, loadConfig().registryUrl) &&+ !pullSecretNames.includes(EVENFIRE_REGISTRY_PULL_SECRET_NAME)+ ) {+ pullSecretNames.push(EVENFIRE_REGISTRY_PULL_SECRET_NAME)+ }const imagePullSecrets =- allowedPullSecrets.length > 0 ? allowedPullSecrets.map(name => ({ name })) : undefined+ pullSecretNames.length > 0 ? pullSecretNames.map(name => ({ name })) : undefinedconst ownershipInitContainer = buildVolumeOwnershipInitContainer(workload)const pluginSdkEnv = buildPluginWorkloadSdkEnv(