Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): verify the operator provisioned the pull secret in managed mode
Jose Ramirez85222388049d
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 5931d6f98..e026ba3a4 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.407",+ "version": "0.1.408","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.407",+ "version": "0.1.408","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 3c16cbba4..1a8af1d1a 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.407",+ "version": "0.1.408","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/services/registryPullSecretReconcileCron.ts b/control-api/src/services/registryPullSecretReconcileCron.tsindex ca600041b..a937a6e25 100644--- a/control-api/src/services/registryPullSecretReconcileCron.ts+++ b/control-api/src/services/registryPullSecretReconcileCron.ts@@ -40,7 +40,16 @@ const log = rootLogger.child({ service: 'registry_pull_secret_reconcile' })*/export async function reconcileRegistryPullSecret(gateway: K8sGateway): Promise<boolean> {try {- const results = await ensureRegistryPullSecrets(gateway, platformWorkloadNamespaces())+ // `required: []` — this loop needs no namespace on its own behalf. Unlike an install it+ // is not about to persist a CRD referencing one, so a namespace it cannot fill (or, on a+ // managed cluster, one the operator has not populated) is not ITS failure to report; the+ // install that actually lands there raises it, with the namespaces that caller needs.+ // Without this the loop would report a failed pass on every tick of a managed cluster,+ // where control-api legitimately has nothing to do. Conditions worth an operator's+ // attention are already logged by the service itself, on every pass.+ const results = await ensureRegistryPullSecrets(gateway, platformWorkloadNamespaces(), {+ required: [],+ })const changed = [...results.entries()].filter(([, r]) => r === 'created' || r === 'repaired')if (changed.length > 0) {log.info(diff --git a/control-api/src/services/registryPullSecretService.ts b/control-api/src/services/registryPullSecretService.tsindex b34017f89..f5bb9d2fc 100644--- a/control-api/src/services/registryPullSecretService.ts+++ b/control-api/src/services/registryPullSecretService.ts@@ -20,10 +20,25 @@* split across all three platform workload namespaces by kind (transport → mcp-server,* spec.ui.workloadRef → sandbox-ui, everything else → sandbox-recipes). So the Secret must* exist in ALL of them — `platformWorkloadNamespaces()`, the one allowlist writes are- * confined to. On a MANAGED cluster control-api writes none of them (provisioning- * short-circuits to 'skipped'), which makes populating all three the external operator's- * job: a managed cluster that provisions only mcp-server leaves recipe pods in- * ImagePullBackOff with nothing in the API trail to explain it.+ * confined to.+ *+ * MANAGED clusters: VERIFY, never write. control-api provisions nothing there — the+ * platform operator owns the Secret — but WRC still injects the reference, so a namespace+ * the operator has not populated yields a workload that can only ImagePullBackOff, behind+ * a 201. Managed mode therefore runs a read-only presence check over the platform+ * namespaces (`verifyOperatorProvisioned`) and fails the caller BEFORE the CRD is+ * persisted when one it needs has no usable copy (`operator_secret_missing`). This asserts+ * nothing about what any operator does; it only refuses to persist a reference that cannot+ * resolve on THIS cluster right now. The check is scoped by `required` for the same reason+ * everything else here is: today's managed operator populates mcp-server, so McpServer+ * installs must keep working while recipe installs — which land in all three — do not+ * silently half-work.+ *+ * A recipe caller passes the whole platform set and requires all of it, which is stricter+ * than that recipe may strictly need: control-api does not model WRC's per-workload+ * kind→namespace split, so it cannot tell which of the three a given recipe will land in.+ * Requiring all three is the conservative side of that gap — it refuses an install that+ * MIGHT have pulled rather than persisting one that might not.** Two invariants make this safe to run repeatedly:* 1. NEVER write a Secret we do not own. An unlabeled Secret belongs to an external@@ -230,11 +245,19 @@ const inflight = new Map<string, Promise<EnsurePass>>()* the pass knows. A blocked namespace has NO entry in `results` — nothing* happened to it, and every caller that could observe the gap fails on it* first.+ * `missing` — MANAGED mode only: a platform namespace with no usable operator-provisioned+ * copy (`operator_secret_missing`). Fragments ("it does not exist", "it exists+ * but …"), because the caller-facing sentence names every missing namespace at+ * once and only `ensureRegistryPullSecrets` knows which ones the caller needs.+ *+ * The three are mutually exclusive by mode: `unusable`/`blocked` come from the+ * provisioning pass, `missing` from the verification pass, and a pass is one or the other.*/type EnsurePass = {results: Map<string, EnsurePullSecretResult>unusable: Map<string, string>blocked: Map<string, string>+ missing: Map<string, string>}/** The platform workload namespaces a pull credential may legitimately be written into. */@@ -261,7 +284,9 @@ export function platformWorkloadNamespaces(): string[] {* 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.+ * reference fails the install loudly instead of persisting an unresolvable one. In managed+ * mode `'skipped'` is now a VERIFIED answer rather than an assumed one: the operator's+ * copies are read first, and a required namespace without a usable one throws too.*/export async function ensureRegistryPullSecrets(gateway: K8sGateway,@@ -275,7 +300,7 @@ export async function ensureRegistryPullSecrets(run = ensureInner(gateway, targets).finally(() => inflight.delete(dedupeKey))inflight.set(dedupeKey, run)}- const { results, unusable, blocked } = await run+ const { results, unusable, blocked, missing } = await run// A recorded failure is fatal only to a caller that needs THAT namespace. A pass covers// the whole platform set (for the mint-once collapse), so an MCP install must not be@@ -284,6 +309,22 @@ export async function ensureRegistryPullSecrets(// so a caller that asks for a set is asserting it needs all of it.const required = opts.required ?? targets+ // MANAGED mode: the operator owns the Secret, so the only thing we can do for a caller+ // is refuse to persist a reference that cannot resolve. Report every missing namespace+ // at once — an operator fixing one at a time would otherwise walk the whole set through+ // three failed installs. (Order against the two loops below is not load-bearing: this+ // map and those are populated by different passes; see EnsurePass.)+ const absent = required.filter(ns => missing.has(ns))+ if (absent.length > 0) {+ const host = registryHostFromUrl(config.registryUrl)+ const detail = absent.map(ns => `"${ns}" (${missing.get(ns)})`).join(', ')+ throw new PullSecretProvisionError(+ `the ${EVENFIRE_REGISTRY_PULL_SECRET_NAME} Secret cannot serve an image pull in ${detail}. This cluster runs in "${config.registryConnectionMode}" registry mode, where the platform operator — not control-api — owns that Secret, so control-api will not create it here. Ask the operator to provision ${EVENFIRE_REGISTRY_PULL_SECRET_NAME} (type ${DOCKERCONFIG_TYPE}, with a ${DOCKERCONFIG_KEY} entry for "${host}") in the namespace(s) above, then retry. Proceeding would persist a workload referencing a credential no pod can resolve.`,+ 'operator_secret_missing',+ 409+ )+ }+// `unusable` first, across the WHOLE required set, before any `blocked`. Both can apply// at once (a malformed foreign copy in one namespace, a well-shaped one blocking the mint// in another), and `unusable` names a concrete defect in a specific Secret that has to be@@ -417,13 +458,20 @@ async function ensureInner(gateway: K8sGateway, targets: string[]): Promise<Ensuconst out = new Map<string, EnsurePullSecretResult>()const unusable = new Map<string, string>()const blocked = new Map<string, string>()+ const missing = new Map<string, string>()// ── Legitimate no-ops ─────────────────────────────────────────────────────- // Managed clusters: the operator owns this Secret; never contend with it.+ // No registry host: nothing references it, and there is no host to check a blob+ // against either — the pull secret is not in play at all.const host = registryHostFromUrl(config.registryUrl)- if (config.registryConnectionMode !== 'self-hosted' || !host) {+ if (!host) {for (const ns of targets) out.set(ns, 'skipped')- return { results: out, unusable, blocked }+ return { results: out, unusable, blocked, missing }+ }+ // Managed clusters: the operator owns this Secret; never contend with it — but do check+ // that what the caller is about to reference is actually there.+ if (config.registryConnectionMode !== 'self-hosted') {+ return verifyOperatorProvisioned(gateway, targets, host)}// ── Hard preconditions: from here on we MUST provision or fail loudly ─────@@ -461,10 +509,61 @@ 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)+ ensureLocked(gateway, targets, host, orgName as string, out, unusable, blocked, missing))}+/**+ * MANAGED clusters: read-only verification that the operator's Secret is where the caller+ * is about to point a workload at it. Mints nothing, writes nothing, takes no lock, and+ * touches neither Postgres nor the registry — invariant 1 admits no exception here, and+ * "the operator owns it" is precisely why we may only look.+ *+ * Reuses `foreignUsabilityProblem`, the same shape-only test applied to externally-owned+ * Secrets on the self-hosted path: correct type, and a dockerconfig entry for our host. A+ * second notion of "usable" would drift from the one the kubelet actually acts on. Ownership+ * is deliberately NOT consulted — whoever wrote it, all that matters is whether it can serve+ * the pull — and neither is liveness of the sealed key, which would cost a registry+ * round-trip per install.+ *+ * Scoped to `platformWorkloadNamespaces()`: that set is the operator contract. A target+ * outside it stays `'skipped'` rather than becoming a failure, because control-api has no+ * claim about namespaces no operator ever agreed to populate, and failing there would break+ * managed installs that work today.+ */+async function verifyOperatorProvisioned(+ gateway: K8sGateway,+ targets: string[],+ host: string+): Promise<EnsurePass> {+ const out = new Map<string, EnsurePullSecretResult>()+ const missing = new Map<string, string>()+ const platform = new Set(platformWorkloadNamespaces())+ for (const ns of targets) {+ // Provisioning is genuinely not our job on this cluster, so the result stays 'skipped'+ // whichever way the check goes; the verdict travels in `missing`.+ out.set(ns, 'skipped')+ if (!platform.has(ns)) continue+ const current = await readCurrent(gateway, ns)+ if (!current) {+ missing.set(ns, 'it does not exist')+ continue+ }+ const problem = foreignUsabilityProblem(current, host)+ if (problem) missing.set(ns, `it exists but ${problem}`)+ }+ // Deliberately not logged at warn: this runs on every reconcile tick as well as every+ // install, and on a managed cluster an unpopulated namespace is a normal state until+ // something actually asks for it. The caller that asks gets the loud failure.+ if (missing.size > 0) {+ logger.debug(+ { namespaces: [...missing.keys()] },+ 'managed cluster: no usable operator-provisioned evenfire-registry-pull Secret in these namespaces'+ )+ }+ return { results: out, unusable: new Map(), blocked: new Map(), missing }+}+/*** 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.@@ -476,7 +575,10 @@ async function ensureLocked(orgName: string,out: Map<string, EnsurePullSecretResult>,unusable: Map<string, string>,- blocked: Map<string, string>+ blocked: Map<string, string>,+ // Always empty on this path: a namespace with nothing in it is one we PROVISION, not one+ // we report as missing. It rides along so both passes return the same shape.+ missing: Map<string, string>): Promise<EnsurePass> {// ── Read + classify every target BEFORE minting anything ──────────────────const states = new Map<string, TargetState>()@@ -510,7 +612,7 @@ async function ensureLocked(}out.set(ns, 'exists-foreign')}- if (ours.length === 0) return { results: out, unusable, blocked }+ if (ours.length === 0) return { results: out, unusable, blocked, missing }// 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@@ -524,7 +626,7 @@ async function ensureLocked(if (!needsMint) {for (const ns of ours) out.set(ns, 'exists-ours')- return { results: out, unusable, blocked }+ return { results: out, unusable, blocked, missing }}// ── All-or-nothing: a USABLE foreign copy anywhere forbids the mint ───────@@ -569,7 +671,7 @@ async function ensureLocked({ external: blocking, unfillable },'usable externally-owned evenfire-registry-pull Secret present; refusing to mint (the mint is org-wide and rotate-on-call, so it would revoke the external key) — installs that need the unfillable namespaces will fail')- return { results: out, unusable, blocked }+ return { results: out, unusable, blocked, missing }}if (diverged) {@@ -610,7 +712,7 @@ async function ensureLocked(fingerprint: cred.fingerprint,})logger.info({ namespaces: ours, orgName }, 'registry pull secret provisioned')- return { results: out, unusable, blocked }+ return { results: out, unusable, blocked, missing }}/** Write `cred` into one namespace, choosing create/update/recreate from its prior state. */diff --git a/control-api/test/registryPullSecretReconcileCron.test.ts b/control-api/test/registryPullSecretReconcileCron.test.tsindex 39c49273e..491243cee 100644--- a/control-api/test/registryPullSecretReconcileCron.test.ts+++ b/control-api/test/registryPullSecretReconcileCron.test.ts@@ -42,11 +42,15 @@ describe('reconcileRegistryPullSecret', () => {]))await expect(reconcileRegistryPullSecret(gateway)).resolves.toBe(true)- expect(ensureRegistryPullSecrets).toHaveBeenCalledWith(gateway, [- 'mcp-server',- 'sandbox-recipes',- 'sandbox-ui',- ])+ // `required: []` is load-bearing, not decoration: this loop is not a caller about to+ // persist a CRD, so it must never fail on a namespace nobody has asked for. It is what+ // keeps a managed cluster — where control-api provisions nothing and the operator may+ // not have populated every namespace — from reporting a failed pass on every tick.+ expect(ensureRegistryPullSecrets).toHaveBeenCalledWith(+ gateway,+ ['mcp-server', 'sandbox-recipes', 'sandbox-ui'],+ { required: [] }+ )})it('does NOT throw when the cluster is not connected yet — it retries next tick', async () => {diff --git a/control-api/test/registryPullSecretService.test.ts b/control-api/test/registryPullSecretService.test.tsindex 38b656811..0dda47252 100644--- a/control-api/test/registryPullSecretService.test.ts+++ b/control-api/test/registryPullSecretService.test.ts@@ -5,6 +5,7 @@ import type { K8sGateway } from '../src/k8s.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 { reconcileRegistryPullSecret } from '../src/services/registryPullSecretReconcileCron.js'import {PullSecretProvisionError,ensureRegistryPullSecret,@@ -132,10 +133,21 @@ afterEach(() => {config.registryUrl = savedUrl})+/** What a managed operator's copy looks like: correctly shaped, and NOT labelled as ours. */+function seedOperator(mock: MockGateway, namespaces: string[], key = 'operator-key'): void {+ for (const ns of namespaces) {+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, key) },+ })+ }+}+describe('ensureRegistryPullSecret — legitimate no-ops', () => {it('skips (no mint) in managed mode — the operator owns the Secret', async () => {config.registryConnectionMode = 'managed'- const { gateway } = gw()+ const { gateway, mock } = gw()+ seedOperator(mock, [NS])await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('skipped')expect(mintOrgPullCredential).not.toHaveBeenCalled()})@@ -148,6 +160,125 @@ describe('ensureRegistryPullSecret — legitimate no-ops', () => {})})+/**+ * Managed clusters: VERIFY what the operator provisioned, write nothing.+ *+ * Skipping the write is right — the operator owns this Secret — but it is not the same as+ * having nothing to say. WRC still injects the `imagePullSecrets` reference into every+ * workload whose image is ours, and recipe workloads land in all three platform+ * namespaces, so an install into a namespace the operator has not populated persists a CRD+ * that can only ImagePullBackOff. Presence is therefore checked read-only, and a caller+ * that needs a namespace without a usable copy is failed BEFORE the CRD is written.+ */+describe('ensureRegistryPullSecrets — managed mode verifies the operator provisioned it', () => {+ beforeEach(() => {+ config.registryConnectionMode = 'managed'+ })++ it('passes without minting or writing when every required namespace is populated', async () => {+ const { gateway, mock } = gw()+ seedOperator(mock, ALL)+ const getSpy = vi.spyOn(mock, 'getSecret')+ const createSpy = vi.spyOn(mock, 'createSecret')+ const updateSpy = vi.spyOn(mock, 'updateSecret')+ const deleteSpy = vi.spyOn(mock, 'deleteSecret')++ const res = await ensureRegistryPullSecrets(gateway, ALL)++ // 'skipped' still means "provisioning was not our job", which is true on a managed+ // cluster — but it is now an answer we checked rather than assumed.+ expect([...res.values()]).toEqual(['skipped', 'skipped', 'skipped'])+ for (const ns of ALL) {+ expect(getSpy).toHaveBeenCalledWith(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns)+ }+ // Invariant 1 is absolute here: managed mode is read-only, all the way down.+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ expect(createSpy).not.toHaveBeenCalled()+ expect(updateSpy).not.toHaveBeenCalled()+ expect(deleteSpy).not.toHaveBeenCalled()+ expect(dbCalls.queries).toHaveLength(0)+ })++ // The shape of a real managed cluster today: MCC provisions `mcp-server`, so transport+ // installs pull fine, and the two sandbox namespaces recipes land in are empty. That is+ // exactly the gap that used to surface only as an ImagePullBackOff.+ it('fails a recipe install for the namespaces the operator never populated', async () => {+ const { gateway, mock } = gw()+ seedOperator(mock, [NS])++ const err = await ensureRegistryPullSecrets(gateway, ALL).catch((e: Error) => e)++ expect(err).toBeInstanceOf(PullSecretProvisionError)+ expect(err).toMatchObject({ reason: 'operator_secret_missing', status: 409 })+ const message = (err as Error).message+ // Actionable means naming the namespaces that are actually missing — and only those.+ expect(message).toContain(`"${SANDBOX}"`)+ expect(message).toContain(`"${UI}"`)+ expect(message).not.toContain(`"${NS}"`)+ expect(message).toContain(EVENFIRE_REGISTRY_PULL_SECRET_NAME)+ expect(message).toMatch(/operator/i) // whose job it is on this cluster+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('fails when the operator copy exists but is the wrong type (kubelet ignores it)', async () => {+ const { gateway, mock } = gw()+ seedOperator(mock, [SANDBOX, UI])+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, { type: 'Opaque', data: {} })++ await expect(ensureRegistryPullSecrets(gateway, ALL)).rejects.toMatchObject({+ reason: 'operator_secret_missing',+ status: 409,+ })+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('fails when the operator copy is keyed on a different registry host', async () => {+ const { gateway, mock } = gw()+ seedOperator(mock, [SANDBOX, UI])+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg('old-registry.example.com', 'operator-key') },+ })++ const err = await ensureRegistryPullSecrets(gateway, ALL).catch((e: Error) => e)+ expect(err).toMatchObject({ reason: 'operator_secret_missing', status: 409 })+ // The kubelet never selects a blob with no entry for our host, so say so rather than+ // reporting a Secret that is plainly sitting right there as "missing".+ expect((err as Error).message).toContain(HOST)+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ // `required` scoping is what keeps this from being the blanket reject it must not be:+ // MCC does provision `mcp-server`, so an McpServer install lands somewhere that works+ // and must not be failed by the sandbox namespaces it never touches.+ it('does not fail an McpServer install over a sandbox namespace it never lands in', async () => {+ const { gateway, mock } = gw()+ seedOperator(mock, [NS])+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('skipped')+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('does fail an McpServer install when ITS OWN namespace is the empty one', async () => {+ const { gateway, mock } = gw()+ seedOperator(mock, [SANDBOX, UI])+ await expect(ensureRegistryPullSecret(gateway, NS)).rejects.toMatchObject({+ reason: 'operator_secret_missing',+ status: 409,+ })+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ // The verification covers the operator's contract, which is defined over the platform+ // workload namespaces. A namespace outside that set is not part of it — and failing on+ // one would break a managed install that works today, which is the opposite of the point.+ it('says nothing about a namespace outside the platform set', async () => {+ const { gateway, mock } = gw()+ seedOperator(mock, ALL)+ const res = await ensureRegistryPullSecrets(gateway, [...ALL, 'channels'])+ expect(res.get('channels')).toBe('skipped')+ })+})+describe('ensureRegistryPullSecret — fails loudly instead of silently skipping', () => {it('throws (not skips) when the registry connection is inactive', async () => {vi.mocked(isRegistryAuthActive).mockResolvedValue(false)@@ -727,9 +858,31 @@ describe('ensureRegistryPullSecrets — cross-process serialization', () => {it('does not reach the lock when the pass is a legitimate no-op', async () => {config.registryConnectionMode = 'managed'- const { gateway } = gw()+ const { gateway, mock } = gw()+ seedOperator(mock, ALL)await ensureRegistryPullSecrets(gateway, ALL)- // Managed clusters must not touch Postgres (or anything else) on this path.+ // Managed clusters must not touch Postgres on this path: the lock exists to serialize+ // a mint, and the managed pass only reads.expect(dbCalls.queries).toHaveLength(0)})})++/**+ * The reconcile loop against the REAL service — its own suite mocks this module out, so+ * this is the only place the managed interaction can be observed.+ *+ * A managed cluster genuinely has nothing for control-api to do here, and the loop runs on+ * a timer: it must stay a quiet no-op rather than reporting a failed pass every tick just+ * because the operator has not populated a namespace no install has asked for yet.+ */+describe('reconcileRegistryPullSecret — managed cluster', () => {+ it('stays a quiet no-op when the operator has provisioned nothing', async () => {+ config.registryConnectionMode = 'managed'+ const { gateway, mock } = gw()+ const createSpy = vi.spyOn(mock, 'createSecret')++ await expect(reconcileRegistryPullSecret(gateway)).resolves.toBe(true)+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ expect(createSpy).not.toHaveBeenCalled()+ })+})diff --git a/control-api/test/routes.adminRecipes.pullSecret.test.ts b/control-api/test/routes.adminRecipes.pullSecret.test.tsindex 363797d2f..cdda4e7cf 100644--- a/control-api/test/routes.adminRecipes.pullSecret.test.ts+++ b/control-api/test/routes.adminRecipes.pullSecret.test.ts@@ -248,3 +248,38 @@ describe('PUT /admin/recipes/:name — pull-secret provisioning (self-hosted)',expect(stored.spec.workloads[0].image).toBe('ghcr.io/acme/plugin:1.0')})})++/**+ * Managed mode reaches the generic recipe routes too. A hand-authored recipe is+ * indistinguishable at reconcile time from an installed one — WRC injects the reference+ * from the image host either way — so the same verification has to gate this path, or the+ * narrowing is only as good as the route the author happened to use.+ */+describe('POST /admin/recipes — managed mode verifies instead of provisioning', () => {+ beforeEach(() => {+ config.registryConnectionMode = 'managed'+ })++ it('refuses the recipe and persists nothing when the operator Secret is absent', async () => {+ const gateway = new MockGateway(MCP_NS)+ const createSecret = vi.spyOn(gateway, 'createSecret')++ 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: 'operator_secret_missing',+ })+ await expect(gateway.getResource('workflowrecipes', 'plat', SANDBOX_NS)).rejects.toBeTruthy()+ // Managed mode is read-only: no mint, and no Secret written on the way to the refusal.+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ expect(createSecret).not.toHaveBeenCalled()+ })++ it('accepts a recipe with no platform-registry image, unchecked', async () => {+ const gateway = new MockGateway(MCP_NS)+ await request(makeApp(gateway)).post('/admin/recipes').send(foreignRecipe('ext')).expect(201)+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })+})diff --git a/control-api/test/routes.registryInstall.pullSecret.test.ts b/control-api/test/routes.registryInstall.pullSecret.test.tsindex 538287b73..ba04cd36e 100644--- a/control-api/test/routes.registryInstall.pullSecret.test.ts+++ b/control-api/test/routes.registryInstall.pullSecret.test.ts@@ -1,15 +1,17 @@/**- * Route-level coverage for image-pull-secret self-provisioning on the install path.+ * Route-level coverage for the image-pull-secret hook on the install path, in BOTH+ * connection modes — the hook behaves differently in each, and the difference is the point.*- * The main `routes.registryInstall` suite runs in the default `managed` connection mode,- * where `ensureRegistryPullSecret` short-circuits to `'skipped'` before doing anything —- * so none of it can catch a regression in the wiring. These tests force `self-hosted`,- * which is the only mode where the hook actually runs, and pin the properties the wiring- * is supposed to guarantee:+ * self-hosted: control-api provisions the Secret itself, so these pin* - it provisions even when the plugin needs NO credentials (outside `credRequired`)* - it provisions BEFORE the McpServer CRD that references the Secret* - a provisioning failure fails the install loudly and persists NOTHING* - it does not run at all for images that are not evenfire-hosted+ *+ * managed: control-api provisions nothing — the operator owns the Secret — but WRC injects+ * the reference regardless, so the install VERIFIES the operator's copy is present and+ * usable and refuses before persisting when it is not. Same guarantee, opposite mechanism:+ * no CRD is written that references a credential no pod can resolve.*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import express from 'express'@@ -118,6 +120,55 @@ function installBody() {}}+/** A recipe entry whose single workload runs `image`. */+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' }+}++const PLATFORM_NAMESPACES = ['mcp-server', 'sandbox-recipes', 'sandbox-ui']++/** Seed the Secret a managed cluster's operator is contracted to provision. */+function seedOperatorSecret(gw: MockGateway, namespaces: string[]): void {+ const auth = Buffer.from('_:operator-key').toString('base64')+ const blob = Buffer.from(+ JSON.stringify({+ auths: { [REGISTRY_HOST]: { username: '_', password: 'operator-key', auth } },+ })+ ).toString('base64')+ for (const ns of namespaces) {+ gw.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { '.dockerconfigjson': blob },+ })+ }+}+let savedMode: typeof config.registryConnectionModelet savedUrl: string@@ -227,38 +278,6 @@ describe('POST /admin/registry/install — pull-secret provisioning (self-hosted})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@@ -336,8 +355,6 @@ describe('POST /admin/registry/install-recipe — pull-secret provisioning (self})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 {@@ -429,3 +446,105 @@ describe('POST /admin/registry/upgrade-recipe — pull-secret provisioning (selfexpect(updateSpy).not.toHaveBeenCalled()})})++/**+ * MANAGED mode: control-api provisions nothing, so the routes verify instead.+ *+ * The reference is injected either way — by WRC, from the image host — so a managed+ * cluster whose operator has not populated a namespace produces a CRD that can only+ * ImagePullBackOff, with a 201 in the API trail. These pin the narrowing: the install is+ * refused BEFORE anything is persisted, and only for the namespaces it actually lands in.+ */+describe('managed mode — installs verify the operator-owned Secret, and never mint', () => {+ beforeEach(() => {+ ;(config as { registryConnectionMode: string }).registryConnectionMode = 'managed'+ })++ it('installs an McpServer when the operator populated the plugin namespace', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(evenfireEntry() as never)+ const { app, gw } = makeInstallApp()+ // MCC provisions mcp-server today, which is why this path must keep working.+ seedOperatorSecret(gw, [NS])+ const createSecret = vi.spyOn(gw, 'createSecret')++ await request(app).post('/admin/registry/install').send(installBody()).expect(201)++ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ expect(createSecret).not.toHaveBeenCalled()+ const mcp = (await gw.getResource('mcpservers', 'forecast', NS)) as {+ spec: { imagePullSecrets?: Array<{ name: string }> }+ }+ expect(mcp.spec.imagePullSecrets).toEqual([{ name: EVENFIRE_REGISTRY_PULL_SECRET_NAME }])+ })++ it('refuses the McpServer install, persisting nothing, when the Secret is absent', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(evenfireEntry() as never)+ const { app, gw } = makeInstallApp()++ const res = await request(app).post('/admin/registry/install').send(installBody())++ expect(res.status).toBe(409)+ expect(res.body).toMatchObject({+ error: 'registry_pull_secret_provision_failed',+ reason: 'operator_secret_missing',+ })+ // The whole point: fail before persisting, not at pull time.+ await expect(gw.getResource('mcpservers', 'forecast', NS)).rejects.toBeTruthy()+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('installs a recipe when the operator populated every platform namespace', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(+ recipeEntry(`${REGISTRY_HOST}/acme/plugin:1.0`) as never+ )+ const { app, gw } = makeInstallApp()+ seedOperatorSecret(gw, PLATFORM_NAMESPACES)+ const createSecret = vi.spyOn(gw, 'createSecret')++ await request(app).post('/admin/registry/install-recipe').send(recipeBody()).expect(201)++ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ expect(createSecret).not.toHaveBeenCalled()+ })++ it('refuses the recipe install when only the mcp-server namespace is populated', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(+ recipeEntry(`${REGISTRY_HOST}/acme/plugin:1.0`) as never+ )+ const { app, gw } = makeInstallApp()+ // The real managed shape: transport workloads pull, recipe workloads do not.+ seedOperatorSecret(gw, [NS])++ const res = await request(app).post('/admin/registry/install-recipe').send(recipeBody())++ expect(res.status).toBe(409)+ expect(res.body).toMatchObject({+ error: 'registry_pull_secret_provision_failed',+ reason: 'operator_secret_missing',+ })+ expect(res.body.detail).toContain('sandbox-recipes')+ const persisted = (await gw.listResource('workflowrecipes', '*')) as Array<{+ metadata: { name: string }+ }>+ expect(persisted.map(r => r.metadata.name)).toEqual([])+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('leaves an install with a NON-platform image untouched', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(+ evenfireEntry({+ mcp_server_meta: { imageRef: 'ghcr.io/acme/forecast:1.2.3', port: 3000 },+ }) as never+ )+ const { app, gw } = makeInstallApp()+ // Nothing seeded anywhere: a public image needs no pull credential, so the check must+ // not run at all. Narrowing that fails installs it has no claim on is not a narrowing.+ const getSecret = vi.spyOn(gw, 'getSecret')++ await request(app).post('/admin/registry/install').send(installBody()).expect(201)++ expect(getSecret.mock.calls.some(([name]) => name === EVENFIRE_REGISTRY_PULL_SECRET_NAME)).toBe(+ false+ )+ })+})diff --git a/control-api/test/routes.registryInstall.test.ts b/control-api/test/routes.registryInstall.test.tsindex ed9baae0c..1ddf306a2 100644--- a/control-api/test/routes.registryInstall.test.ts+++ b/control-api/test/routes.registryInstall.test.ts@@ -68,6 +68,27 @@ function makeApp(gateway?: MockGateway) {return app}+/**+ * Seed the `evenfire-registry-pull` Secret an operator provisions on a managed cluster.+ *+ * This file runs in the default `managed` connection mode, where control-api writes that+ * Secret for nobody — but a platform-registry image still makes the install VERIFY that+ * the operator's copy is present and usable, and refuse before persisting when it is not+ * (registryPullSecretService). Without this seed those installs 409, and the suites below+ * stop being about what they are about: which images get an imagePullSecrets reference.+ */+function seedOperatorPullSecret(gw: MockGateway, host: string, namespace = 'mcp-server'): void {+ const auth = Buffer.from('_:operator-key').toString('base64')+ gw.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, namespace, {+ type: 'kubernetes.io/dockerconfigjson',+ data: {+ '.dockerconfigjson': Buffer.from(+ JSON.stringify({ auths: { [host]: { username: '_', password: 'operator-key', auth } } })+ ).toString('base64'),+ },+ })+}+function internalSiblingRecipeYaml(dns = 'db.sandbox-recipes.svc.cluster.local'): string {return JSON.stringify({spec: {@@ -1436,6 +1457,7 @@ describe('POST /admin/registry/install — evenfire imagePullSecrets attach', ()metadata: { name: 'default-context' },spec: { contextId: 'default-context', mcpServers: [] },})+ seedOperatorPullSecret(gw, 'example.com')return { app: makeApp(gw), gw }}@@ -1560,6 +1582,7 @@ describe('POST /admin/registry/install — evenfire imageRef identity (2.5)', ()metadata: { name: 'default-context' },spec: { contextId: 'default-context', mcpServers: [] },})+ seedOperatorPullSecret(gw, 'example.com')return { app: makeApp(gw), gw }}@@ -3199,6 +3222,7 @@ describe('POST /admin/registry/upgrade — evenfire imagePullSecrets recompute',...existingSpecPatch,},})+ seedOperatorPullSecret(gw, 'example.com')return { app: makeApp(gw), gw }}@@ -3319,6 +3343,7 @@ describe('POST /admin/registry/upgrade — evenfire imageRef identity (2.5)', ()},},})+ seedOperatorPullSecret(gw, 'example.com')return { app: makeApp(gw), gw }}