Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): never rotate the org key while a usable foreign Secret exists
Jose Ramirez1a8e8f6fd4d9
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 9ae2667b7..df73d708a 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.404",+ "version": "0.1.405","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.404",+ "version": "0.1.405","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 60dfd0c43..d20bbae0a 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.404",+ "version": "0.1.405","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/registryPullSecretService.ts b/control-api/src/services/registryPullSecretService.tsindex 53b7746d9..449fafb2d 100644--- a/control-api/src/services/registryPullSecretService.ts+++ b/control-api/src/services/registryPullSecretService.ts@@ -34,6 +34,22 @@* registry's pull-credential mint is rotate-on-call — it revokes the org's previous* key — so a mint that is followed by a failed write strands every other namespace's* Secret on a revoked credential.+ *+ * Those two combine into an ALL-OR-NOTHING rule on external pre-provisioning, because the+ * credential is per-ORG while the Secret is per-NAMESPACE. Minting for a namespace we own+ * also revokes the key sealed inside a foreign Secret we deliberately refused to touch —+ * silently: the foreign bytes never change, foreign copies are excluded from the+ * fingerprint set so the divergence check can never see it, and invariant 1 forbids+ * repairing it. So if ANY target in a pass holds a USABLE foreign Secret, the org's pull+ * credential is externally managed and this service mints NOTHING, in any namespace. An+ * operator therefore provisions ALL of `platformWorkloadNamespaces()` or none of them; a+ * half-external cluster fails the installs that need a namespace we cannot fill+ * (`foreign_secret_would_be_revoked`) instead of quietly breaking the ones that work.+ *+ * "Usable" is the gate, not "foreign": an unusable foreign Secret (wrong type, or keyed on+ * another host) is not serving any pull for this registry, so rotating the org key cannot+ * break a working path through it and it does not block the mint. It is still fatal to a+ * caller that references its namespace — via `foreign_secret_unusable`, per invariant 1.*/import { createHash } from 'node:crypto'import { config } from '../config.js'@@ -192,18 +208,32 @@ async function mintCredential(orgName: string, host: string): Promise<MintedCred// would require an org-scoped distributed lock around the mint — control-api has Postgres// available for that. Not implemented: single-replica is the deployed shape today.//-// The cached value carries the unusable-foreign REASONS alongside the results rather than-// throwing for them inside the pass. Whether an unusable foreign Secret is fatal depends on-// which namespaces the CALLER needs, and the dedupe key deliberately does not encode that —+// The cached value carries the per-namespace FAILURE REASONS alongside the results rather+// than throwing for them inside the pass. Whether an unusable foreign Secret — or a+// namespace we could not fill without revoking a foreign key — is fatal depends on which+// namespaces the CALLER needs, and the dedupe key deliberately does not encode that:// folding the required set into the key would stop an MCP install and a recipe install from// collapsing, which is the very race this map exists to prevent. So the pass records, and// each caller applies its own policy on the shared result.const inflight = new Map<string, Promise<EnsurePass>>()-/** One pass's outcome: per-namespace results, plus why any foreign Secret is unusable. */+/**+ * One pass's outcome: per-namespace results, plus the two per-namespace reasons a caller+ * may have to fail on.+ *+ * `unusable` — a FOREIGN Secret the kubelet cannot use (`foreign_secret_unusable`).+ * `blocked` — a namespace we OWN that needed a mint we refused to perform, because some+ * other target in the pass holds a USABLE foreign Secret and the mint would+ * revoke its key (`foreign_secret_would_be_revoked`). Full caller-facing+ * sentences, not fragments: the remedy names the foreign namespace, which only+ * 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.+ */type EnsurePass = {results: Map<string, EnsurePullSecretResult>unusable: Map<string, string>+ blocked: Map<string, string>}/** The platform workload namespaces a pull credential may legitimately be written into. */@@ -222,7 +252,10 @@ export function platformWorkloadNamespaces(): string[] {* 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.+ * Post-condition: every non-foreign target holds the same, current credential — UNLESS some+ * target holds a USABLE foreign Secret, in which case the pass mints and writes nothing at+ * all (see the all-or-nothing rule in the file header) and every owned target that needed a+ * mint is recorded as blocked instead.** Returns `'skipped'` for all targets ONLY when provisioning is legitimately not our job* (managed mode, or no registry configured). Every other "cannot provision" condition@@ -241,14 +274,21 @@ export async function ensureRegistryPullSecrets(run = ensureInner(gateway, targets).finally(() => inflight.delete(dedupeKey))inflight.set(dedupeKey, run)}- const { results, unusable } = await run+ const { results, unusable, blocked } = await run- // An unusable foreign Secret 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 failed by a squatter in a sandbox namespace it never references — while a recipe+ // 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+ // failed by a squatter in a sandbox namespace it never references — while a recipe// install, which does land there, still fails loudly. `required` defaults to every target,// so a caller that asks for a set is asserting it needs all of it.- for (const ns of opts.required ?? targets) {+ const required = opts.required ?? targets++ // `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+ // fixed or removed either way — deleting the copy that blocked the mint would just+ // surface it on the next install. Leading with the defect is the shorter path out.+ for (const ns of required) {const why = unusable.get(ns)if (why) {throw new PullSecretProvisionError(@@ -258,6 +298,10 @@ export async function ensureRegistryPullSecrets()}}+ for (const ns of required) {+ const why = blocked.get(ns)+ if (why) throw new PullSecretProvisionError(why, 'foreign_secret_would_be_revoked', 409)+ }return results}@@ -284,8 +328,10 @@ export async function ensureRegistryPullSecret(gateway,[targetNs, ...platformWorkloadNamespaces()],// Only this caller's own namespace is load-bearing: the siblings are swept along for- // the mint-once collapse, so a foreign squatter in one of them must not fail an install- // that never references it.+ // the mint-once collapse, so an unusable foreign squatter in one of them must not fail+ // an install that never references it. A USABLE foreign copy in a sibling is different+ // — it forbids the mint outright (see the all-or-nothing rule in the file header), so+ // if `targetNs` needed one it comes back `foreign_secret_would_be_revoked`.{ required: [targetNs] })return results.get(targetNs) ?? 'skipped'@@ -342,13 +388,14 @@ function classify(current: SecretView | null, host: string): TargetState {async function ensureInner(gateway: K8sGateway, targets: string[]): Promise<EnsurePass> {const out = new Map<string, EnsurePullSecretResult>()const unusable = new Map<string, string>()+ const blocked = new Map<string, string>()// ── Legitimate no-ops ─────────────────────────────────────────────────────// Managed clusters: the operator owns this Secret; never contend with it.const host = registryHostFromUrl(config.registryUrl)if (config.registryConnectionMode !== 'self-hosted' || !host) {for (const ns of targets) out.set(ns, 'skipped')- return { results: out, unusable }+ return { results: out, unusable, blocked }}// ── Hard preconditions: from here on we MUST provision or fail loudly ─────@@ -396,12 +443,11 @@ async function ensureInner(gateway: K8sGateway, targets: string[]): Promise<Ensu// throwing: the pass spans the whole platform set for the mint-once collapse, but only a// caller that actually references the namespace should be failed by it (see// `ensureRegistryPullSecrets`, which raises `foreign_secret_unusable` for its own- // required set). A well-shaped foreign Secret proceeds untouched either way: external- // pre-provisioning is a supported contract.+ // required set). A well-shaped foreign Secret proceeds untouched either way.+ const foreign = targets.filter(ns => states.get(ns)!.kind === 'foreign')const ours = targets.filter(ns => states.get(ns)!.kind !== 'foreign')- for (const ns of targets) {- const state = states.get(ns)!- if (state.kind !== 'foreign') continue+ for (const ns of foreign) {+ const state = states.get(ns) as { kind: 'foreign'; unusable: string | null }if (state.unusable) {unusable.set(ns, state.unusable)logger.warn(@@ -416,7 +462,7 @@ async function ensureInner(gateway: K8sGateway, targets: string[]): Promise<Ensu}out.set(ns, 'exists-foreign')}- if (ours.length === 0) return { results: out, unusable }+ if (ours.length === 0) return { results: out, unusable, blocked }// 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@@ -430,8 +476,54 @@ async function ensureInner(gateway: K8sGateway, targets: string[]): Promise<Ensuif (!needsMint) {for (const ns of ours) out.set(ns, 'exists-ours')- return { results: out, unusable }+ return { results: out, unusable, blocked }}++ // ── All-or-nothing: a USABLE foreign copy anywhere forbids the mint ───────+ // The credential is per-ORG and the mint is rotate-on-call, so minting for a namespace we+ // own would revoke the key inside the foreign Secret we just agreed not to touch. That+ // damage is invisible — the foreign bytes are unchanged, the foreign fingerprint is not+ // in the divergence set above, and invariant 1 forbids repairing it — so the only safe+ // move is to mint nothing and report the namespaces we could not fill. Owned copies that+ // are already current are untouched by this: they needed no mint, so `needsMint` above+ // has already returned them as `exists-ours`.+ //+ // The gate is USABILITY, not foreignness. An UNUSABLE foreign Secret cannot be serving a+ // pull for this registry by construction — the kubelet ignores a wrong `type` outright,+ // and never selects a blob carrying no entry for our host — so rotating the org key+ // cannot break a working path through it. Blocking on it would only fail installs that+ // never reference its namespace, which is the scoping this service already decided+ // against. It stays recorded in `unusable`, so the callers that DO reference it still+ // fail on it (`foreign_secret_unusable`).+ const blocking = foreign.filter(+ ns => (states.get(ns) as { unusable: string | null }).unusable === null+ )+ if (blocking.length > 0) {+ // Under divergence every owned copy needs the rewrite, not just the invalid ones.+ const unfillable = diverged ? ours : ours.filter(ns => states.get(ns)!.kind !== 'valid')+ const externals = blocking.map(n => `"${n}"`).join(', ')+ const all = platformWorkloadNamespaces()+ .map(n => `"${n}"`)+ .join(', ')+ for (const ns of unfillable) {+ blocked.set(+ ns,+ `cannot provision the ${EVENFIRE_REGISTRY_PULL_SECRET_NAME} Secret in namespace "${ns}": an externally-owned copy of it exists in ${externals}, and this organization's pull credential is rotate-on-call — minting one for "${ns}" would revoke the key inside that external Secret and break every pod already pulling with it. Either provision ${EVENFIRE_REGISTRY_PULL_SECRET_NAME} externally in ALL of ${all}, or delete the external copy in ${externals} so control-api can manage every namespace itself.`+ )+ }+ // The owned copies we did NOT block are genuinely current — nothing rotated their key —+ // so report them honestly. Leaving them out would fall through the wrapper's+ // `?? 'skipped'` and claim provisioning was never our job.+ for (const ns of ours) {+ if (!blocked.has(ns)) out.set(ns, 'exists-ours')+ }+ logger.warn(+ { 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 }+ }+if (diverged) {logger.warn({ namespaces: ours },@@ -457,7 +549,10 @@ async function ensureInner(gateway: K8sGateway, targets: string[]): Promise<Ensuconst 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))+ const outcome = await writeCredential(gateway, ns, state, cred, recreate.has(ns), {+ host,+ unusable,+ })out.set(ns, outcome)}@@ -467,7 +562,7 @@ async function ensureInner(gateway: K8sGateway, targets: string[]): Promise<Ensufingerprint: cred.fingerprint,})logger.info({ namespaces: ours, orgName }, 'registry pull secret provisioned')- return { results: out, unusable }+ return { results: out, unusable, blocked }}/** Write `cred` into one namespace, choosing create/update/recreate from its prior state. */@@ -476,7 +571,10 @@ async function writeCredential(ns: string,state: TargetState,cred: MintedCredential,- alreadyDeleted: boolean+ alreadyDeleted: boolean,+ // The pass's `unusable` map, so a foreign Secret discovered on the race path below is+ // recorded exactly as one discovered by `classify` would be — see the comment there.+ pass: { host: string; unusable: Map<string, string> }): Promise<EnsurePullSecretResult> {// Wrong-typed Secrets were deleted before the mint (see ensureInner), so they are now// absent and must be created, not updated.@@ -498,7 +596,28 @@ async function writeCredential(// adopting the winner's would split this namespace from the rest for a credential we// can verify no better. Skip if the winner is foreign — invariant 1 still holds.const winner = await readCurrent(gateway, ns)- if (winner && winner.labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) return 'exists-foreign'+ if (!winner) {+ // Created and deleted again before this read. The Secret is absent, and an update+ // against an absent Secret 404s — so create, do not fall through.+ await gateway.createSecret(buildSecretReq(ns, cred))+ return 'created'+ }+ if (winner.labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) {+ // The all-or-nothing scan in ensureInner ran before this Secret existed, so the+ // mint has already happened and cannot be taken back. What we CAN still do is give+ // this namespace the same verdict the classify path would: a foreign Secret the+ // kubelet will ignore must fail the callers that reference it, not sail past them+ // and leave a CRD pointing at a credential no pod can use.+ const problem = foreignUsabilityProblem(winner, pass.host)+ if (problem) {+ pass.unusable.set(ns, problem)+ logger.warn(+ { namespace: ns, problem },+ 'lost the create race to an externally-owned evenfire-registry-pull Secret that cannot serve an image pull; leaving it untouched — installs that reference this namespace will fail until it is fixed or removed'+ )+ }+ return 'exists-foreign'+ }await gateway.updateSecret(buildSecretReq(ns, cred))return 'created'}diff --git a/control-api/test/registryPullSecretService.test.ts b/control-api/test/registryPullSecretService.test.tsindex a01012173..f8eb5d516 100644--- a/control-api/test/registryPullSecretService.test.ts+++ b/control-api/test/registryPullSecretService.test.ts@@ -302,8 +302,36 @@ describe('ensureRegistryPullSecret — never touches a Secret we do not own', ()})// The pass covers the whole platform set so the mint can be collapsed across callers —- // but that must not turn a squatter in one namespace into an outage for installs that- // never land there. The failure is scoped to the caller's OWN required namespaces.+ // and that sweep is exactly why a USABLE foreign copy anywhere has to stop the mint. The+ // credential is per-ORG and the registry's mint is rotate-on-call, so provisioning+ // mcp-server revokes whatever key the external owner sealed into the sandbox-ui Secret,+ // which we may not repair (invariant 1) and cannot even detect (a foreign copy is not in+ // the fingerprint set). A well-shaped foreign copy therefore means the org credential is+ // externally managed: mint nothing, and fail the caller that needed a namespace we could+ // not fill.+ it('refuses to provision around a usable foreign Secret in a namespace the caller never references', async () => {+ const { gateway, mock } = gw()+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, UI, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'operator-key') },+ })++ await expect(ensureRegistryPullSecret(gateway, NS)).rejects.toMatchObject({+ reason: 'foreign_secret_would_be_revoked',+ status: 409,+ })+ // Nothing minted, so the operator's key is still live...+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ // ...and nothing written, in the foreign namespace or the ones we own.+ await expect(mock.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)).rejects.toThrow()+ expect((await readStored(mock, UI)).labels['clerum.io/managed-by']).toBeUndefined()+ })++ // ...but that sweep must not turn a BROKEN squatter into an outage for installs that+ // never land there. An unusable foreign Secret is by definition not serving any pull —+ // the kubelet ignores a wrong type outright, and never selects a blob keyed on another+ // host — so rotating the org key cannot break a working path through it. The failure+ // stays scoped to the caller's OWN required namespaces.it('does not fail a single-namespace install over an unusable foreign Secret elsewhere', async () => {const { gateway, mock } = gw()mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, UI, { type: 'Opaque', data: {} })@@ -321,6 +349,106 @@ describe('ensureRegistryPullSecret — never touches a Secret we do not own', ()expect(squatter.labels['clerum.io/managed-by']).toBeUndefined()})+ // The boundary itself, pinned in one place. The gate is USABILITY, not foreignness: only+ // a foreign Secret that could plausibly be serving pulls right now (correct type AND+ // keyed on our host) can be holding the org's live key, and only that one is worth+ // blocking a mint for. Collapsing the two cases in either direction breaks this test —+ // treating every foreign copy as blocking reverses the deliberate scoping fix above;+ // treating none as blocking reinstates the silent cross-namespace revocation.+ it('blocks the mint for a USABLE foreign sibling but not for an unusable one', async () => {+ // (a) unusable squatter — nothing to revoke through it, so the mint proceeds.+ const broken = gw()+ broken.mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, UI, { type: 'Opaque', data: {} })+ await expect(ensureRegistryPullSecret(broken.gateway, NS)).resolves.toBe('created')+ expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)++ // (b) same shape, same caller, but the squatter is well-formed — it may be the live+ // credential for this org, so the mint is refused instead.+ vi.mocked(mintOrgPullCredential).mockClear()+ const wellShaped = gw()+ wellShaped.mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, UI, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'operator-key') },+ })+ await expect(ensureRegistryPullSecret(wellShaped.gateway, NS)).rejects.toMatchObject({+ reason: 'foreign_secret_would_be_revoked',+ status: 409,+ })+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ // The remedy is not obvious from a bare 409 — the namespace that fails is not the one+ // holding the external Secret — so the message has to name both and say what to do.+ it('names the external namespace, the unfillable one, and both remedies', async () => {+ const { gateway, mock } = gw()+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'operator-key') },+ })++ const err = await ensureRegistryPullSecrets(gateway, ALL).catch((e: Error) => e)+ expect(err).toBeInstanceOf(PullSecretProvisionError)+ const message = (err as Error).message+ expect(message).toContain(`"${SANDBOX}"`) // the namespace we cannot provision+ expect(message).toContain(`"${NS}"`) // the externally-owned one that blocks it+ expect(message).toMatch(/revoke/i) // why we refuse+ expect(message).toMatch(/delete/i) // remedy B: hand the namespaces back to control-api+ expect(message).toContain(EVENFIRE_REGISTRY_PULL_SECRET_NAME)+ })++ // A pass that has nothing to mint for is untouched by the rule: no mint, no revocation,+ // no block. This is the shape a fully externally-provisioned cluster settles into.+ it('accepts a foreign Secret alongside already-current owned copies (nothing to mint)', async () => {+ const { gateway, mock } = gw()+ seedValid(mock, [NS, UI], 'efrk_live')+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, SANDBOX, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'operator-key') },+ })++ const res = await ensureRegistryPullSecrets(gateway, ALL)+ expect(res.get(SANDBOX)).toBe('exists-foreign')+ expect(res.get(NS)).toBe('exists-ours')+ expect(res.get(UI)).toBe('exists-ours')+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ // A blocked pass is not a blanket failure: the namespaces it leaves alone are genuinely+ // fine, and a caller that only needs one of those must still get a truthful answer. It+ // must NOT come back `'skipped'`, which means "provisioning is not our job" (managed+ // cluster) and would tell an operator to look in entirely the wrong place.+ it('reports an untouched, already-current copy as exists-ours even when the mint is blocked', async () => {+ const { gateway, mock } = gw()+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'operator-key') },+ })+ seedValid(mock, [SANDBOX], 'efrk_live')+ // sandbox-ui is absent, so the pass wants a mint — and the foreign mcp-server copy+ // forbids it. sandbox-recipes is unaffected: nothing rotated the key it holds.+ await expect(ensureRegistryPullSecret(gateway, SANDBOX)).resolves.toBe('exists-ours')+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ // Divergence is normally the trigger for a corrective re-mint. It is not a licence to+ // rotate a key we do not fully own: converging our copies would still kill the external+ // one. Stay diverged and say so.+ it('does not re-mint to converge diverged owned copies while a foreign copy exists', async () => {+ const { gateway, mock } = gw()+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'operator-key') },+ })+ seedValid(mock, [SANDBOX], 'efrk_a')+ seedValid(mock, [UI], 'efrk_b')++ await expect(ensureRegistryPullSecrets(gateway, ALL)).rejects.toMatchObject({+ reason: 'foreign_secret_would_be_revoked',+ status: 409,+ })+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })+it('still fails the recipe path, which does reference that namespace', async () => {const { gateway, mock } = gw()mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, UI, { type: 'Opaque', data: {} })@@ -357,6 +485,54 @@ describe('ensureRegistryPullSecret — concurrent create race', () => {expect(decodeHosts(stored.blob)).toEqual([HOST])expect(stored.annotations[FINGERPRINT_ANNOTATION]).toBe(fingerprintOf('efrk_test_key'))})++ // The winner appeared after classification, so the up-front foreign scan never saw it.+ // Bowing out with 'exists-foreign' is right (invariant 1) but is not the whole job: the+ // caller is still about to attach an imagePullSecrets reference to a Secret the kubelet+ // will ignore. The race path has to record the same unusability the classify path does,+ // or the install persists a CRD that can never pull.+ it('records an unusable foreign race winner, so a caller that needs it still fails', async () => {+ const { gateway, mock } = gw()+ const create = mock.createSecret.bind(mock)+ vi.spyOn(mock, 'createSecret').mockImplementation(async req => {+ if ((req as { namespace?: string }).namespace !== NS) return create(req)+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, { type: 'Opaque', data: {} })+ throw Object.assign(new Error('already exists'), { statusCode: 409, code: 409 })+ })++ await expect(ensureRegistryPullSecret(gateway, NS)).rejects.toMatchObject({+ reason: 'foreign_secret_unusable',+ status: 409,+ })+ // Still never written: invariant 1 holds on the race path too.+ const stored = await readStored(mock)+ expect(stored.type).toBe('Opaque')+ expect(stored.labels['clerum.io/managed-by']).toBeUndefined()+ })++ it('creates again when the race winner is already gone by the time we re-read', async () => {+ const { gateway, mock } = gw()+ const create = mock.createSecret.bind(mock)+ const updateSpy = vi.spyOn(mock, 'updateSecret')+ let raced = false+ vi.spyOn(mock, 'createSecret').mockImplementation(async req => {+ if ((req as { namespace?: string }).namespace === NS && !raced) {+ raced = true+ // Created and deleted again before our re-read, so the re-read finds nothing.+ throw Object.assign(new Error('already exists'), { statusCode: 409, code: 409 })+ }+ return create(req)+ })++ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('created')+ // The real API 404s an update against an absent Secret, so this path must CREATE. The+ // mock's updateSecret happily upserts, which is precisely why the assertion is on the+ // call and not on the stored bytes.+ expect(updateSpy.mock.calls.some(c => (c[0] as { namespace?: string }).namespace === NS)).toBe(+ false+ )+ expect((await readStored(mock)).blob).toBeTruthy()+ })})describe('ensureRegistryPullSecrets — fan-out across platform namespaces', () => {@@ -446,20 +622,34 @@ describe('ensureRegistryPullSecrets — fan-out across platform namespaces', ()expect(new Set(seen.map(s => s.fingerprint)).size).toBe(1)})- it('skips a foreign namespace but still provisions the others', async () => {+ // This used to assert that a foreign namespace is skipped while the others are+ // provisioned, and that the foreign blob survives "byte for byte". Byte-identity is NOT+ // the property that matters here, and asserting it is what let the bug through: the mint+ // is per-ORG and rotate-on-call, so provisioning the two namespaces we own revokes the+ // key sealed INSIDE those untouched bytes. The Secret then looks perfect and is dead —+ // its fingerprint is not in the divergence set (foreign copies are excluded), invariant 1+ // forbids repairing it, and every pod already pulling with it breaks on its next restart.+ // The property that actually keeps the credential alive is that no mint happens at all.+ it('mints nothing at all when one namespace is foreign, and says which one it cannot fill', async () => {const { gateway, mock } = gw()const operatorBlob = encodeDockercfg(HOST, 'operator-key')mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, SANDBOX, {type: 'kubernetes.io/dockerconfigjson',data: { [DOCKERCONFIG_KEY]: operatorBlob },})- 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.+ // A full-set caller lands workloads in the namespaces we cannot fill without that+ // mint, so it must fail loudly instead of getting a 201 over a cluster we just broke.+ await expect(ensureRegistryPullSecrets(gateway, ALL)).rejects.toMatchObject({+ reason: 'foreign_secret_would_be_revoked',+ status: 409,+ })+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ // The bytes are unchanged — but only as a consequence of the key still being live.expect((await blobIn(mock, SANDBOX)).blob).toBe(operatorBlob)+ // And the namespaces we own stay absent rather than half-provisioned.+ await expect(mock.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)).rejects.toThrow()+ await expect(mock.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, UI)).rejects.toThrow()})it('refuses a namespace outside the platform set, before minting', async () => {diff --git a/docs/architecture/registry-pull-secret-self-provisioning.md b/docs/architecture/registry-pull-secret-self-provisioning.mdindex ea808dbdc..964916c63 100644--- a/docs/architecture/registry-pull-secret-self-provisioning.md+++ b/docs/architecture/registry-pull-secret-self-provisioning.md@@ -361,8 +361,23 @@ Algorithm:- `404` → **absent** → go to step 4.- any other status (esp. **403**) → **abort before minting**.- present and **not** labeled `managed-by=control-api` → **`'exists-foreign'`**,- returned unconditionally (I1). If it is also unusable we log a warning naming the- remedy (delete it), but we never write.+ returned unconditionally (I1). We never write it, usable or not.++ A foreign copy is not merely "skip this namespace", because the pull key is per-**org**+ and the mint is rotate-on-call: minting for the namespaces we *do* own revokes the key+ inside the foreign Secret as well, and I1 forbids us from repairing it afterwards. So a+ **usable** foreign copy (right `type`, blob keyed on the current host) blocks the mint+ for the whole pass — the org's credential is externally managed and this service must+ not rotate it. Owned namespaces that needed that mint are recorded as blocked and+ surfaced to callers that require them as `foreign_secret_would_be_revoked` (409); a+ caller whose own namespaces are already current is unaffected.++ An **unusable** foreign copy (wrong `type`, or a blob keyed on another host) does *not*+ block the mint: the kubelet never selects it, so it cannot be serving pulls and+ rotating breaks nothing. It still fails any caller that requires *its* namespace, with+ `foreign_secret_unusable` (409). Both conditions are recorded during the pass rather+ than thrown from it, because one pass is shared across callers with different required+ sets — see the `blocked`/`unusable` maps in `registryPullSecretService.ts`.- present, ours, `type` correct, and the decoded blob's `auths` contains the currenthost → **`'exists-ours'`**. Presence alone is not enough: a blob keyed on a previous`CLERUM_REGISTRY_URL` can never be selected by the kubelet.@@ -471,6 +486,13 @@ working on-cluster key — so read-before-mint (§7.1 step 2) is the load-bearinidempotency guarantee: control-api mints only when the Secret is absent or broken, andnever for an `'exists-ours'`/`'exists-foreign'` hit.+Leaving a foreign Secret unwritten is **not** on its own sufficient, because the key is+per-org: a mint for any *other* namespace revokes the foreign copy's credential too, with+no way to detect it (foreign copies are excluded from the fingerprint comparison) and no+way to repair it (I1). A **usable** foreign copy therefore blocks the mint entirely for+that pass — see §7.1 step 3. This is the same one-writer-per-org rule the registry+enforces between operator and tenant, applied within a single cluster.+### 7.5 What stays unchanged- The attach/upgrade logic and `shouldAttachEvenfirePullSecret` (correct today).diff --git a/docs/how-to/connect-to-registry.md b/docs/how-to/connect-to-registry.mdindex 5024fd121..9a80b6fb4 100644--- a/docs/how-to/connect-to-registry.md+++ b/docs/how-to/connect-to-registry.md@@ -71,12 +71,30 @@ Once connected, browsing the public catalog, publishing, and image push/pull allwork using the credential stored when you claimed the connection — no furthersetup is needed for those.-> **In-cluster image pulls.** When you install a private plugin whose image lives on-> the evenfire registry, control-api (in self-hosted mode) automatically provisions-> the in-cluster `evenfire-registry-pull` Secret in the plugin namespace, so the-> plugin pods can pull the image — you do not create that Secret by hand. It is-> minted from your connection's own registry identity and left untouched if an-> external operator already provided one.+> **In-cluster image pulls.** When you install a private plugin or recipe whose image+> lives on the evenfire registry, control-api (in self-hosted mode) automatically+> provisions the in-cluster `evenfire-registry-pull` Secret in every platform workload+> namespace — `mcp-server`, `sandbox-recipes` and `sandbox-ui` — so the pods can pull+> the image. You do not create that Secret by hand. It is minted from your+> connection's own registry identity.+>+> **If you pre-provision it yourself, do all three namespaces.** control-api never+> writes a Secret it does not own (one without the `clerum.io/managed-by: control-api`+> label), and the registry's pull credential is **per-organization and rotate-on-call**:+> minting a key for one namespace revokes the key in every other copy, including yours.+> So the moment control-api finds a **working** externally-provided copy in any of the+> three namespaces, it stops minting entirely rather than silently invalidating your+> credential. Installs that need a namespace you left empty then fail with+> `foreign_secret_would_be_revoked`, naming both namespaces. Provide the Secret in all+> three namespaces, or delete your copies and let control-api manage all three — a+> half-external setup is not supported.+>+> A **malformed** external copy is treated differently: one with the wrong `type`, or a+> `.dockerconfigjson` carrying no entry for your registry host, can never serve a pull,+> so it does not hold control-api back from minting for the other namespaces. It does+> fail any install that lands a workload in _its own_ namespace, with+> `foreign_secret_unusable` — fix that Secret in place, or delete it and let control-api+> manage that namespace.**Creating and managing API keys** (`efrk_` org keys, used for CI and otherprogrammatic publishing) needs registry authentication active. In self-hosted,