Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): self-provision the evenfire-registry-pull image-pull secret
Claude8734ca63f28b
diff --git a/control-api/src/routes/admin/registry.ts b/control-api/src/routes/admin/registry.tsindex ea085ba9c..7889cbd76 100644--- a/control-api/src/routes/admin/registry.ts+++ b/control-api/src/routes/admin/registry.ts@@ -43,6 +43,7 @@ import {EVENFIRE_REGISTRY_PULL_SECRET_NAME,shouldAttachEvenfirePullSecret,} from './registryImagePullSecret.js'+import { ensureRegistryPullSecret } from '../../services/registryPullSecretService.js'import { checkEvenfireImageRefMatchesEntry } from './registryImageRefIdentity.js'/** Validate a Kubernetes resource name (RFC 1123 DNS subdomain). */@@ -1111,16 +1112,17 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {transport: transportSpec,}- // Phase 2.4-delivery: local plugins whose image lives on the evenfire- // registry pull with the tenant's per-org pull secret (provisioned by- // MCC in the plugin namespace). Attach the reference; HCC propagates it.- if (- shouldAttachEvenfirePullSecret({- isLocal,- image: mcpServerSpec.image,- registryUrl: config.registryUrl,- })- ) {+ // Local plugins whose image lives on the evenfire registry pull with the+ // per-org `evenfire-registry-pull` secret. control-api self-provisions that+ // secret in self-hosted mode (see ensureRegistryPullSecret below); it may+ // also be pre-provisioned by an external operator. Attach the reference here;+ // HCC propagates it to the pod.+ const attachEvenfirePullSecret = shouldAttachEvenfirePullSecret({+ isLocal,+ image: mcpServerSpec.image,+ registryUrl: config.registryUrl,+ })+ if (attachEvenfirePullSecret) {mcpServerSpec.imagePullSecrets = [{ name: EVENFIRE_REGISTRY_PULL_SECRET_NAME }]}@@ -1212,6 +1214,25 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {body.registryEntryVersion)+ // ── Ensure the shared registry pull secret (self-hosted) ───────────+ // Must run when a private evenfire-hosted image is in play — independent of+ // whether the plugin needs credentials (a credential-less plugin still needs+ // to pull). Runs BEFORE the per-plugin credentials Secret so a failure leaves+ // nothing to roll back, and BEFORE the McpServer CRD that references it.+ // Namespace-shared, so it is NOT part of the per-plugin rollback below.+ if (attachEvenfirePullSecret) {+ try {+ await ensureRegistryPullSecret(gateway, targetNs)+ } catch (err) {+ const k8sErr = extractK8sError(err)+ res.status(k8sErr?.status && k8sErr.status < 500 ? 502 : 500).json({+ error: 'registry_pull_secret_provision_failed',+ detail: k8sErr?.message || (err instanceof Error ? err.message : 'unknown error'),+ })+ return+ }+ }+// ── Step 3: Create K8s Secret if credentials provided ─────────────let secretCreated = falseif (credRequired) {@@ -1800,23 +1821,36 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {return}- // Phase 2.4-delivery: recompute imagePullSecrets on every upgrade. The- // spread of ...existingSpec above carries a prior ref forward, so we- // must set it when the new image is evenfire-hosted and DELETE it- // otherwise (host change evenfire→GCP-AR, or local→remote) to avoid a- // stale, unresolvable pull-secret reference.- if (- shouldAttachEvenfirePullSecret({- isLocal,- image: updatedSpec.image,- registryUrl: config.registryUrl,- })- ) {+ // Recompute imagePullSecrets on every upgrade. The spread of ...existingSpec+ // above carries a prior ref forward, so we must set it when the new image is+ // evenfire-hosted and DELETE it otherwise (host change evenfire→GCP-AR, or+ // local→remote) to avoid a stale, unresolvable pull-secret reference.+ const attachEvenfirePullSecret = shouldAttachEvenfirePullSecret({+ isLocal,+ image: updatedSpec.image,+ registryUrl: config.registryUrl,+ })+ if (attachEvenfirePullSecret) {updatedSpec.imagePullSecrets = [{ name: EVENFIRE_REGISTRY_PULL_SECRET_NAME }]} else {delete updatedSpec.imagePullSecrets}+ // Ensure the shared pull secret exists before the CRD update references it+ // (self-hosted self-provision; namespace-shared, idempotent, fail-loud).+ if (attachEvenfirePullSecret) {+ try {+ await ensureRegistryPullSecret(gateway, namespace)+ } catch (err) {+ const k8sErr = extractK8sError(err)+ res.status(k8sErr?.status && k8sErr.status < 500 ? 502 : 500).json({+ error: 'registry_pull_secret_provision_failed',+ detail: k8sErr?.message || (err instanceof Error ? err.message : 'unknown error'),+ })+ return+ }+ }+const preflightErrors = await validateMcpServerSpecPreflight(updatedSpec, {allowedImagePrefixes: config.allowedPluginImagePrefixes,enforceImageAllowlist: config.enforcePluginImageAllowlist,diff --git a/control-api/src/routes/admin/registryImagePullSecret.ts b/control-api/src/routes/admin/registryImagePullSecret.tsindex fab4c350d..d7ff20188 100644--- a/control-api/src/routes/admin/registryImagePullSecret.ts+++ b/control-api/src/routes/admin/registryImagePullSecret.ts@@ -1,16 +1,18 @@/**- * Registry Phase 2.4-delivery — evenfire pull-secret attach classification.+ * evenfire pull-secret attach classification.** Pure, dependency-free helpers deciding whether an installed local-mode- * McpServer image should carry the `evenfire-registry-pull` imagePullSecret.- * The secret is provisioned onto the tenant cluster by MCC (out of this repo);- * control-api only references it by name when the image lives on the configured- * evenfire registry host.+ * McpServer image should carry the `evenfire-registry-pull` imagePullSecret,+ * i.e. when the image lives on the configured evenfire registry host. The Secret+ * itself is self-provisioned by control-api in self-hosted mode+ * (`registryPullSecretService`) and may also be pre-provisioned by an external+ * operator; this file only decides when to reference it by name.*//**- * Name of the dockerconfigjson Secret MCC provisions in the tenant plugin- * namespace. Must stay in sync with the MCC install step. Never inline.+ * Name of the dockerconfigjson Secret referenced by local-mode McpServers whose+ * image lives on the evenfire registry. The single source of truth for the name —+ * `registryPullSecretService` writes it, this file references it. Never inline.*/export const EVENFIRE_REGISTRY_PULL_SECRET_NAME = 'evenfire-registry-pull'diff --git a/control-api/src/services/registryClient.ts b/control-api/src/services/registryClient.tsindex 1616741f1..3d4fa42c7 100644--- a/control-api/src/services/registryClient.ts+++ b/control-api/src/services/registryClient.ts@@ -592,6 +592,29 @@ export async function createOrgGrant(})}+/**+ * Mint a PULL-ONLY registry credential for `orgName` using our machine identity.+ *+ * Hits the registry's `POST /org/:org/registry-pull-credential`, which — once the+ * companion registry change ships — authorizes an org-bound machine holding+ * `registry:manage-keys` (our tenant client's standing scope) to mint a pull-only,+ * rotate-on-call key for its OWN org. The endpoint also returns a `dockerconfigjson`,+ * but we DELIBERATELY ignore it: it is keyed on the registry's own token-issuer host,+ * whereas the kubelet matches on the image host (our configured registry URL host).+ * The caller builds the dockerconfigjson locally from `key`, keyed on that host.+ *+ * Rotate-on-call: each call revokes the org's prior pull key, so callers MUST+ * read-before-mint (only call when the on-cluster Secret is absent or broken) or they+ * orphan a working credential.+ */+export async function mintOrgPullCredential(orgName: string): Promise<{ key: string }> {+ const res = await orgRegistryFetch<{ username: string; key: string; dockerconfigjson: string }>(+ `/org/${encodeURIComponent(orgName)}/registry-pull-credential`,+ { method: 'POST' }+ )+ return { key: res.key }+}+export async function listOrgGrants(orgName: string): Promise<unknown> {return orgRegistryFetch(`/org/${encodeURIComponent(orgName)}/grants`)}diff --git a/control-api/src/services/registryPullSecretService.ts b/control-api/src/services/registryPullSecretService.tsnew file mode 100644index 000000000..8669c27be--- /dev/null+++ b/control-api/src/services/registryPullSecretService.ts@@ -0,0 +1,175 @@+/**+ * Self-provisioning of the `evenfire-registry-pull` image-pull Secret.+ *+ * On a self-hosted cluster there is no managed operator to drop the dockerconfigjson+ * Secret that local-mode plugins on the private registry need, so control-api+ * 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):+ * name = 'evenfire-registry-pull' (EVENFIRE_REGISTRY_PULL_SECRET_NAME)+ * ns = the McpServer's own namespace (imagePullSecrets are namespace-local)+ * type = kubernetes.io/dockerconfigjson+ * data['.dockerconfigjson'] = base64 payload, keyed on OUR image host (registryUrl),+ * NOT the registry's token-issuer (spec §7.9-2)+ * label clerum.io/managed-by = control-api (ownership marker; absent ⇒ externally owned)+ */+import type { K8sGateway } from '../k8s.js'+import type { SecretUpsertRequest } from '../types.js'+import { rootLogger } from '../observability/logger.js'+import { config } from '../config.js'+import { isRegistryAuthActive } from './registryConnectionDb.js'+import { resolvePublishScope, mintOrgPullCredential } from './registryClient.js'+import {+ EVENFIRE_REGISTRY_PULL_SECRET_NAME,+ registryHostFromUrl,+} from '../routes/admin/registryImagePullSecret.js'++const logger = rootLogger.child({ module: 'registry-pull-secret' })++const MANAGED_BY_LABEL = 'clerum.io/managed-by'+const MANAGED_BY_VALUE = 'control-api'+const DOCKERCONFIG_KEY = '.dockerconfigjson'++export type EnsurePullSecretResult =+ | 'created'+ | 'repaired'+ | 'exists-ours'+ | 'exists-foreign'+ | 'skipped'++/** Extract an HTTP-ish status from a K8s client error (mirrors extractK8sError). */+function k8sStatus(err: unknown): number | null {+ if (err && typeof err === 'object') {+ const e = err as { code?: number; statusCode?: number; httpStatus?: number }+ const s = e.code ?? e.statusCode ?? e.httpStatus+ if (typeof s === 'number') return s+ }+ return null+}++/**+ * Build a kubernetes.io/dockerconfigjson payload (base64) for `key` against `host`.+ * Keyed on OUR configured registry host (= the image host, per the attach invariant)+ * so the kubelet selects this credential — the registry's server-built blob is keyed+ * on its own token-issuer and cannot be trusted here (spec §7.9-2).+ */+function buildDockerconfigjson(host: string, key: string): string {+ const auth = Buffer.from(`_:${key}`).toString('base64')+ const cfg = { auths: { [host]: { username: '_', password: key, auth } } }+ return Buffer.from(JSON.stringify(cfg)).toString('base64')+}++interface SecretView {+ labels: Record<string, string>+ dockerconfig: string | undefined+}++function readSecret(raw: unknown): SecretView {+ const s = (raw ?? {}) as {+ metadata?: { labels?: Record<string, string> }+ data?: Record<string, string>+ }+ return {+ labels: s.metadata?.labels ?? {},+ dockerconfig: s.data?.[DOCKERCONFIG_KEY],+ }+}++function buildSecretReq(targetNs: string, dockerconfigjson: string): SecretUpsertRequest {+ return {+ name: EVENFIRE_REGISTRY_PULL_SECRET_NAME,+ namespace: targetNs,+ type: 'kubernetes.io/dockerconfigjson',+ labels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE },+ data: { [DOCKERCONFIG_KEY]: dockerconfigjson },+ }+}++async function mintAndBuild(orgName: string, host: string): Promise<string> {+ const { key } = await mintOrgPullCredential(orgName)+ return buildDockerconfigjson(host, key)+}++// Serialize concurrent ensures for the same (namespace, secret) WITHIN this replica so+// two in-flight installs don't both mint. Cross-replica races are additionally bounded+// by the registry's rotate-on-call (≤1 active pull key/org) plus reactive rotation.+const inflight = new Map<string, Promise<EnsurePullSecretResult>>()++/**+ * Ensure the `evenfire-registry-pull` Secret exists in `targetNs`, minting a fresh+ * pull-only credential only when it is absent or broken. Idempotent and coexistence-safe:+ * a Secret we do not own (no managed-by=control-api label) is left untouched.+ *+ * No-ops (`'skipped'`) outside self-hosted mode, without active registry auth, without a+ * configured registry host, or before the connect flow has resolved our org.+ *+ * THROWS on mint/write failure so the caller can fail the install loudly rather than+ * attach an unresolvable imagePullSecrets reference.+ */+export function ensureRegistryPullSecret(+ gateway: K8sGateway,+ targetNs: string+): Promise<EnsurePullSecretResult> {+ const dedupeKey = `${targetNs}/${EVENFIRE_REGISTRY_PULL_SECRET_NAME}`+ const existing = inflight.get(dedupeKey)+ if (existing) return existing+ const run = ensureInner(gateway, targetNs).finally(() => inflight.delete(dedupeKey))+ inflight.set(dedupeKey, run)+ return run+}++async function ensureInner(+ gateway: K8sGateway,+ targetNs: string+): Promise<EnsurePullSecretResult> {+ // ── Gate: only self-hosted, connected, with a resolvable org ──────────────+ if (config.registryConnectionMode !== 'self-hosted') return 'skipped'+ const host = registryHostFromUrl(config.registryUrl)+ if (!host) return 'skipped'+ if (!(await isRegistryAuthActive())) return 'skipped'+ const { orgName } = await resolvePublishScope()+ if (!orgName) {+ logger.warn(+ { targetNs },+ 'registry pull secret: org not resolved (connect flow incomplete); skipping'+ )+ return 'skipped'+ }++ // ── Read (getSecret re-throws 404; any other error aborts before minting) ──+ let current: SecretView | null = null+ try {+ current = readSecret(await gateway.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, targetNs))+ } catch (err) {+ if (k8sStatus(err) !== 404) throw err // e.g. 403 = ns outside our RBAC → abort+ current = null // 404 → absent+ }++ if (current) {+ const ours = current.labels[MANAGED_BY_LABEL] === MANAGED_BY_VALUE+ const hasCred = !!current.dockerconfig+ if (hasCred && !ours) return 'exists-foreign' // external operator owns it — never touch+ if (hasCred && ours) return 'exists-ours' // reuse; rotation handled reactively+ // Present but missing/empty .dockerconfigjson → repair (mint + replace).+ await gateway.updateSecret(buildSecretReq(targetNs, await mintAndBuild(orgName, host)))+ logger.info({ targetNs, orgName }, 'registry pull secret repaired')+ return 'repaired'+ }++ // ── Absent → mint + create ────────────────────────────────────────────────+ try {+ await gateway.createSecret(buildSecretReq(targetNs, await mintAndBuild(orgName, host)))+ } catch (err) {+ if (k8sStatus(err) === 409) {+ // Lost a concurrent create race. We hold a freshly-minted (now-active) key, so+ // overwrite with it — rotate-on-call means the last minter's key is authoritative.+ await gateway.updateSecret(buildSecretReq(targetNs, await mintAndBuild(orgName, host)))+ logger.info({ targetNs, orgName }, 'registry pull secret reconciled after create race')+ return 'created'+ }+ throw err+ }+ logger.info({ targetNs, orgName }, 'registry pull secret created')+ return 'created'+}diff --git a/control-api/test/registryImagePullSecret.test.ts b/control-api/test/registryImagePullSecret.test.tsindex 788845a88..2dee5d8ca 100644--- a/control-api/test/registryImagePullSecret.test.ts+++ b/control-api/test/registryImagePullSecret.test.ts@@ -7,7 +7,7 @@ import {} from '../src/routes/admin/registryImagePullSecret.js'describe('EVENFIRE_REGISTRY_PULL_SECRET_NAME', () => {- it('is the exact secret name MCC provisions', () => {+ it('is the frozen pull-secret name', () => {expect(EVENFIRE_REGISTRY_PULL_SECRET_NAME).toBe('evenfire-registry-pull')})})diff --git a/control-api/test/registryPullSecretService.test.ts b/control-api/test/registryPullSecretService.test.tsnew file mode 100644index 000000000..afe3ebbaa--- /dev/null+++ b/control-api/test/registryPullSecretService.test.ts@@ -0,0 +1,144 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { config } from '../src/config.js'+import { MockGateway } from './mockGateway.js'+import type { K8sGateway } from '../src/k8s.js'+import { EVENFIRE_REGISTRY_PULL_SECRET_NAME } from '../src/routes/admin/registryImagePullSecret.js'++vi.mock('../src/services/registryConnectionDb.js', () => ({+ isRegistryAuthActive: vi.fn(),+}))+vi.mock('../src/services/registryClient.js', () => ({+ resolvePublishScope: vi.fn(),+ mintOrgPullCredential: vi.fn(),+}))++import { isRegistryAuthActive } from '../src/services/registryConnectionDb.js'+import { resolvePublishScope, mintOrgPullCredential } from '../src/services/registryClient.js'+import { ensureRegistryPullSecret } from '../src/services/registryPullSecretService.js'++const NS = 'mcp-server'++function gw(): { gateway: K8sGateway; mock: MockGateway } {+ const mock = new MockGateway(NS)+ return { gateway: mock as unknown as K8sGateway, mock }+}++/** Decode the `.dockerconfigjson` a seeded/created Secret carries. */+async function decodeDockercfg(+ mock: MockGateway+): Promise<{ host: string; username: string; password: string }> {+ const raw = (await mock.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)) as {+ type?: string+ data?: Record<string, string>+ }+ expect(raw.type).toBe('kubernetes.io/dockerconfigjson')+ const blob = raw.data?.['.dockerconfigjson']+ expect(blob).toBeTruthy()+ const parsed = JSON.parse(Buffer.from(blob as string, 'base64').toString('utf8')) as {+ auths: Record<string, { username: string; password: string }>+ }+ const host = Object.keys(parsed.auths)[0]!+ return { host, username: parsed.auths[host]!.username, password: parsed.auths[host]!.password }+}++let savedMode: typeof config.registryConnectionMode+let savedUrl: string++beforeEach(() => {+ vi.clearAllMocks()+ savedMode = config.registryConnectionMode+ savedUrl = config.registryUrl+ config.registryConnectionMode = 'self-hosted'+ config.registryUrl = 'https://registry.evenfire.ai'+ vi.mocked(isRegistryAuthActive).mockResolvedValue(true)+ vi.mocked(resolvePublishScope).mockResolvedValue({ curator: false, orgName: 'acme', scope: '@acme' })+ vi.mocked(mintOrgPullCredential).mockResolvedValue({ key: 'efrk_test_key' })+})++afterEach(() => {+ config.registryConnectionMode = savedMode+ config.registryUrl = savedUrl+})++describe('ensureRegistryPullSecret', () => {+ it('skips (no mint) in managed mode', async () => {+ config.registryConnectionMode = 'managed'+ const { gateway } = gw()+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('skipped')+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('skips when registry auth is inactive', async () => {+ vi.mocked(isRegistryAuthActive).mockResolvedValue(false)+ const { gateway } = gw()+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('skipped')+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('skips when the org is not yet resolved (connect flow incomplete)', async () => {+ vi.mocked(resolvePublishScope).mockResolvedValue({ curator: false, orgName: null, scope: null })+ const { gateway } = gw()+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('skipped')+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('mints and creates the Secret when absent, keyed on the registryUrl host', async () => {+ const { gateway, mock } = gw()+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('created')+ expect(mintOrgPullCredential).toHaveBeenCalledWith('acme')+ const { host, username, password } = await decodeDockercfg(mock)+ expect(host).toBe('registry.evenfire.ai') // image host, NOT the registry token-issuer+ expect(username).toBe('_')+ expect(password).toBe('efrk_test_key')+ const raw = (await mock.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)) as {+ metadata: { labels: Record<string, string> }+ }+ expect(raw.metadata.labels['clerum.io/managed-by']).toBe('control-api')+ })++ it('reuses our existing Secret without minting', async () => {+ const { gateway, mock } = gw()+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: { 'clerum.io/managed-by': 'control-api' },+ data: { '.dockerconfigjson': 'existing' },+ })+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-ours')+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('leaves a foreign (unlabeled) Secret untouched', async () => {+ const { gateway, mock } = gw()+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { '.dockerconfigjson': 'operator-provisioned' },+ })+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-foreign')+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ const raw = (await mock.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)) as {+ data: Record<string, string>+ }+ expect(raw.data['.dockerconfigjson']).toBe('operator-provisioned') // unchanged+ })++ it('repairs a present-but-empty Secret via update', async () => {+ const { gateway, mock } = gw()+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: { 'clerum.io/managed-by': 'control-api' },+ data: {},+ })+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('repaired')+ expect(mintOrgPullCredential).toHaveBeenCalledOnce()+ expect((await decodeDockercfg(mock)).password).toBe('efrk_test_key')+ })++ it('aborts without minting when the read fails with a non-404 (e.g. 403)', async () => {+ const { gateway, mock } = gw()+ vi.spyOn(mock, 'getSecret').mockRejectedValue(+ Object.assign(new Error('forbidden'), { statusCode: 403, code: 403 })+ )+ await expect(ensureRegistryPullSecret(gateway, NS)).rejects.toMatchObject({ statusCode: 403 })+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })+})diff --git a/docs/how-to/connect-to-registry.md b/docs/how-to/connect-to-registry.mdindex 0c48eaea5..5024fd121 100644--- a/docs/how-to/connect-to-registry.md+++ b/docs/how-to/connect-to-registry.md@@ -71,6 +71,13 @@ 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.+**Creating and managing API keys** (`efrk_` org keys, used for CI and otherprogrammatic publishing) needs registry authentication active. In self-hosted,connecting is sufficient: authentication turns on automatically the moment