Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): harden pull-secret self-provisioning after deep review
Jose Ramirez200d3a0147de
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex f52b8d497..e274676d8 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.398",+ "version": "0.1.399","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.398",+ "version": "0.1.399","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 a85e64e68..342e9df2e 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.398",+ "version": "0.1.399","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/registry.ts b/control-api/src/routes/admin/registry.tsindex 7889cbd76..3ee84c9b6 100644--- a/control-api/src/routes/admin/registry.ts+++ b/control-api/src/routes/admin/registry.ts@@ -34,6 +34,10 @@ import {uploadArtifacts,} from '../../services/registryClient.js'import { isRegistryAuthActive } from '../../services/registryConnectionDb.js'+import {+ PullSecretProvisionError,+ ensureRegistryPullSecret,+} from '../../services/registryPullSecretService.js'import {validateWorkflowRecipeEgressPreflight,validateWorkflowRecipeLimits,@@ -43,7 +47,6 @@ 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). */@@ -301,6 +304,56 @@ async function loadRegistryCredentialSchema(entry: {}}+/**+ * Map an image-pull-secret provisioning failure onto an actionable HTTP response.+ *+ * The three classes are meaningfully different to an operator, and collapsing them all to+ * a bare 500 (as a generic K8s-error mapping does — `extractK8sError` cannot read+ * `RegistryProxyError.status`) makes a deploy-ordering or connect-flow problem look like a+ * control-api bug:+ * - PullSecretProvisionError → a precondition the operator can fix (wrong namespace,+ * registry not connected, org not yet bound); carries its own status + reason code.+ * - RegistryProxyError → the registry rejected us (e.g. 403 because the+ * pull-credential endpoint has not been upgraded, or this client lacks+ * `registry:manage-keys`); surfaced as 502 with the upstream status.+ * - anything else → 500.+ */+function pullSecretErrorResponse(err: unknown): {+ status: number+ body: Record<string, unknown>+} {+ if (err instanceof PullSecretProvisionError) {+ return {+ status: err.status,+ body: {+ error: 'registry_pull_secret_provision_failed',+ reason: err.reason,+ detail: err.message,+ },+ }+ }+ if (err instanceof RegistryProxyError) {+ return {+ status: 502,+ body: {+ error: 'registry_pull_secret_provision_failed',+ reason: 'registry_rejected',+ upstreamStatus: err.status,+ detail: `the registry rejected the image-pull credential request (${err.status}); confirm the registry supports tenant pull-credential minting and that this deployment holds registry:manage-keys`,+ },+ }+ }+ const k8sErr = extractK8sError(err)+ return {+ status: 500,+ body: {+ error: 'registry_pull_secret_provision_failed',+ reason: 'unexpected_error',+ detail: k8sErr?.message || (err instanceof Error ? err.message : 'unknown error'),+ },+ }+}+/** Audit log for security-sensitive operations (finding #10). */function auditLog(action: string, details: Record<string, unknown>): void {const safe: Record<string, unknown> = { timestamp: new Date().toISOString(), action, ...details }@@ -1224,11 +1277,8 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {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'),- })+ const mapped = pullSecretErrorResponse(err)+ res.status(mapped.status).json(mapped.body)return}}@@ -1836,21 +1886,6 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {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,@@ -1860,6 +1895,20 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {return}+ // Ensure the shared pull secret exists before the CRD update references it+ // (self-hosted self-provision; namespace-shared, idempotent, fail-loud). Runs+ // AFTER preflight — matching install — so a request that will 422 never mints a+ // rotate-on-call credential.+ if (attachEvenfirePullSecret) {+ try {+ await ensureRegistryPullSecret(gateway, namespace)+ } catch (err) {+ const mapped = pullSecretErrorResponse(err)+ res.status(mapped.status).json(mapped.body)+ return+ }+ }+// 4. Update credentials if providedlet previousSecretSnapshot: SecretSnapshot | null = nulllet secretCreatedDuringUpgrade = falsediff --git a/control-api/src/services/registryClient.ts b/control-api/src/services/registryClient.tsindex 3d4fa42c7..3f42f40fa 100644--- a/control-api/src/services/registryClient.ts+++ b/control-api/src/services/registryClient.ts@@ -606,12 +606,21 @@ export async function createOrgGrant(* 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.+ *+ * Carries an explicit timeout: `authedFetch` only bounds GETs, and this POST sits on the+ * install path behind an in-process dedupe — a stalled origin would otherwise hang every+ * concurrent install for that namespace. The response is validated because a missing+ * `key` would otherwise render a valid-LOOKING dockerconfigjson (`_:undefined`) that gets+ * written as a permanently unusable credential which later reads classify as healthy.*/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' }+ { method: 'POST', signal: AbortSignal.timeout(READ_TIMEOUT_MS) })+ if (!res || typeof res.key !== 'string' || res.key.length === 0) {+ throw new Error('registry returned no pull key for the image-pull credential')+ }return { key: res.key }}diff --git a/control-api/src/services/registryPullSecretService.ts b/control-api/src/services/registryPullSecretService.tsindex 8669c27be..158c461a0 100644--- a/control-api/src/services/registryPullSecretService.ts+++ b/control-api/src/services/registryPullSecretService.ts@@ -11,25 +11,44 @@* 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)+ * NOT the registry's token-issuer* label clerum.io/managed-by = control-api (ownership marker; absent ⇒ externally owned)+ *+ * 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.+ * 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+ * Secret on a revoked credential.*/+import { config } from '../config.js'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'+import type { SecretUpsertRequest } from '../types.js'+import { mintOrgPullCredential, resolvePublishScope } from './registryClient.js'+import { isRegistryAuthActive } from './registryConnectionDb.js'const logger = rootLogger.child({ module: 'registry-pull-secret' })+/**+ * Audit trail for minting + writing a registry credential, matching the `[AUDIT]` shape+ * the admin registry routes emit. NEVER include the key or the dockerconfigjson payload.+ */+function auditPullSecret(action: string, details: Record<string, unknown>): void {+ console.log(+ `[AUDIT] ${JSON.stringify({ timestamp: new Date().toISOString(), action, ...details })}`+ )+}+const MANAGED_BY_LABEL = 'clerum.io/managed-by'const MANAGED_BY_VALUE = 'control-api'const DOCKERCONFIG_KEY = '.dockerconfigjson'+const DOCKERCONFIG_TYPE = 'kubernetes.io/dockerconfigjson'export type EnsurePullSecretResult =| 'created'@@ -38,6 +57,23 @@ export type EnsurePullSecretResult =| 'exists-foreign'| 'skipped'+/**+ * Raised when the pull Secret cannot be provisioned but the caller is about to attach a+ * reference to it. The caller MUST fail the install rather than persist an McpServer+ * whose imagePullSecrets can never resolve — that is the silent ImagePullBackOff this+ * whole mechanism exists to remove.+ */+export class PullSecretProvisionError extends Error {+ constructor(+ message: string,+ readonly reason: string,+ readonly status: number = 500+ ) {+ super(message)+ this.name = 'PullSecretProvisionError'+ }+}+/** Extract an HTTP-ish status from a K8s client error (mirrors extractK8sError). */function k8sStatus(err: unknown): number | null {if (err && typeof err === 'object') {@@ -52,7 +88,7 @@ function k8sStatus(err: unknown): number | 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).+ * on its own token-issuer and cannot be trusted here.*/function buildDockerconfigjson(host: string, key: string): string {const auth = Buffer.from(`_:${key}`).toString('base64')@@ -60,18 +96,38 @@ function buildDockerconfigjson(host: string, key: string): string {return Buffer.from(JSON.stringify(cfg)).toString('base64')}+/**+ * True when the stored blob actually carries an entry for `host`. Presence alone is not+ * enough: a Secret minted before CLERUM_REGISTRY_URL changed is keyed on the old host and+ * the kubelet will never select it. Unparseable ⇒ false (treat as broken, repair it).+ */+function dockerconfigMatchesHost(blob: string | undefined, host: string): boolean {+ if (!blob) return false+ try {+ const parsed = JSON.parse(Buffer.from(blob, 'base64').toString('utf8')) as {+ auths?: Record<string, unknown>+ }+ return !!parsed?.auths && Object.prototype.hasOwnProperty.call(parsed.auths, host)+ } catch {+ return false+ }+}+interface SecretView {labels: Record<string, string>+ type: string | undefineddockerconfig: string | undefined}function readSecret(raw: unknown): SecretView {const s = (raw ?? {}) as {metadata?: { labels?: Record<string, string> }+ type?: stringdata?: Record<string, string>}return {labels: s.metadata?.labels ?? {},+ type: s.type,dockerconfig: s.data?.[DOCKERCONFIG_KEY],}}@@ -80,7 +136,7 @@ function buildSecretReq(targetNs: string, dockerconfigjson: string): SecretUpserreturn {name: EVENFIRE_REGISTRY_PULL_SECRET_NAME,namespace: targetNs,- type: 'kubernetes.io/dockerconfigjson',+ type: DOCKERCONFIG_TYPE,labels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE },data: { [DOCKERCONFIG_KEY]: dockerconfigjson },}@@ -91,21 +147,20 @@ async function mintAndBuild(orgName: string, host: string): Promise<string> {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.+// Collapse concurrent ensures for the same (namespace, secret) WITHIN this replica so two+// in-flight installs cannot both mint. Cross-replica races are bounded by the registry's+// rotate-on-call (<=1 active pull key per org) plus the read-before-mint discipline below:+// the loser of a create race re-reads and adopts the winner's Secret instead of minting.const inflight = new Map<string, Promise<EnsurePullSecretResult>>()/*** 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.+ * pull-only credential only when it is absent or verifiably broken.*- * THROWS on mint/write failure so the caller can fail the install loudly rather than- * attach an unresolvable imagePullSecrets reference.+ * Returns `'skipped'` ONLY when provisioning is legitimately not our job (managed mode,+ * where the operator owns the Secret) or when no registry host is configured. Every other+ * "cannot provision" condition THROWS `PullSecretProvisionError` so the caller fails the+ * install loudly instead of attaching an unresolvable imagePullSecrets reference.*/export function ensureRegistryPullSecret(gateway: K8sGateway,@@ -119,41 +174,79 @@ export function ensureRegistryPullSecret(return run}-async function ensureInner(- gateway: K8sGateway,- targetNs: string-): Promise<EnsurePullSecretResult> {- // ── Gate: only self-hosted, connected, with a resolvable org ──────────────+async function ensureInner(gateway: K8sGateway, targetNs: string): Promise<EnsurePullSecretResult> {+ // ── Legitimate no-ops ─────────────────────────────────────────────────────+ // Managed clusters: the operator owns this Secret; never contend with it.if (config.registryConnectionMode !== 'self-hosted') return 'skipped'const host = registryHostFromUrl(config.registryUrl)- if (!host) return 'skipped'- if (!(await isRegistryAuthActive())) return 'skipped'- const { orgName } = await resolvePublishScope()+ if (!host) return 'skipped' // no registry configured; the attach predicate is false too++ // ── Hard preconditions: from here on we MUST provision or fail loudly ─────+ // The pull Secret is a registry credential. Confine writes to the namespace this+ // deployment actually serves so a caller-supplied `body.namespace` cannot plant it+ // in an unrelated namespace (and cannot rotate the org key as a side effect).+ if (targetNs !== config.mcpServersNamespace) {+ throw new PullSecretProvisionError(+ `refusing to provision the registry pull secret outside the configured plugin namespace (got "${targetNs}", expected "${config.mcpServersNamespace}")`,+ 'unsupported_namespace',+ 400+ )+ }+ if (!(await isRegistryAuthActive())) {+ throw new PullSecretProvisionError(+ 'registry connection is not active; complete the registry connect flow before installing a private plugin',+ 'registry_not_connected',+ 409+ )+ }+ // A cold-started control-api can cache a null org from before the registry bound this+ // client. Force one refresh before failing, mirroring the self-service key routes.+ let { orgName } = await resolvePublishScope()+ if (!orgName) ({ orgName } = await resolvePublishScope({ force: true }))if (!orgName) {- logger.warn(- { targetNs },- 'registry pull secret: org not resolved (connect flow incomplete); skipping'+ throw new PullSecretProvisionError(+ 'registry has not bound this deployment to an organization yet; cannot mint an image-pull credential',+ 'org_unresolved',+ 409)- 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- }+ const current = await readCurrent(gateway, targetNs)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)))+ // INVARIANT 1: never write a Secret we do not own — even a broken one. Adopting it+ // would seize an external operator's credential; repairing it in place would rotate+ // the org key out from under them.+ if (!ours) {+ if (!dockerconfigMatchesHost(current.dockerconfig, host)) {+ logger.warn(+ { targetNs, host },+ 'externally-owned evenfire-registry-pull Secret is missing or mis-keyed; leaving it untouched (remove it to let control-api provision one)'+ )+ }+ return 'exists-foreign'+ }+ // Ours and genuinely usable → reuse. Presence alone is not enough: a blob keyed on a+ // previous registry host can never be selected by the kubelet.+ if (current.type === DOCKERCONFIG_TYPE && dockerconfigMatchesHost(current.dockerconfig, host)) {+ return 'exists-ours'+ }+ // Ours but broken. `Secret.type` is immutable, so a wrong-typed Secret must be+ // recreated. Delete FIRST so a failed delete cannot strand a freshly-minted key.+ if (current.type !== DOCKERCONFIG_TYPE) {+ await gateway.deleteSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, targetNs)+ await gateway.createSecret(buildSecretReq(targetNs, await mintAndBuild(orgName, host)))+ } else {+ await gateway.updateSecret(buildSecretReq(targetNs, await mintAndBuild(orgName, host)))+ }logger.info({ targetNs, orgName }, 'registry pull secret repaired')+ auditPullSecret('registry_pull_secret_provisioned', {+ namespace: targetNs,+ org: orgName,+ outcome: 'repaired',+ })return 'repaired'}@@ -161,15 +254,31 @@ async function ensureInner(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+ if (k8sStatus(err) !== 409) throw err+ // Lost a concurrent create race. Do NOT mint again — a second mint would revoke the+ // key the winner just stored. Re-read and adopt whatever is now there.+ const winner = await readCurrent(gateway, targetNs)+ if (!winner) throw err // vanished again; surface rather than loop+ const winnerOurs = winner.labels[MANAGED_BY_LABEL] === MANAGED_BY_VALUE+ if (!winnerOurs) return 'exists-foreign'+ logger.info({ targetNs, orgName }, 'registry pull secret already created concurrently')+ return 'exists-ours'}logger.info({ targetNs, orgName }, 'registry pull secret created')+ auditPullSecret('registry_pull_secret_provisioned', {+ namespace: targetNs,+ org: orgName,+ outcome: 'created',+ })return 'created'}++/** Read the Secret, mapping 404 to null. Any other error propagates (e.g. 403 = wrong ns). */+async function readCurrent(gateway: K8sGateway, targetNs: string): Promise<SecretView | null> {+ try {+ return readSecret(await gateway.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, targetNs))+ } catch (err) {+ if (k8sStatus(err) === 404) return null+ throw err+ }+}diff --git a/control-api/test/registryPullSecretService.test.ts b/control-api/test/registryPullSecretService.test.tsindex afe3ebbaa..78d789d8c 100644--- a/control-api/test/registryPullSecretService.test.ts+++ b/control-api/test/registryPullSecretService.test.ts@@ -1,8 +1,14 @@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'+import { mintOrgPullCredential, resolvePublishScope } from '../src/services/registryClient.js'+import { isRegistryAuthActive } from '../src/services/registryConnectionDb.js'+import {+ PullSecretProvisionError,+ ensureRegistryPullSecret,+} from '../src/services/registryPullSecretService.js'+import { MockGateway } from './mockGateway.js'vi.mock('../src/services/registryConnectionDb.js', () => ({isRegistryAuthActive: vi.fn(),@@ -12,33 +18,41 @@ vi.mock('../src/services/registryClient.js', () => ({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'+const HOST = 'registry.evenfire.ai'+const DOCKERCONFIG_KEY = '.dockerconfigjson'+const OURS = { 'clerum.io/managed-by': 'control-api' }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(+/** Encode a dockerconfigjson blob keyed on `host`, matching what the realm expects. */+function encodeDockercfg(host: string, key: string): string {+ const auth = Buffer.from(`_:${key}`).toString('base64')+ return Buffer.from(+ JSON.stringify({ auths: { [host]: { username: '_', password: key, auth } } })+ ).toString('base64')+}++async function readStored(mock: MockGateway-): Promise<{ host: string; username: string; password: string }> {+): Promise<{ type?: string; labels: Record<string, string>; blob?: string }> {const raw = (await mock.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)) as {+ metadata?: { labels?: Record<string, string> }type?: stringdata?: 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 }>+ return { type: raw.type, labels: raw.metadata?.labels ?? {}, blob: raw.data?.[DOCKERCONFIG_KEY] }+}++function decodeHosts(blob: string | undefined): string[] {+ if (!blob) return []+ const parsed = JSON.parse(Buffer.from(blob, 'base64').toString('utf8')) as {+ auths: Record<string, unknown>}- const host = Object.keys(parsed.auths)[0]!- return { host, username: parsed.auths[host]!.username, password: parsed.auths[host]!.password }+ return Object.keys(parsed.auths)}let savedMode: typeof config.registryConnectionMode@@ -49,9 +63,13 @@ beforeEach(() => {savedMode = config.registryConnectionModesavedUrl = config.registryUrlconfig.registryConnectionMode = 'self-hosted'- config.registryUrl = 'https://registry.evenfire.ai'+ config.registryUrl = `https://${HOST}`vi.mocked(isRegistryAuthActive).mockResolvedValue(true)- vi.mocked(resolvePublishScope).mockResolvedValue({ curator: false, orgName: 'acme', scope: '@acme' })+ vi.mocked(resolvePublishScope).mockResolvedValue({+ curator: false,+ orgName: 'acme',+ scope: '@acme',+ })vi.mocked(mintOrgPullCredential).mockResolvedValue({ key: 'efrk_test_key' })})@@ -60,85 +78,180 @@ afterEach(() => {config.registryUrl = savedUrl})-describe('ensureRegistryPullSecret', () => {- it('skips (no mint) in managed mode', async () => {+describe('ensureRegistryPullSecret — legitimate no-ops', () => {+ it('skips (no mint) in managed mode — the operator owns the Secret', 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)+ it('skips when no registry host is configured', async () => {+ config.registryUrl = ''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 () => {+describe('ensureRegistryPullSecret — fails loudly instead of silently skipping', () => {+ it('throws (not skips) when the registry connection is inactive', async () => {+ vi.mocked(isRegistryAuthActive).mockResolvedValue(false)+ const { gateway } = gw()+ await expect(ensureRegistryPullSecret(gateway, NS)).rejects.toBeInstanceOf(+ PullSecretProvisionError+ )+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('throws when the org cannot be resolved even after a forced refresh', async () => {vi.mocked(resolvePublishScope).mockResolvedValue({ curator: false, orgName: null, scope: null })const { gateway } = gw()- await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('skipped')+ await expect(ensureRegistryPullSecret(gateway, NS)).rejects.toMatchObject({+ reason: 'org_unresolved',+ })+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ })++ it('recovers from a stale cached null org by forcing one refresh', async () => {+ vi.mocked(resolvePublishScope)+ .mockResolvedValueOnce({ curator: false, orgName: null, scope: null })+ .mockResolvedValueOnce({ curator: false, orgName: 'acme', scope: '@acme' })+ const { gateway } = gw()+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('created')+ expect(resolvePublishScope).toHaveBeenNthCalledWith(2, { force: true })+ expect(mintOrgPullCredential).toHaveBeenCalledWith('acme')+ })++ it('refuses to write the credential outside the configured plugin namespace', async () => {+ const { gateway } = gw()+ await expect(ensureRegistryPullSecret(gateway, 'channels')).rejects.toMatchObject({+ reason: 'unsupported_namespace',+ status: 400,+ })expect(mintOrgPullCredential).not.toHaveBeenCalled()})- it('mints and creates the Secret when absent, keyed on the registryUrl host', async () => {+ 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()+ })++ it('propagates a mint failure and writes nothing', async () => {+ vi.mocked(mintOrgPullCredential).mockRejectedValue(new Error('registry returned no pull key'))+ const { gateway, mock } = gw()+ const createSpy = vi.spyOn(mock, 'createSecret')+ await expect(ensureRegistryPullSecret(gateway, NS)).rejects.toThrow(/no pull key/)+ expect(createSpy).not.toHaveBeenCalled()+ })+})++describe('ensureRegistryPullSecret — provisioning', () => {+ it('mints and creates the Secret when absent, keyed on the image 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')+ const stored = await readStored(mock)+ expect(stored.type).toBe('kubernetes.io/dockerconfigjson')+ expect(stored.labels['clerum.io/managed-by']).toBe('control-api')+ // Keyed on OUR image host, never the registry's token issuer.+ expect(decodeHosts(stored.blob)).toEqual([HOST])})- it('reuses our existing Secret without minting', async () => {+ 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: { 'clerum.io/managed-by': 'control-api' },- data: { '.dockerconfigjson': 'existing' },+ labels: OURS,+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_live') },})await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-ours')expect(mintOrgPullCredential).not.toHaveBeenCalled()})- it('leaves a foreign (unlabeled) Secret untouched', async () => {+ it('repairs our Secret when the blob is keyed on a STALE host (registry URL changed)', async () => {const { gateway, mock } = gw()mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {type: 'kubernetes.io/dockerconfigjson',- data: { '.dockerconfigjson': 'operator-provisioned' },+ labels: OURS,+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg('old-registry.example.com', 'efrk_stale') },})- 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+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('repaired')+ expect(decodeHosts((await readStored(mock)).blob)).toEqual([HOST])})- it('repairs a present-but-empty Secret via update', async () => {+ it('repairs our Secret when the payload is missing', async () => {const { gateway, mock } = gw()mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {type: 'kubernetes.io/dockerconfigjson',- labels: { 'clerum.io/managed-by': 'control-api' },+ labels: OURS,data: {},})await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('repaired')- expect(mintOrgPullCredential).toHaveBeenCalledOnce()- expect((await decodeDockercfg(mock)).password).toBe('efrk_test_key')+ expect(decodeHosts((await readStored(mock)).blob)).toEqual([HOST])})- it('aborts without minting when the read fails with a non-404 (e.g. 403)', async () => {+ it('recreates our Secret when the type is wrong (Secret.type is immutable)', async () => {const { gateway, mock } = gw()- vi.spyOn(mock, 'getSecret').mockRejectedValue(- Object.assign(new Error('forbidden'), { statusCode: 403, code: 403 })+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'Opaque',+ labels: OURS,+ data: {},+ })+ const deleteSpy = vi.spyOn(mock, 'deleteSecret')+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('repaired')+ // An in-place update of `type` would 422, so it must delete first — and the delete+ // must precede the mint so a failed delete cannot strand a freshly-rotated key.+ expect(deleteSpy).toHaveBeenCalledWith(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)+ expect(deleteSpy.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(mintOrgPullCredential).mock.invocationCallOrder[0])- await expect(ensureRegistryPullSecret(gateway, NS)).rejects.toMatchObject({ statusCode: 403 })+ expect((await readStored(mock)).type).toBe('kubernetes.io/dockerconfigjson')+ })+})++describe('ensureRegistryPullSecret — never touches a Secret we do not own', () => {+ it('leaves a foreign Secret WITH data untouched', async () => {+ const { gateway, mock } = gw()+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ data: { [DOCKERCONFIG_KEY]: 'operator-provisioned' },+ })+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-foreign')+ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ expect((await readStored(mock)).blob).toBe('operator-provisioned')+ })++ it('leaves a foreign EMPTY Secret untouched (never seizes ownership)', async () => {+ const { gateway, mock } = gw()+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, { type: 'Opaque', data: {} })+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-foreign')expect(mintOrgPullCredential).not.toHaveBeenCalled()+ const stored = await readStored(mock)+ expect(stored.type).toBe('Opaque')+ expect(stored.labels['clerum.io/managed-by']).toBeUndefined()+ })+})++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 () => {+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: OURS,+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_winner') },+ })+ throw Object.assign(new Error('already exists'), { statusCode: 409, code: 409 })+ })+ await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('exists-ours')+ // Exactly ONE mint — a second would revoke the key the winner just stored.+ expect(mintOrgPullCredential).toHaveBeenCalledTimes(1)+ expect(decodeHosts((await readStored(mock)).blob)).toEqual([HOST])})})diff --git a/control-api/test/routes.registryInstall.pullSecret.test.ts b/control-api/test/routes.registryInstall.pullSecret.test.tsnew file mode 100644index 000000000..761e71a4d--- /dev/null+++ b/control-api/test/routes.registryInstall.pullSecret.test.ts@@ -0,0 +1,220 @@+/**+ * Route-level coverage for image-pull-secret self-provisioning on the install path.+ *+ * 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:+ * - 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+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import request from 'supertest'+import { config } from '../src/config.js'+import { createAdminRegistryRouter } from '../src/routes/admin/registry.js'+import { EVENFIRE_REGISTRY_PULL_SECRET_NAME } from '../src/routes/admin/registryImagePullSecret.js'+import {+ getCredentialSchema,+ getDigest,+ getEntryVersion,+ mintOrgPullCredential,+ reportInstall,+ resolvePublishScope,+} from '../src/services/registryClient.js'+import { isRegistryAuthActive } from '../src/services/registryConnectionDb.js'+import { MockGateway } from './mockGateway.js'++vi.mock('node:dns/promises', () => ({+ lookup: vi.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),+}))+vi.mock('../src/services/registryClient.js', () => ({+ searchEntries: vi.fn(),+ getEntry: vi.fn(),+ getEntryVersion: vi.fn(),+ getCredentialSchema: vi.fn(),+ getCategories: vi.fn(),+ reportInstall: vi.fn(),+ downloadBundle: vi.fn(),+ getDigest: vi.fn(),+ uploadArtifacts: vi.fn(),+ updateVersionMetadata: vi.fn(),+ deleteVersion: vi.fn(),+ publishEntry: vi.fn(),+ resolvePublishScope: vi.fn(),+ applyPublishScope: vi.fn((name?: string) => name),+ mintOrgPullCredential: vi.fn(),+ RegistryProxyError: class RegistryProxyError extends Error {+ constructor(+ readonly status: number,+ readonly body: unknown+ ) {+ super(`Registry ${status}`)+ this.name = 'RegistryProxyError'+ }+ },+}))+vi.mock('../src/services/registryConnectionDb.js', async importOriginal => ({+ ...(await importOriginal<typeof import('../src/services/registryConnectionDb.js')>()),+ isRegistryAuthActive: vi.fn(),+}))++const REGISTRY_HOST = 'registry.evenfire.ai'+const NS = 'mcp-server'++function makeApp(gateway: MockGateway) {+ const app = express()+ app.use(express.json())+ app.use(createAdminRegistryRouter(gateway as unknown as import('../src/k8s.js').K8sGateway))+ app.use(+ (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {+ res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })+ }+ )+ return app+}++function makeInstallApp() {+ const gw = new MockGateway(NS)+ gw.createResource('contexts', {+ metadata: { name: 'default-context' },+ spec: { contextId: 'default-context', mcpServers: [] },+ })+ return { app: makeApp(gw), gw }+}++/** A local-mode entry whose image lives on the configured evenfire registry. */+function evenfireEntry(overrides: Record<string, unknown> = {}) {+ return {+ id: '1',+ name: 'forecast',+ version: '1.0.0',+ entry_type: 'mcp-server',+ description: 'Forecast MCP',+ author: 'acme',+ server_mode: 'local' as const,+ transport: 'streamableHttp',+ mcp_server_meta: { imageRef: `${REGISTRY_HOST}/acme/forecast:1.2.3`, port: 3000 },+ ...overrides,+ }+}++function installBody() {+ return {+ serverName: 'forecast',+ contextRef: 'default-context',+ registryEntryName: 'forecast',+ registryEntryVersion: '1.0.0',+ }+}++let savedMode: typeof config.registryConnectionMode+let savedUrl: string++beforeEach(() => {+ vi.resetAllMocks()+ savedMode = config.registryConnectionMode+ savedUrl = config.registryUrl+ ;(config as { registryConnectionMode: string }).registryConnectionMode = 'self-hosted'+ ;(config as { registryUrl: string }).registryUrl = `https://${REGISTRY_HOST}`++ vi.mocked(getDigest).mockResolvedValue({ digest: null })+ // No credentials required — proves provisioning is NOT gated on `credRequired`.+ vi.mocked(getCredentialSchema).mockResolvedValue({+ required: false,+ authType: 'none',+ keys: [],+ } as never)+ vi.mocked(reportInstall).mockResolvedValue({ acknowledged: true, stored: true } as never)+ vi.mocked(isRegistryAuthActive).mockResolvedValue(true)+ vi.mocked(resolvePublishScope).mockResolvedValue({+ curator: false,+ orgName: 'acme',+ scope: '@acme',+ } as never)+ vi.mocked(mintOrgPullCredential).mockResolvedValue({ key: 'efrk_route_key' } as never)+})++afterEach(() => {+ ;(config as { registryConnectionMode: string }).registryConnectionMode = savedMode+ ;(config as { registryUrl: string }).registryUrl = savedUrl+})++describe('POST /admin/registry/install — pull-secret provisioning (self-hosted)', () => {+ it('provisions the pull Secret for a credential-less private plugin', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(evenfireEntry() as never)+ const { app, gw } = makeInstallApp()++ await request(app).post('/admin/registry/install').send(installBody()).expect(201)++ // The Secret must exist in the plugin namespace, keyed on the image host.+ const secret = (await gw.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)) as {+ type?: string+ data?: Record<string, string>+ }+ expect(secret.type).toBe('kubernetes.io/dockerconfigjson')+ const blob = JSON.parse(+ Buffer.from(secret.data?.['.dockerconfigjson'] as string, 'base64').toString('utf8')+ ) as { auths: Record<string, unknown> }+ expect(Object.keys(blob.auths)).toEqual([REGISTRY_HOST])++ // ...and the CRD must reference it.+ 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('fails the install loudly and persists NO McpServer when minting fails', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(evenfireEntry() as never)+ vi.mocked(mintOrgPullCredential).mockRejectedValueOnce(new Error('registry unavailable'))+ const { app, gw } = makeInstallApp()++ const res = await request(app).post('/admin/registry/install').send(installBody())+ expect(res.status).toBeGreaterThanOrEqual(500)+ expect(res.body.error).toBe('registry_pull_secret_provision_failed')++ // Nothing may be persisted — an McpServer referencing an absent Secret is exactly the+ // silent ImagePullBackOff this mechanism exists to prevent.+ await expect(gw.getResource('mcpservers', 'forecast', NS)).rejects.toBeTruthy()+ })++ it('surfaces an actionable error when the deployment has no org bound yet', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(evenfireEntry() as never)+ vi.mocked(resolvePublishScope).mockResolvedValue({+ curator: false,+ orgName: null,+ scope: null,+ } 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: 'org_unresolved',+ })+ await expect(gw.getResource('mcpservers', 'forecast', NS)).rejects.toBeTruthy()+ })++ it('does not provision for an image that is not evenfire-hosted', 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()++ await request(app).post('/admin/registry/install').send(installBody()).expect(201)++ expect(mintOrgPullCredential).not.toHaveBeenCalled()+ await expect(gw.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)).rejects.toBeTruthy()+ const mcp = (await gw.getResource('mcpservers', 'forecast', NS)) as {+ spec: { imagePullSecrets?: unknown }+ }+ expect(mcp.spec.imagePullSecrets).toBeUndefined()+ })+})diff --git a/docs/architecture/registry-pull-secret-self-provisioning.md b/docs/architecture/registry-pull-secret-self-provisioning.mdindex 246aa0032..717d48278 100644--- a/docs/architecture/registry-pull-secret-self-provisioning.md+++ b/docs/architecture/registry-pull-secret-self-provisioning.md@@ -470,16 +470,21 @@ never for an `'exists-ours'`/`'exists-foreign'` hit.### 7.6 Rotation & lifecycle-- **Rotation & liveness.** `'exists-ours'` reuse (§7.1 step 2) serves the embedded- key indefinitely, so the key must not silently die. The pull key carries no- expiry (`mintPullKey` sets none), so reuse is safe by construction. Treat an- observed `401`/`ImagePullBackOff` (or an admin "re-provision" action) as the- reactive rotation trigger — which re-mints (the endpoint rotates the org's pull- key) and **replaces** the `'exists-ours'` Secret in place (never a foreign one). A- scheduled proactive rotation may be deferred, but the *reactive* trigger is- **required**, else a revoked-out-of-band key strands the cluster with no self-heal.- Posture in one line: *control-api owns rotation for Secrets it owns and never- touches a foreign Secret.*+- **Rotation & liveness.** The pull key carries no expiry (`mintPullKey` sets none), so+ reuse is safe by construction. `'exists-ours'` is **not** a presence-only check: the+ stored blob is decoded and its `auths` map must contain the currently-configured+ registry host, so a Secret minted before `CLERUM_REGISTRY_URL` changed is detected as+ broken and repaired on the next install. A wrong-`type` Secret is likewise detected and+ recreated (`Secret.type` is immutable, so an in-place update would 422).+ Posture in one line: *control-api owns rotation for Secrets it owns and never touches a+ foreign Secret.*++ **Not shipped (accepted gap):** there is no reactive trigger on an observed+ `401`/`ImagePullBackOff`, and no admin "re-provision" action. A key revoked+ **out-of-band** is therefore not self-healed — the stored blob still decodes and still+ matches the host, so it reads as healthy. Today's remedy is to delete the Secret and+ re-install, which re-provisions. A re-provision endpoint is the natural follow-up; it is+ deliberately out of scope here rather than documented as if it exists.- **GC.** Plugin uninstall deletes the per-plugin `<name>-credentials` Secret by nameand does **not** touch the shared pull Secret (§7.9) — correct, since other pluginsmay still need it. The Secret is therefore a standing namespace credential for the@@ -643,6 +648,17 @@ future scope.1. **Deploy the registry gate change (§6.2) first or together** — control-api's mint`403`s until the relaxed endpoint is live, so the `evenfire-registry` deploy mustland before (or with) the control-api rollout. Both are part of this release.++ > **Precondition the gate alone does not satisfy.** The relaxed endpoint authorizes on+ > `registry:manage-keys`, but only the registry's **auto-approve** path grants that+ > scope (`routes/deployments.ts`). A deployment approved through the **admin approve**+ > route (`POST /deployments/:id/approve`) falls back to `approveDeployment`'s default+ > scope set, which omits it — and the backfill migration is scoped+ > `WHERE created_by = 'mcc-admin'` while that path writes `created_by =+ > 'deployment-approval'`, so it is not covered either. Those deployments 403 forever+ > with no self-service remedy. **Registry-side fix required:** pass the same scope set+ > from the admin approve route and widen the backfill. Until then, self-provisioning+ > only works for auto-approved (open-registration) deployments.2. **Ship control-api self-provisioning** gated on `self-hosted`, with the comment/docscrub (§7.8). Managed clusters are inert (the managed operator keeps owning theSecret) — the mode gate guarantees no double-writer, so no cross-repo coordination