Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): serialize pull-secret minting across every caller
Jose Ramirezd1f99a531c1c
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex bb7007cdb..6059fe77a 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.401",+ "version": "0.1.402","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.401",+ "version": "0.1.402","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 4099c1caa..da67d9803 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.401",+ "version": "0.1.402","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 b8614c057..0a08c9c4a 100644--- a/control-api/src/services/registryPullSecretService.ts+++ b/control-api/src/services/registryPullSecretService.ts@@ -6,17 +6,30 @@* provisions it itself. Design: docs/architecture/registry-pull-secret-self-provisioning.md.** Contract (must match what the managed operator writes, so either satisfies the same- * McpServer.spec.imagePullSecrets reference):+ * imagePullSecrets reference):* name = 'evenfire-registry-pull' (EVENFIRE_REGISTRY_PULL_SECRET_NAME)- * ns = the McpServer's own namespace (imagePullSecrets are namespace-local)+ * ns = EVERY platform workload namespace (see below; imagePullSecrets are ns-local)* type = kubernetes.io/dockerconfigjson* data['.dockerconfigjson'] = base64 payload, keyed on OUR image host (registryUrl),* NOT the registry's token-issuer* label clerum.io/managed-by = control-api (ownership marker; absent ⇒ externally owned)*+ * Namespaces — the reference is NOT confined to an McpServer's own namespace. WRC injects+ * `imagePullSecrets: [evenfire-registry-pull]` into every workload whose image host equals+ * the configured registry host, wherever CLERUM_REGISTRY_URL is set, and recipe workloads+ * 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.+ ** Two invariants make this safe to run repeatedly:* 1. NEVER write a Secret we do not own. An unlabeled Secret belongs to an external- * operator; we return `exists-foreign` and leave it alone even if it looks broken.+ * operator; we return `exists-foreign` and leave it alone. Not owning it does not+ * mean waving the caller through, though: if it cannot serve an image pull at all we+ * fail the install (`foreign_secret_unusable`) rather than let a CRD reference it.* 2. Mint ONLY when we are already committed to a write we know can succeed. The* 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@@ -167,7 +180,17 @@ async function mintCredential(orgName: string, host: string): Promise<MintedCred}// 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.+// both mint. Keyed on the whole target set, since a pass is atomic over its namespaces —+// which means every caller must pass the SAME set or the dedupe silently does nothing.+// That is why the single-namespace wrapper below delegates to the full platform set: two+// mints against a rotate-on-call registry leave the loser's namespaces on a revoked key,+// and (because the loser rewrites the winner's namespaces too) with FINGERPRINTS THAT+// AGREE — so the divergence check in ensureInner cannot see it and no later pass re-mints.+//+// Correct only at ONE replica (deploy/base/control-plane/control-api.yaml pins+// `replicas: 1`). An in-process Map cannot see another replica's pass, so scaling out+// 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.const inflight = new Map<string, Promise<Map<string, EnsurePullSecretResult>>>()/** The platform workload namespaces a pull credential may legitimately be written into. */@@ -209,28 +232,66 @@ export function ensureRegistryPullSecrets(/*** Single-namespace convenience wrapper, for the McpServer install/upgrade paths that* provision exactly the namespace their workload lands in.+ *+ * It still runs the FULL platform-namespace pass and then picks its own namespace out of+ * the result, because the inflight dedupe is keyed on the target set: a pass over just+ * `[targetNs]` would never collapse with a concurrent recipe install over all three, and+ * both would mint (see the note on `inflight`). `targetNs` stays in the list so an+ * unsupported namespace is still rejected by ensureInner's allowlist — same reason code,+ * same status, same point in the sequence.+ *+ * Costs two extra Secret reads per MCP install. Buys the mint-once guarantee across route+ * paths, and makes every install a full-set pass, so a diverged cluster converges on+ * whichever install runs next.*/export async function ensureRegistryPullSecret(gateway: K8sGateway,targetNs: string): Promise<EnsurePullSecretResult> {- const results = await ensureRegistryPullSecrets(gateway, [targetNs])+ const results = await ensureRegistryPullSecrets(gateway, [+ targetNs,+ ...platformWorkloadNamespaces(),+ ])return results.get(targetNs) ?? 'skipped'}/** Classification of one namespace's current Secret, decided before anything is minted. */type TargetState =- | { kind: 'foreign' }+ | { kind: 'foreign'; unusable: string | null }| { kind: 'valid'; fingerprint: string }| { kind: 'absent' }| { kind: 'broken'; wrongType: boolean }+/**+ * Why a Secret we do NOT own cannot serve an image pull, or null when it can.+ *+ * Read-only by construction — the same two checks `classify` applies to our own copies,+ * with no fingerprint requirement (that annotation is ours; an external operator has no+ * reason to write it) and no write of any kind.+ *+ * Deliberately shape-only: a well-formed blob whose key the registry has since revoked+ * still passes here. Proving liveness would take a registry round-trip on every install,+ * which this check does not do.+ */+function foreignUsabilityProblem(current: SecretView, host: string): string | null {+ if (current.type !== DOCKERCONFIG_TYPE) {+ return `its type is "${current.type ?? 'unset'}", not ${DOCKERCONFIG_TYPE} — the kubelet ignores it for image pulls`+ }+ if (!dockerconfigMatchesHost(current.dockerconfig, host)) {+ return `its ${DOCKERCONFIG_KEY} carries no entry for "${host}", so the kubelet will never select it`+ }+ return null+}+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' }+ // key out from under them. We still inspect it: not-ours decides who WRITES, not whether+ // the caller may attach a reference to it (see ensureInner).+ if (current.labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) {+ return { kind: 'foreign', unusable: foreignUsabilityProblem(current, host) }+ }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@@ -294,15 +355,28 @@ async function ensureInner(states.set(ns, classify(await readCurrent(gateway, ns), host))}+ // ── Foreign targets: hands off, but not a free pass ───────────────────────+ // Every caller of this service is about to attach an `imagePullSecrets` reference to+ // this name and persist a CRD, so a foreign Secret the kubelet cannot use is exactly as+ // fatal as a missing one — and we may not repair it. Fail the install instead, naming+ // the namespace, before anything is minted (so the org's live key is untouched).+ // A well-shaped foreign Secret still proceeds: external pre-provisioning is supported.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)'+ const state = states.get(ns)!+ if (state.kind !== 'foreign') continue+ if (state.unusable) {+ throw new PullSecretProvisionError(+ `the ${EVENFIRE_REGISTRY_PULL_SECRET_NAME} Secret in namespace "${ns}" is externally owned and cannot serve an image pull: ${state.unusable}. Fix it in place, or delete it to let control-api manage that namespace. (A well-shaped foreign Secret is accepted even if its key has since been revoked — checking that would take a registry round-trip.)`,+ 'foreign_secret_unusable',+ 409)- out.set(ns, 'exists-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')}if (ours.length === 0) return out@@ -378,9 +452,13 @@ async function writeCredential(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.+ // Lost a create race — but NOT against ourselves: concurrent passes in this replica+ // collapse on the `inflight` key. The winner is therefore another writer (a second+ // replica, which this design does not support, or an out-of-band actor), and which+ // key is live is not knowable here — ours revoked theirs only if we minted last.+ // Write ours anyway, so this pass leaves every namespace it owns on ONE key;+ // 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'await gateway.updateSecret(buildSecretReq(ns, cred))diff --git a/control-api/test/registryPullSecretService.test.ts b/control-api/test/registryPullSecretService.test.tsindex 247ac32ce..a735044d1 100644--- a/control-api/test/registryPullSecretService.test.ts+++ b/control-api/test/registryPullSecretService.test.ts@@ -21,6 +21,9 @@ vi.mock('../src/services/registryClient.js', () => ({}))const NS = 'mcp-server'+const SANDBOX = 'sandbox-recipes'+const UI = 'sandbox-ui'+const ALL = [NS, SANDBOX, UI]const HOST = 'registry.evenfire.ai'const DOCKERCONFIG_KEY = '.dockerconfigjson'const OURS = { 'clerum.io/managed-by': 'control-api' }@@ -63,6 +66,24 @@ async function readStored(mock: MockGateway): Promise<{}}+/**+ * Seed an already-provisioned, agreeing credential in `namespaces`.+ *+ * Every entry point provisions the WHOLE platform set (the single-namespace wrapper+ * delegates to it), so a test aimed at one namespace's state must settle the others too —+ * an absent sibling alone forces a mint and swamps what the test is about.+ */+function seedValid(mock: MockGateway, namespaces: string[], key: string): void {+ for (const ns of namespaces) {+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: OURS,+ annotations: { [FINGERPRINT_ANNOTATION]: fingerprintOf(key) },+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, key) },+ })+ }+}+function decodeHosts(blob: string | undefined): string[] {if (!blob) return []const parsed = JSON.parse(Buffer.from(blob, 'base64').toString('utf8')) as {@@ -180,12 +201,7 @@ describe('ensureRegistryPullSecret — provisioning', () => {it('reuses our existing, correctly-keyed Secret without minting', async () => {const { gateway, mock } = gw()- 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') },- })+ seedValid(mock, ALL, 'efrk_live')await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-ours')expect(mintOrgPullCredential).not.toHaveBeenCalled()})@@ -233,33 +249,64 @@ describe('ensureRegistryPullSecret — provisioning', () => {})describe('ensureRegistryPullSecret — never touches a Secret we do not own', () => {- it('leaves a foreign Secret WITH data untouched', async () => {+ it('leaves a well-shaped foreign Secret untouched and proceeds', async () => {const { gateway, mock } = gw()+ // The siblings are settled, so nothing but the foreign namespace is in play.+ seedValid(mock, [SANDBOX, UI], 'efrk_live')mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {type: 'kubernetes.io/dockerconfigjson',- data: { [DOCKERCONFIG_KEY]: 'operator-provisioned' },+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'operator-key') },})+ // External pre-provisioning is a supported contract: usable + not ours ⇒ hands off.await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-foreign')expect(mintOrgPullCredential).not.toHaveBeenCalled()- expect((await readStored(mock)).blob).toBe('operator-provisioned')+ expect((await readStored(mock)).blob).toBe(encodeDockercfg(HOST, 'operator-key'))})- it('leaves a foreign EMPTY Secret untouched (never seizes ownership)', async () => {+ // Foreign is a reason not to WRITE, not a reason to wave the caller through: every+ // caller attaches an imagePullSecrets reference to this exact name and then persists a+ // CRD. A foreign Secret the kubelet cannot use makes that reference unresolvable, which+ // is the silent ImagePullBackOff this service exists to prevent.+ it('fails loudly when a foreign Secret is the wrong type (kubelet ignores it)', async () => {const { gateway, mock } = gw()+ seedValid(mock, [SANDBOX, UI], 'efrk_live')mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, { type: 'Opaque', data: {} })- await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-foreign')++ await expect(ensureRegistryPullSecret(gateway, NS)).rejects.toMatchObject({+ reason: 'foreign_secret_unusable',+ status: 409,+ })+ // Still never written, and never minted for: invariant 1 is unchanged.expect(mintOrgPullCredential).not.toHaveBeenCalled()const stored = await readStored(mock)expect(stored.type).toBe('Opaque')expect(stored.labels['clerum.io/managed-by']).toBeUndefined()})++ it('fails loudly when a foreign Secret is keyed on a different registry host', async () => {+ const { gateway, mock } = gw()+ seedValid(mock, [SANDBOX, UI], 'efrk_live')+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg('old-registry.example.com', 'operator-key') },+ })++ await expect(ensureRegistryPullSecret(gateway, NS)).rejects.toMatchObject({+ reason: 'foreign_secret_unusable',+ status: 409,+ })+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })})describe('ensureRegistryPullSecret — concurrent create race', () => {it('adopts the winner without minting a second key', async () => {const { gateway, mock } = gw()- // The winner's Secret appears between our 404 read and our create.- vi.spyOn(mock, 'createSecret').mockImplementation(async () => {+ // The winner's Secret appears between our 404 read and our create — in ONE namespace;+ // the pass's other namespaces are created normally.+ 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: 'kubernetes.io/dockerconfigjson',labels: OURS,@@ -268,8 +315,8 @@ describe('ensureRegistryPullSecret — concurrent create race', () => {throw Object.assign(new Error('already exists'), { statusCode: 409, code: 409 })})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.+ // Exactly ONE mint, and the pass converges its own namespaces on that one key rather+ // than adopting a winner's credential it cannot verify.expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)const stored = await readStored(mock)expect(decodeHosts(stored.blob)).toEqual([HOST])@@ -278,10 +325,6 @@ describe('ensureRegistryPullSecret — concurrent create race', () => {})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> }@@ -370,9 +413,10 @@ describe('ensureRegistryPullSecrets — fan-out across platform namespaces', ()it('skips a foreign namespace but still provisions the others', 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]: 'operator-provisioned' },+ data: { [DOCKERCONFIG_KEY]: operatorBlob },})const res = await ensureRegistryPullSecrets(gateway, ALL)@@ -380,7 +424,7 @@ describe('ensureRegistryPullSecrets — fan-out across platform namespaces', ()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')+ expect((await blobIn(mock, SANDBOX)).blob).toBe(operatorBlob)})it('refuses a namespace outside the platform set, before minting', async () => {@@ -391,4 +435,39 @@ describe('ensureRegistryPullSecrets — fan-out across platform namespaces', ()})expect(mintOrgPullCredential).not.toHaveBeenCalled()})++ // The inflight dedupe is keyed on the target SET, so concurrent passes only collapse if+ // they agree on that set. An MCP install (one namespace) and a recipe install (all+ // three) overlap on mcp-server, and two mints against a rotate-on-call registry leave+ // the loser's namespaces holding a revoked key — with matching fingerprints, so the+ // divergence detector cannot see it and no later pass ever re-mints. Hence: the+ // single-namespace wrapper must run the SAME full-set pass.+ it('collapses a single-namespace pass and a full-set pass into ONE mint', async () => {+ const { gateway, mock } = gw()++ const [single, fanOut] = await Promise.all([+ ensureRegistryPullSecret(gateway, NS),+ ensureRegistryPullSecrets(gateway, ALL),+ ])++ expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)+ expect(single).toBe('created')+ expect([...fanOut.values()]).toEqual(['created', 'created', 'created'])+ // Every namespace holds the one live credential — including the two the+ // single-namespace caller did not name.+ 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('provisions the whole platform set from a single-namespace caller', async () => {+ const { gateway, mock } = gw()++ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('created')++ // A full-set pass every time is also what lets a diverged cluster self-heal on the+ // next install, whichever route triggers it.+ expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)+ 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')]))+ })})