Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(e2e): prove the pull-secret chain against a live cluster
Jose Ramirez0cc1e969f747
diff --git a/docs/architecture/registry-pull-secret-recipe-workloads.md b/docs/architecture/registry-pull-secret-recipe-workloads.mdindex 24be1250f..a9b50df98 100644--- a/docs/architecture/registry-pull-secret-recipe-workloads.md+++ b/docs/architecture/registry-pull-secret-recipe-workloads.md@@ -1,13 +1,15 @@# Platform image-pull credentials for recipe workloads**Status:** Implemented in PR #243. Five blocking review findings were raised against it-(§13); **the four P1s are fixed** — including §13.1, which reversed this document's-install-time trigger decision (provisioning is now a standing invariant, because a-`WorkflowRecipe` can be created without control-api while WRC injects the pull-secret-reference regardless). **§13.5 — end-to-end runtime evidence — remains open and is the-last acceptance gate.** Two earlier carve-outs also remain recorded in place: WRC injection-is deliberately **not** mode-gated, so the operator contract changes on managed clusters-too (§9), and the `POST /admin/recipes/secrets` `Opaque` fix (§6.5) did **not** ship.+(§13); **all five are now closed** — the four P1s in code, including §13.1, which reversed+this document's install-time trigger decision (provisioning is now a standing invariant,+because a `WorkflowRecipe` can be created without control-api while WRC injects the+pull-secret reference regardless); and **§13.5, the runtime acceptance gate, by a live+cluster E2E: `tests/e2e/integration/registry-pull-secret-runtime.test.ts`** (§11, §13.5).+Two earlier carve-outs remain recorded in place and are still true: WRC injection is+deliberately **not** mode-gated, so the operator contract changes on managed clusters too+(§9), and the `POST /admin/recipes/secrets` `Opaque` fix (§6.5) did **not** ship — the+third-party BYO-registry path is still the silent failure described there.**Date:** 2026-08-04**Area:** control-api · workflow-recipes (WRC) · workflow-runtime-core · image pull · self-hosted**Follows:** [`registry-pull-secret-self-provisioning.md`](registry-pull-secret-self-provisioning.md)@@ -165,7 +167,7 @@ platform removes the reference to it.the managed operator keeps owning provisioning on its clusters. Note this is a non-goalfor the *write* side only — WRC's **injection** is not mode-gated and therefore doeschange what the managed operator must provision (§9).-- Reactive rotation of an out-of-band-revoked key (still open from #243 §12-2), though+- Reactive rotation of an out-of-band-revoked key (still open — `registry-pull-secret-self-provisioning.md` §12-1), though§6.3's fingerprint makes cross-namespace divergence detectable.---@@ -229,19 +231,28 @@ Both enforcement points get the injection, since both produce runnable specs:| Pod template | `resourceBuilder.ts` (after the `allowedPullSecrets` filter) | recipe workloads in any namespace || McpServer delegation | `mcpDelegation.ts` (after `projectableImagePullSecrets`) | transport workloads → `McpServer` → HCC |-**Reserved-name handling — NOT shipped in #243** (still §12-2). The intent: if a recipe-explicitly declares the platform name, injection makes it redundant, so recipe validation-should **reject** the reserved name with a message saying it is platform-managed — fail-loudly rather than appear to honor a declaration we ignore.--What actually happens today, absent that validation, is *louder* than the "silent no-op"-this paragraph feared: the #637 gate classifies the declared name `denied`, which makes the-whole **workload** denied (`workflowRecipeReconciler.ts`, `collectSecretOwnership` counts-`imagePullSecrets` refs alongside `envSecret`), so the workload is **not rendered at all** —-it is torn down and reported `EnvSecretOwnershipDenied`. A recipe must therefore *not* name-the reserved Secret. The injection sites still normalize the name defensively (§11), because-the builders are re-entered with a denied access map on the StatefulSet revocation-re-render path.+**Reserved-name handling — SHIPPED in #243** (§12-2, resolved; R5). If a recipe explicitly+declares the platform name, injection makes it redundant, so recipe validation **rejects**+the reserved name with a message saying it is platform-managed — failing loudly rather than+appearing to honor a declaration we ignore. As built:+`isPlatformManagedWorkflowSecretName` (`control-api/src/routes/admin/recipes.ts`) reserves+`EVENFIRE_REGISTRY_PULL_SECRET_NAME` alongside the `wf-` prefix, and `/validate`, POST, PUT+and `POST /admin/recipes/secrets` all reject the declaration at admission with a+`RefReserved` rule.++> An earlier revision of this section recorded the validation as *not shipped* while §12-2+> and R5 recorded it as shipped. That contradiction was flagged in review (P2) and is+> resolved here in favour of the source: the reservation is live.++The #637 gate stays behind that validation as defense-in-depth for anything already+persisted, and its behavior is *louder* than the "silent no-op" the validation was meant to+prevent: the gate classifies the declared name `denied`, which makes the whole **workload**+denied (`workflowRecipeReconciler.ts`, `collectSecretOwnership` counts `imagePullSecrets`+refs alongside `envSecret`), so the workload is **not rendered at all** — it is torn down and+reported `EnvSecretOwnershipDenied`. A recipe must therefore not name the reserved Secret by+either route. The injection sites still normalize the name defensively (§11), because the+builders are re-entered with a denied access map on the StatefulSet revocation re-render+path.### 6.2 One source of truth, in `@clerum/workflow-runtime-core`@@ -541,10 +552,10 @@ working immediately.| # | Risk | Mitigation || --- | --- | --- |-| R1 | Per-namespace minting revokes other namespaces' keys → partial cluster-wide `ImagePullBackOff`. | Single mint + fan-out write (§6.3); post-condition asserted in tests. |-| R2 | Partial write (mint OK, one namespace fails) leaves a stale, undetectable key. | Fingerprint annotation makes divergence detectable and repairable (§6.3). |+| R1 | Per-namespace minting revokes other namespaces' keys → partial cluster-wide `ImagePullBackOff`. | Single mint + fan-out write (§6.3); post-condition asserted in unit tests, and on a live cluster by the E2E's one-fingerprint-across-all-copies assertion (§11) — divergent fingerprints are the only symptom this failure has. |+| R2 | Partial write (mint OK, one namespace fails) leaves a stale, undetectable key. | Fingerprint annotation makes divergence detectable and repairable (§6.3). **Observed working live** — an induced divergence was detected and converged on the next ensure pass; timestamps and fingerprints in §11. || R3 | WRC/control-api registry URL drift → recipe pods get no credential while MCP servers do. | **Was live, not hypothetical** — the shipped minikube overlay pinned WRC to the in-cluster registry while control-api used the shared one, so every recipe install hit it (found in live testing 2026-08-04). Closed in-repo: the **base** WRC Deployment now projects `control-api-config.CLERUM_REGISTRY_URL` via an `optional: true` `configMapKeyRef`, so every deployment built from `deploy/base` — including OSS self-hosted, the only mode where control-api provisioning actually runs — reads the same definition control-api does, and the minikube overlay no longer redeclares it (§6.2). Pinned by `workflow-recipes/tests/unit/workflow/deployManifest.test.ts`. Shared predicate alone was insufficient. **Residual:** the GCP dev/prod overlays and MCC tenant rendering live outside this repo and still set the value for both services independently (they agree today); and an overlay may still leave the key unset, which disables injection — WRC now emits a startup WARN naming that consequence instead of failing silently. Surfacing both values on a status/health endpoint is still worth doing. |-| R4 | Someone "fixes" #637 denial by labelling the Secret `shared`. | §5.1 recorded as an explicit, permanent non-goal; add a test asserting the Secret is NOT `shared`/`owner-recipe` labeled. |+| R4 | Someone "fixes" #637 denial by labelling the Secret `shared`. | §5.1 recorded as an explicit, permanent non-goal; the live-cluster E2E asserts the Secret carries neither `clerum.io/shared` nor `clerum.io/owner-recipe` in any platform namespace (§11), so a "fix" of this shape fails the acceptance gate. || R5 | A recipe declares the reserved name and expects it honored. | **Closed.** Validation rejection (§6.1) shipped: `isPlatformManagedWorkflowSecretName` now reserves `EVENFIRE_REGISTRY_PULL_SECRET_NAME`, so `/validate`, POST, PUT and `POST /admin/recipes/secrets` reject the declaration at admission with a reserved-name rule. The #637 gate stays behind it as defense-in-depth for anything already persisted. || R6 | Two extra copies of the credential. | Pull-only, org-scoped, no push; §8.2. |@@ -564,8 +575,45 @@ working immediately.- **Anti-exfiltration** — a recipe declaring the platform Secret as `envSecret` is `denied`(regression guard for §5.1); a test asserts the Secret carries neither `shared` nor`owner-recipe`.-- **e2e (minikube, self-hosted)** — install a recipe plugin with a private image; assert the- pod pulls; assert a mixed recipe (transport + non-transport) works in both namespaces.+- **e2e (minikube, self-hosted)** — **SHIPPED:**+ `tests/e2e/integration/registry-pull-secret-runtime.test.ts`, the §13.5 acceptance gate.+ Four blocks against a live cluster and the live registry:++ | Block | Asserts | Why a MockGateway cannot |+ | --- | --- | --- |+ | Secret placement | present in all three platform namespaces; `kubernetes.io/dockerconfigjson`; `managed-by=control-api`; `auths` keyed on the configured registry host; **one fingerprint across all copies**; neither `shared` nor `owner-recipe` | namespace + RBAC are real; the fingerprint check is the only cluster-visible symptom of R1 (three mints against a rotate-on-call registry) |+ | Materialization | WRC renders the recipe workload's PodTemplate with `imagePullSecrets: [evenfire-registry-pull]` while the CRD does **not** declare it (proving injection, not declaration); control-api writes the reference onto the `McpServer` CRD and HCC materializes it verbatim onto the Deployment it owns | the WRC and HCC reconcile hops, and the rollout, are outside any route test |+ | Pod readiness + real pull | image evicted from the node's docker cache first (`imagePullPolicy: IfNotPresent` would otherwise serve it from cache and exercise no credential); Pod Ready; the `Pulled` event says `Successfully pulled image … Image size: N bytes` and **not** `already present on machine` | proves the kubelet accepts the blob and the registry honors the minted key — both previously assumed from docs |+ | Pre-persistence failure | a foreign, unusable Secret planted in one namespace makes `install-recipe` return `409 foreign_secret_unusable` **and** leaves no `WorkflowRecipe` behind | the ordering of provision-then-persist only matters against a real API server |++ Guarded to **skip** (not fail) when the cluster, the port-forward, the admin credential,+ self-hosted mode, or the private fixtures are unavailable; everything it creates is+ prefixed `e2e-pullsecret-` and removed in `afterAll`, including an unconditional restore+ of the temporary foreign Secret.++ Two gaps it deliberately does not close. **The periodic reconcile (§13.1)** is not in the+ suite: `REGISTRY_PULL_SECRET_RECONCILE_INTERVAL_MS` defaults to 600 000 ms and shortening+ it needs a redeploy, so a committed E2E cannot wait for a tick. It was verified+ out-of-band on `clerum-test` instead — the `sandbox-ui` copy was deleted at 11:30:18Z and+ restored by the cron at 11:32:33Z with a fresh fingerprint and a+ `registry_pull_secret_reconciled` log line naming all three namespaces. **The+ `kubectl apply` creation path** is covered only indirectly: the suite proves the standing+ invariant is what makes it work (the Secret is present in every namespace before any+ particular install), not the apply itself.++ **R2's divergence repair was observed live during this work**, which is worth recording+ because it is otherwise only argued. A regression rehearsal left `sandbox-ui` holding a+ fingerprint (`dab2bc929d3d`) that disagreed with `mcp-server` / `sandbox-recipes`+ (`f64af065ebe4`). The next install's ensure pass detected it —+ `registry pull secret copies diverged across namespaces; re-minting to converge`+ (2026-08-04T12:37:38Z) — re-minted once and rewrote all three onto `f3170a6e0585`. The+ following run then took the no-mint path (`exists-ours`, fingerprint unchanged),+ confirming both halves of §6.3: converge when diverged, do nothing when already current.++ The suite is not in `DEFAULT_VITEST_SUITES` in `scripts/e2e/run-vitest-e2e.sh`, so it does+ not run in the default gate; invoke it by path. Adding it there is safe — it skips+ cleanly without the fixtures — and is worth doing when the fixtures become part of the+ seeded environment.---@@ -703,6 +751,16 @@ control-api already has Postgres, so `pg_advisory_lock` is the natural mechanismno dependency — mirroring what the registry itself does inside `mintPullKey`. Thein-process map stays as a cheap first-level dedupe.+**The overlap is observed, not argued.** During #243's live testing on `clerum-test`+(2026-08-04) a control-api rollout put two pods in `Running` simultaneously —+ReplicaSets `786f7dcb9` and `7b7746fdf9`, both serving, before the older was killed.+The finding was originally derived from the manifest (`replicas: 1` + default+`RollingUpdate` ⇒ transient two-pod overlap); this is the same shape happening in an+ordinary deploy on the deployed configuration. It is worth recording because the+counter-argument to §13.3 was that a single-replica Deployment makes the in-process+`inflight` map sufficient — which is true only between rollouts, and a rollout is+exactly when a boot-time provisioning pass runs.+### 13.4 [P1] ✅ SHIPPED — `upgrade-recipe` has no provisioning hook`POST /admin/registry/upgrade-recipe` (`control-api/src/routes/admin/registry.ts:2001`)@@ -717,22 +775,43 @@ fails at pull time, with a `200` on the API call.install-recipe placement. Fix it explicitly even once §13.1 lands: the reconcile is asafety net, not a substitute for failing the request that introduced the problem.-### 13.5 [Acceptance] ⏳ OPEN — No end-to-end runtime evidence--Coverage is unit- and route-level against `MockGateway`. Nothing exercises-`Secret → WRC → McpServer/HCC → Pod Ready → private image pull`.+### 13.5 [Acceptance] ✅ SHIPPED — End-to-end runtime evidence-Mutation testing sharpens this rather than substituting for it: it proves the tests fail-when the code breaks. It cannot prove the kubelet accepts the blob, that the type and data-key are what Kubernetes wants, that RBAC permits the write in `sandbox-ui`, or that the-registry honors the minted key at pull time. Those are assumptions verified only against+**The finding.** Coverage was unit- and route-level against `MockGateway`. Nothing+exercised `Secret → WRC → McpServer/HCC → Pod Ready → private image pull`. Mutation+testing sharpened that rather than substituting for it: it proves the tests fail when the+code breaks, but it cannot prove the kubelet accepts the blob, that the type and data key+are what Kubernetes wants, that RBAC permits the write in `sandbox-ui`, or that the+registry honors the minted key at pull time. Those were assumptions verified only againstdocs and source.-The dependency that made this untestable is gone: `evenfire-registry` #64 is merged and-deployed. **Remediation:** a minikube e2e against the live registry covering (a) an-MCP-server plugin, (b) a recipe plugin with a non-transport workload, (c) a recipe created-by `kubectl apply` (the §13.1 path), each asserting `Pod Ready` rather than just Secret-contents.+**Closed by** `tests/e2e/integration/registry-pull-secret-runtime.test.ts` — a live-cluster+suite against `clerum-test` and the live `registry.evenfire.ai`, run in+`REGISTRY_CONNECTION_MODE=self-hosted` against a connected org. Contents and per-block+rationale are in §11; the short version is the four things a mock could not reach:++| Assumption previously unverified | How the suite verifies it |+| --- | --- |+| the kubelet accepts the blob we write | a Pod pulls a private image with only this Secret referenced, after the image is evicted from the node |+| the type and data key are what Kubernetes wants | the Secret is read back as `kubernetes.io/dockerconfigjson` with `.dockerconfigjson`, and a pull actually succeeds through it |+| RBAC permits the write in `sandbox-ui` | the Secret is asserted present in all three platform namespaces, `sandbox-ui` included |+| the registry honors the minted key at pull time | the `Pulled` event must read `Successfully pulled image … Image size: N bytes`, never `already present on machine` |++Two additional properties the suite pins that no unit test can: **one mint fanned out**+(all copies must carry the same `clerum.io/pull-key-fingerprint` — the only cluster-visible+symptom of R1), and **injection rather than declaration** (the rendered PodTemplate carries+the reference while the `WorkflowRecipe` CRD does not).++**Coverage against the remediation as originally written.** (a) MCP-server plugin — covered.+(b) recipe plugin with a non-transport workload — covered. (c) recipe created by+`kubectl apply` — covered only *indirectly*: §13.1 turned provisioning into a standing+invariant, so what makes that path work is the Secret already being present in every+namespace, which the suite asserts directly. The apply itself is not exercised.++**Deliberately still out of the suite:** the periodic reconcile tick (interval is 10 min by+default and shortening it needs a redeploy — verified out-of-band instead; timestamps in+§11) and managed-cluster behaviour (control-api writes nothing there by design, so there is+no runtime outcome to observe — §9.1).### 13.7 As-built@@ -742,7 +821,7 @@ contents.| 13.2 | ✅ | `registryPullSecretService.ts` — `foreign_secret_would_be_revoked`, all-or-nothing refusal || 13.3 | ✅ | `withPullSecretLock` — `pg_advisory_xact_lock(hashtext('registry-pull-secret:<org>'))` around read→mint→write || 13.4 | ✅ | `registry.ts` — hook on `upgrade-recipe`, keyed on the INCOMING spec |-| 13.5 | ⏳ | still open — the only remaining acceptance gate |+| 13.5 | ✅ | `tests/e2e/integration/registry-pull-secret-runtime.test.ts` — live-cluster acceptance (§11, §13.5) |Notes worth carrying forward:diff --git a/docs/architecture/registry-pull-secret-self-provisioning.md b/docs/architecture/registry-pull-secret-self-provisioning.mdindex 5e52ff060..a889a6faf 100644--- a/docs/architecture/registry-pull-secret-self-provisioning.md+++ b/docs/architecture/registry-pull-secret-self-provisioning.md@@ -790,14 +790,24 @@ is outside `credRequired`); a mint failure fails the install and persists **no**McpServer; an unresolved org returns `409 org_unresolved`; a non-evenfire image provisionsnothing. Mutation-verified: gating the hook on `credRequired` fails 3 of these 4.-**Not shipped (deliberate)**+**Shipped since — `tests/e2e/integration/registry-pull-secret-runtime.test.ts`**- **Integration / e2e (minikube, self-hosted)** — install a private plugin end-to-end and- assert the pod actually pulls. Requires the Workstream-A registry change deployed to a- reachable registry; worth adding once that lands.+ assert the pod actually pulls. This was blocked on the Workstream-A registry change+ reaching a live registry; `evenfire-registry` #64 is merged and deployed, so it now+ exists. It covers this spec's `McpServer` path — control-api → `McpServer` CRD → HCC →+ Deployment → Pod Ready → a real authenticated pull, with the image evicted from the+ node's docker cache first so `imagePullPolicy: IfNotPresent` cannot serve it from cache+ and leave the credential unexercised — alongside the recipe-workload extension. See+ [`registry-pull-secret-recipe-workloads.md`](registry-pull-secret-recipe-workloads.md)+ §11 and §13.5.++**Not shipped (deliberate)**+- **A `mintOrgPullCredential` transport test** (endpoint path, POST, timeout, key- validation). It is mocked in both suites above; its behavior is asserted only- indirectly.+ validation). It is mocked in both suites above; its behavior is still asserted only+ indirectly at the unit level — though the e2e above now exercises the real transport end+ to end, since a pull that succeeds proves the minted key reached the registry intact.---diff --git a/tests/e2e/integration/registry-pull-secret-runtime.test.ts b/tests/e2e/integration/registry-pull-secret-runtime.test.tsnew file mode 100644index 000000000..db8076141--- /dev/null+++ b/tests/e2e/integration/registry-pull-secret-runtime.test.ts@@ -0,0 +1,827 @@+/**+ * Integration: platform image-pull credential — runtime acceptance+ *+ * This is the acceptance gate for PR #243 §13.5+ * (`docs/architecture/registry-pull-secret-recipe-workloads.md`). Everything else covering+ * this feature is unit- or route-level against a `MockGateway`, which by construction+ * cannot detect a namespace mistake, a rollout that never happens, or a kubelet that+ * rejects the blob. This suite runs the whole chain against a LIVE cluster and a LIVE+ * private registry:+ *+ * control-api mint -> Secret in every platform workload namespace+ * -> WRC / control-api inject the reference+ * -> McpServer CRD -> HCC -> Deployment+ * -> Pod Ready+ * -> a real `docker pull` of a private image using that credential+ *+ * What each block proves, and why it is here:+ *+ * 1. `Secret placement` — the Secret exists in EVERY platform workload namespace, is+ * `kubernetes.io/dockerconfigjson` (the only two types a kubelet honours for pulls),+ * is labelled ours, is keyed on OUR registry host, and — the load-bearing one — every+ * copy carries the SAME fingerprint. The registry's `mintPullKey` is rotate-on-call+ * with at most one active pull key per org, so three separate mints would leave the+ * first two namespaces holding revoked credentials while reporting success. One+ * fingerprint across all copies is the observable form of "one mint, fanned out"+ * (spec §6.3 / R1). It also asserts the Secret is NOT labelled `clerum.io/shared` or+ * `clerum.io/owner-recipe` — labelling it either way would make it readable by any+ * recipe's `envSecret` and turn a pull-only credential into an exfiltration primitive+ * (spec §5.1 / R4).+ *+ * 2. `Materialization` — WRC renders the recipe workload's PodTemplate with+ * `imagePullSecrets: [evenfire-registry-pull]`, while the WorkflowRecipe CRD itself+ * never declares it. That gap is the whole design: a declared name would be classified+ * by the Issue #637 ownership gate and stripped, so the reference has to be injected+ * after the filter (spec §6.1). For the MCP-server path the same assertion runs one+ * hop further out — control-api writes it onto the McpServer CRD and HCC materializes+ * it verbatim onto the Deployment it owns.+ *+ * 3. `Pod readiness + a REAL private pull` — the image is evicted from the node's docker+ * cache first. Without that the kubelet reuses the cached layers under+ * `imagePullPolicy: IfNotPresent`, no credential is ever exercised, and the assertion+ * passes vacuously. The two outcomes are distinguishable in the `Pulled` event: a+ * genuine pull logs `Successfully pulled image ... in Xs. Image size: N bytes.`, a+ * cache hit logs `Container image ... already present on machine`. This asserts the+ * former and explicitly rejects the latter.+ *+ * 4. `Pre-persistence failure` — a provisioning failure must fail the install BEFORE the+ * CRD is written. The alternative is the exact silent `ImagePullBackOff` this whole+ * mechanism exists to remove: a 201 on the API call and a workload that can never+ * pull.+ *+ * Deliberately NOT covered here — see the docs for why:+ * - The periodic reconcile cron (§13.1). Its interval is+ * `REGISTRY_PULL_SECRET_RECONCILE_INTERVAL_MS` (default 600_000) and shortening it+ * needs a redeploy, so a committed E2E cannot wait for a tick. Verified out-of-band.+ * - Managed-cluster behaviour (§9.1). control-api writes nothing there by design, so+ * there is no runtime outcome for this suite to observe.+ *+ * Requires (each guarded — the suite SKIPS rather than fails when unavailable):+ * - minikube cluster `clerum-test` running, kubectl context reachable+ * - control-api port-forwarded on :8090 (make minikube-pf-control-ui)+ * - admin credentials via TEST_ADMIN_PASSWORD (or ADMIN_PASSWORD)+ * - REGISTRY_CONNECTION_MODE=self-hosted with a connected registry org+ * - the private registry entries named below installable by this deployment+ *+ * Everything this suite creates is prefixed `e2e-pullsecret-` and removed in afterAll.+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { execSync } from 'node:child_process'+import { KUBE_CONTEXT, kubectl, sleep } from '../helpers.js'+import { CONTROL_API_URL, fetchJson, isServiceUp } from './helpers.integration.js'++// ─── Contract constants (must match the shipped implementation) ──────────────++/** `EVENFIRE_REGISTRY_PULL_SECRET_NAME` in packages/workflow-runtime-core. */+const PULL_SECRET = 'evenfire-registry-pull'+const MANAGED_BY_LABEL = 'clerum.io/managed-by'+const MANAGED_BY_VALUE = 'control-api'+const FINGERPRINT_ANNOTATION = 'clerum.io/pull-key-fingerprint'+const DOCKERCONFIG_TYPE = 'kubernetes.io/dockerconfigjson'+const DOCKERCONFIG_KEY = '.dockerconfigjson'++// ─── Cluster shape ──────────────────────────────────────────────────────────++const MCP_SERVERS_NS = process.env.E2E_MCP_SERVERS_NAMESPACE ?? 'mcp-server'+const SANDBOX_NS = process.env.E2E_SANDBOX_NAMESPACE ?? 'sandbox-recipes'+const SANDBOX_UI_NS = process.env.E2E_SANDBOX_UI_NAMESPACE ?? 'sandbox-ui'+const CONTROL_PLANE_NS = process.env.E2E_CONTROL_PLANE_NAMESPACE ?? 'control-plane'+/** `platformWorkloadNamespaces()` in control-api/src/services/registryPullSecretService.ts. */+const PLATFORM_NAMESPACES = [...new Set([MCP_SERVERS_NS, SANDBOX_NS, SANDBOX_UI_NS])]++const MINIKUBE_PROFILE = process.env.MINIKUBE_PROFILE ?? KUBE_CONTEXT++// ─── Fixtures (private, platform-registry-hosted) ───────────────────────────++const RECIPE_ENTRY = process.env.E2E_PRIVATE_RECIPE_ENTRY ?? '@josete-pr243/pr243-registry-recipe'+const RECIPE_ENTRY_VERSION = process.env.E2E_PRIVATE_RECIPE_VERSION ?? '1.0.0'+const MCP_ENTRY = process.env.E2E_PRIVATE_MCP_ENTRY ?? '@josete-pr243/test-docgen'+const MCP_ENTRY_VERSION = process.env.E2E_PRIVATE_MCP_VERSION ?? '1.0.5'+const CONTEXT_REF = process.env.E2E_CONTEXT_ID ?? 'context1'++const RUN_ID = Date.now().toString(36)+const RECIPE_NAME = `e2e-pullsecret-recipe-${RUN_ID}`+const MCP_NAME = `e2e-pullsecret-mcp-${RUN_ID}`+const PREPERSIST_RECIPE_NAME = `e2e-pullsecret-prepersist-${RUN_ID}`++// ─── State resolved in beforeAll ────────────────────────────────────────────++let controlApiUp = false+let clusterUp = false+let adminCookie = ''+/** Image host of the configured registry, e.g. `registry.evenfire.ai`. */+let registryHost = ''+let selfHosted = false+/** Both private fixtures are present in this deployment's catalog. */+let fixturesAvailable = false+/** Set once the recipe install returns 201, so downstream blocks can bail cleanly. */+let recipeInstalled = false+let mcpInstalled = false+/** Image of the MCP-server fixture, read from the catalog entry (not string-built). */+let mcpImage = ''+/** True only when the node's docker cache was actually made cold before the MCP install. */+let nodeWasCold = false++// ─── Helpers ────────────────────────────────────────────────────────────────++/** kubectl that returns null instead of throwing (for existence probes). */+function kubectlOrNull(args: string): string | null {+ try {+ return kubectl(args)+ } catch {+ return null+ }+}++function kubectlJson<T = Record<string, unknown>>(args: string): T | null {+ const out = kubectlOrNull(`${args} -o json`)+ if (!out) return null+ try {+ return JSON.parse(out) as T+ } catch {+ return null+ }+}++/** Run a command inside the minikube node VM. Returns null on failure. */+function nodeExec(command: string): string | null {+ try {+ return execSync(`minikube -p ${MINIKUBE_PROFILE} ssh -- ${command}`, {+ encoding: 'utf-8',+ timeout: 60_000,+ stdio: ['pipe', 'pipe', 'pipe'],+ }).trim()+ } catch {+ return null+ }+}++async function waitFor<T>(+ probe: () => T | Promise<T>,+ predicate: (value: T) => boolean,+ timeoutMs: number,+ intervalMs = 3_000+): Promise<T | null> {+ const deadline = Date.now() + timeoutMs+ let last: T | null = null+ while (Date.now() < deadline) {+ last = await probe()+ if (predicate(last)) return last+ await sleep(intervalMs)+ }+ return predicate(last as T) ? last : null+}++type K8sSecret = {+ type?: string+ metadata?: { labels?: Record<string, string>; annotations?: Record<string, string> }+ data?: Record<string, string>+}++function readPullSecret(namespace: string): K8sSecret | null {+ return kubectlJson<K8sSecret>(`get secret ${PULL_SECRET} -n ${namespace}`)+}++/** Hosts the dockerconfigjson blob carries credentials for. */+function authHosts(secret: K8sSecret): string[] {+ const blob = secret.data?.[DOCKERCONFIG_KEY]+ if (!blob) return []+ try {+ const parsed = JSON.parse(Buffer.from(blob, 'base64').toString('utf8')) as {+ auths?: Record<string, unknown>+ }+ return Object.keys(parsed.auths ?? {})+ } catch {+ return []+ }+}++type PodTemplateHolder = {+ spec?: { template?: { spec?: { imagePullSecrets?: Array<{ name?: string }> } } }+ metadata?: { labels?: Record<string, string> }+}++function pullSecretNamesOnDeployment(name: string, namespace: string): string[] | null {+ const dep = kubectlJson<PodTemplateHolder>(`get deployment ${name} -n ${namespace}`)+ if (!dep) return null+ return (dep.spec?.template?.spec?.imagePullSecrets ?? []).map(r => r.name ?? '')+}++/** POST/DELETE against control-api with the admin session cookie. */+async function adminRequest<T = Record<string, unknown>>(+ method: 'POST' | 'DELETE' | 'GET',+ path: string,+ body?: unknown+): Promise<{ status: number; data: T }> {+ return fetchJson<T>(`${CONTROL_API_URL}${path}`, {+ method,+ headers: {+ 'Content-Type': 'application/json',+ ...(adminCookie ? { Cookie: adminCookie } : {}),+ },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ })+}++/**+ * Admin login. The session is delivered as a `Secure` HttpOnly cookie, not a bearer+ * token, so the cookie pair has to be captured and replayed explicitly — `Secure` is+ * advisory on the wire and the port-forward is plain HTTP.+ */+async function login(): Promise<string> {+ const username = process.env.TEST_ADMIN_USERNAME ?? 'admin'+ const password = process.env.TEST_ADMIN_PASSWORD ?? process.env.ADMIN_PASSWORD ?? ''+ if (!password) return ''+ try {+ const res = await fetch(`${CONTROL_API_URL}/api/v1/admin/auth/login`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ username, password }),+ signal: AbortSignal.timeout(10_000),+ })+ if (res.status !== 200) return ''+ const raw =+ typeof res.headers.getSetCookie === 'function'+ ? res.headers.getSetCookie()+ : [res.headers.get('set-cookie') ?? '']+ return raw+ .filter(Boolean)+ .map(c => c.split(';')[0].trim())+ .join('; ')+ } catch {+ return ''+ }+}++function hostFromUrl(url: string): string {+ try {+ return new URL(url).host+ } catch {+ return ''+ }+}++/** Find the `Pulled` event for `pod` that mentions `image`. */+function pulledEventMessage(pod: string, namespace: string, image: string): string | null {+ const events = kubectlJson<{ items?: Array<{ message?: string }> }>(+ `get events -n ${namespace} --field-selector involvedObject.name=${pod},reason=Pulled`+ )+ const match = (events?.items ?? []).find(e => (e.message ?? '').includes(image))+ return match?.message ?? null+}++function podsFor(+ labelSelector: string,+ namespace: string+): Array<{+ name: string+ ready: boolean+ phase: string+}> {+ const list = kubectlJson<{+ items?: Array<{+ metadata?: { name?: string }+ status?: { phase?: string; containerStatuses?: Array<{ ready?: boolean }> }+ }>+ }>(`get pods -n ${namespace} -l ${labelSelector}`)+ return (list?.items ?? []).map(p => ({+ name: p.metadata?.name ?? '',+ phase: p.status?.phase ?? 'Unknown',+ ready:+ (p.status?.containerStatuses ?? []).length > 0 &&+ (p.status?.containerStatuses ?? []).every(c => c.ready === true),+ }))+}++// ─── Precondition handling: skip locally, FAIL in CI ────────────────────────++/**+ * Set by CI (and by anyone who wants the strict behaviour locally).+ *+ * This suite exists because green unit tests could not detect namespace, rollout or+ * kubelet failures. A suite that silently skips has exactly that defect in a worse form:+ * it reports "14 passed" in 250ms while proving nothing, and the wall of ticks looks like+ * evidence. Observed for real twice while validating this file — once with+ * TEST_ADMIN_PASSWORD unset, once with the port-forward down.+ *+ * So: locally an unwired harness is a normal state and skipping is right. Under+ * E2E_REQUIRE_CLUSTER=1 (or CI=true) it is a hard failure.+ */+const REQUIRE_CLUSTER = process.env.E2E_REQUIRE_CLUSTER === '1' || process.env.CI === 'true'++/**+ * A precondition that means the HARNESS is not wired up (no control-api, no cluster, no+ * credentials, no fixtures). Recoverable by configuring the environment, so it is fatal+ * when the environment claims to be able to run this.+ */+function unmet(reason: string): void {+ const msg = `[pull-secret-runtime] ${reason}`+ if (REQUIRE_CLUSTER) {+ throw new Error(+ `${msg}. Refusing to skip: E2E_REQUIRE_CLUSTER/CI is set, and a silent skip here ` ++ `would report success while asserting nothing. Fix the environment or unset the flag.`+ )+ }+ console.log(`${msg} — suite will be skipped`)+}++/**+ * A precondition that means the feature legitimately has no runtime outcome to assert+ * HERE (a managed cluster, where control-api provisions nothing by design). Not a+ * misconfiguration, so this skips even under REQUIRE_CLUSTER — failing would be wrong.+ */+function notApplicable(reason: string): void {+ console.log(`[pull-secret-runtime] ${reason} — not applicable on this cluster, skipping`)+}++// ─── Setup / teardown ───────────────────────────────────────────────────────++beforeAll(async () => {+ controlApiUp = await isServiceUp(CONTROL_API_URL)+ if (!controlApiUp) {+ unmet(`control-api not reachable at ${CONTROL_API_URL}`)+ return+ }++ clusterUp = kubectlOrNull('get ns default -o name') !== null+ if (!clusterUp) {+ unmet(`kube context "${KUBE_CONTEXT}" unreachable`)+ return+ }++ adminCookie = await login()+ if (!adminCookie) {+ unmet('admin login failed (set TEST_ADMIN_PASSWORD)')+ return+ }++ // The provisioner is mode-gated: on a managed cluster control-api writes nothing and+ // there is no runtime outcome to assert. Read the deployed config rather than assuming.+ const mode = kubectlOrNull(+ `get configmap control-api-config -n ${CONTROL_PLANE_NS} -o jsonpath={.data.REGISTRY_CONNECTION_MODE}`+ )+ const registryUrl = kubectlOrNull(+ `get configmap control-api-config -n ${CONTROL_PLANE_NS} -o jsonpath={.data.CLERUM_REGISTRY_URL}`+ )+ selfHosted = mode === 'self-hosted'+ registryHost = hostFromUrl(registryUrl ?? '')+ if (!selfHosted || !registryHost) {+ notApplicable(+ `REGISTRY_CONNECTION_MODE=${mode ?? 'unset'} / registry=${registryUrl ?? 'unset'}`+ )+ return+ }++ // The fixtures are private entries owned by the connected org, so they exist only on a+ // deployment that has published them. Without this probe an environment that simply+ // lacks them would FAIL on a 404 install instead of skipping, which is not a signal+ // about the feature.+ const { status, data } = await adminRequest<{ data?: RegistryEntry[] }>(+ 'GET',+ '/api/v1/admin/registry/entries?limit=200'+ )+ const catalog = status === 200 ? (data.data ?? []) : []+ const recipeEntry = catalog.find(+ e => e.name === RECIPE_ENTRY && e.version === RECIPE_ENTRY_VERSION+ )+ const mcpEntry = catalog.find(e => e.name === MCP_ENTRY && e.version === MCP_ENTRY_VERSION)+ mcpImage = mcpEntry?.mcp_server_meta?.imageRef ?? ''+ fixturesAvailable = Boolean(recipeEntry) && Boolean(mcpEntry) && mcpImage.startsWith(registryHost)+ if (!fixturesAvailable) {+ // Fatal under REQUIRE_CLUSTER: without private fixtures every runtime assertion in+ // this file is unreachable, so the suite would go green having proved nothing —+ // which is precisely the failure mode it was written to rule out.+ unmet(+ `private fixtures unavailable (recipe=${Boolean(recipeEntry)}, mcp=${Boolean(+ mcpEntry+ )}, image=${mcpImage || 'unset'}). ` ++ 'Set E2E_PRIVATE_RECIPE_ENTRY / E2E_PRIVATE_MCP_ENTRY to point at private ' ++ 'platform-registry entries this deployment can install'+ )+ }+}, 120_000)++/** Only the catalog fields this suite reads. */+type RegistryEntry = {+ name?: string+ version?: string+ mcp_server_meta?: { imageRef?: string } | null+}++/** Every block's precondition: a live self-hosted cluster with the private fixtures. */+function ready(): boolean {+ return controlApiUp && clusterUp && Boolean(adminCookie) && selfHosted && fixturesAvailable+}++afterAll(async () => {+ if (!adminCookie) return++ // Unconditional: a leaked foreign Secret would 409 every subsequent private install+ // into that namespace and read as a product bug.+ await restoreSandboxUiPullSecret()++ if (recipeInstalled) {+ await adminRequest('DELETE', `/api/v1/admin/registry/uninstall/${RECIPE_NAME}?type=recipe`)+ }+ if (mcpInstalled) {+ await adminRequest('DELETE', `/api/v1/admin/registry/uninstall/${MCP_NAME}?type=mcp-server`)+ }+ // Belt and braces — the uninstall route is best-effort and returns warnings, not errors.+ kubectlOrNull(`delete workflowrecipe ${RECIPE_NAME} -n ${SANDBOX_NS} --ignore-not-found=true`)+ kubectlOrNull(+ `delete workflowrecipe ${PREPERSIST_RECIPE_NAME} -n ${SANDBOX_NS} --ignore-not-found=true`+ )+ kubectlOrNull(`delete mcpserver ${MCP_NAME} -n ${MCP_SERVERS_NS} --ignore-not-found=true`)+}, 300_000)++// ─── Sandbox-ui Secret backup/restore, used by the pre-persistence block ─────++let sandboxUiBackup: string | null = null++/**+ * Replace the sandbox-ui copy with an externally-owned Secret the kubelet cannot use+ * (no `clerum.io/managed-by` label, wrong type). `classify()` reads that as+ * `foreign` + `unusable`, which is a pure classification outcome — it does NOT depend on+ * whether a mint is needed, so it cannot accidentally rotate the org's live credential.+ */+function plantForeignSandboxUiPullSecret(): boolean {+ sandboxUiBackup = kubectlOrNull(`get secret ${PULL_SECRET} -n ${SANDBOX_UI_NS} -o json`)+ if (+ kubectlOrNull(`delete secret ${PULL_SECRET} -n ${SANDBOX_UI_NS} --ignore-not-found=true`) ===+ null+ ) {+ return false+ }+ return (+ kubectlOrNull(+ `create secret generic ${PULL_SECRET} -n ${SANDBOX_UI_NS} --from-literal=note=e2e-foreign-fixture`+ ) !== null+ )+}++/**+ * Remove the foreign fixture and put `sandbox-ui` back into a state control-api considers+ * correct. Runs unconditionally: a leaked foreign copy would 409 every later private+ * install into that namespace and read as a product bug.+ *+ * The backup is only replayed when it is still CURRENT. An `install-recipe` that runs while+ * the fixture is planted can legitimately mint (an *unusable* foreign copy does not block+ * the mint — only a usable one does), which rotates the org key and leaves the captured+ * bytes holding a revoked credential. Restoring that would be worse than restoring nothing:+ * the copy would look valid, and its fingerprint would silently disagree with the other+ * namespaces. So when the backup is stale we delete instead — absent is a state the next+ * provisioning pass (any install, or the reconcile cron) repairs by design, converging every+ * namespace onto one fresh mint.+ */+async function restoreSandboxUiPullSecret(): Promise<void> {+ const current = kubectlJson<K8sSecret>(`get secret ${PULL_SECRET} -n ${SANDBOX_UI_NS}`)+ const isOurs = current?.metadata?.labels?.[MANAGED_BY_LABEL] === MANAGED_BY_VALUE+ if (isOurs) {+ sandboxUiBackup = null+ return+ }+ if (current) {+ kubectlOrNull(`delete secret ${PULL_SECRET} -n ${SANDBOX_UI_NS} --ignore-not-found=true`)+ }+ const backup = sandboxUiBackup+ sandboxUiBackup = null+ if (!backup) return++ let backupFingerprint: string | undefined+ try {+ backupFingerprint = (JSON.parse(backup) as K8sSecret).metadata?.annotations?.[+ FINGERPRINT_ANNOTATION+ ]+ } catch {+ backupFingerprint = undefined+ }+ const liveFingerprint =+ readPullSecret(MCP_SERVERS_NS)?.metadata?.annotations?.[FINGERPRINT_ANNOTATION]+ if (!backupFingerprint || backupFingerprint !== liveFingerprint) {+ console.log(+ `[pull-secret-runtime] the captured ${SANDBOX_UI_NS} credential was rotated during the run ` ++ `(${backupFingerprint ?? 'none'} vs ${liveFingerprint ?? 'none'}); leaving it absent so the ` ++ 'next provisioning pass re-mints and converges rather than restoring a revoked key'+ )+ return+ }++ try {+ execSync(`kubectl --context=${KUBE_CONTEXT} apply -f -`, {+ input: backup,+ encoding: 'utf-8',+ timeout: 30_000,+ stdio: ['pipe', 'pipe', 'pipe'],+ })+ } catch {+ // Nothing more we can do here; the reconcile cron re-provisions it on its next tick.+ }+}++// ─── 1. Secret placement ────────────────────────────────────────────────────++describe('registry pull secret — placement after a private-image recipe install', () => {+ it('installs the private recipe plugin', async () => {+ if (!ready()) return++ const { status, data } = await adminRequest('POST', '/api/v1/admin/registry/install-recipe', {+ recipeName: RECIPE_NAME,+ registryEntryName: RECIPE_ENTRY,+ registryEntryVersion: RECIPE_ENTRY_VERSION,+ })++ expect(status, `install-recipe failed: ${JSON.stringify(data)}`).toBe(201)+ recipeInstalled = true+ }, 120_000)++ it('provisions the Secret in EVERY platform workload namespace', () => {+ if (!recipeInstalled) return++ for (const ns of PLATFORM_NAMESPACES) {+ const secret = readPullSecret(ns)+ expect(secret, `${PULL_SECRET} missing in namespace ${ns}`).not.toBeNull()+ // Only dockerconfigjson/dockercfg are honoured by the kubelet for image pulls; an+ // Opaque Secret is accepted by the API server and then silently ignored at pull time.+ expect(secret!.type, `wrong Secret type in ${ns}`).toBe(DOCKERCONFIG_TYPE)+ expect(secret!.data?.[DOCKERCONFIG_KEY], `no ${DOCKERCONFIG_KEY} in ${ns}`).toBeTruthy()+ expect(secret!.metadata?.labels?.[MANAGED_BY_LABEL], `unowned Secret in ${ns}`).toBe(+ MANAGED_BY_VALUE+ )+ // The blob must be keyed on OUR image host, not the registry's token issuer —+ // otherwise the kubelet never selects this credential for the image being pulled.+ expect(+ authHosts(secret!),+ `dockerconfigjson in ${ns} not keyed on ${registryHost}`+ ).toContain(registryHost)+ }+ })++ it('all copies share ONE fingerprint — a single mint fanned out, not three mints', () => {+ if (!recipeInstalled) return++ const fingerprints = new Map<string, string>()+ for (const ns of PLATFORM_NAMESPACES) {+ const secret = readPullSecret(ns)+ const fp = secret?.metadata?.annotations?.[FINGERPRINT_ANNOTATION]+ expect(fp, `no ${FINGERPRINT_ANNOTATION} on the copy in ${ns}`).toBeTruthy()+ fingerprints.set(ns, fp!)+ }++ // The registry's mintPullKey is rotate-on-call with <=1 active pull key per org, so+ // per-namespace minting would leave earlier namespaces holding revoked credentials+ // while every Secret still looks present and well-formed. Divergent fingerprints are+ // the only cluster-visible symptom.+ const distinct = new Set(fingerprints.values())+ expect(+ distinct.size,+ `pull credential diverged across namespaces: ${JSON.stringify(Object.fromEntries(fingerprints))}`+ ).toBe(1)+ })++ it('is NOT recipe-accessible — no `shared` or `owner-recipe` label', () => {+ if (!recipeInstalled) return++ // spec §5.1 / R4: `isSecretAccessibleByRecipe` is the SAME predicate for envSecret and+ // imagePullSecrets. Either label would let any recipe on the cluster mount the org's+ // registry credential into its own environment.+ for (const ns of PLATFORM_NAMESPACES) {+ const labels = readPullSecret(ns)?.metadata?.labels ?? {}+ expect(labels['clerum.io/shared'], `${PULL_SECRET} is shared in ${ns}`).toBeUndefined()+ expect(+ labels['clerum.io/owner-recipe'],+ `${PULL_SECRET} is recipe-owned in ${ns}`+ ).toBeUndefined()+ }+ })+})++// ─── 2. Materialization onto the recipe workload ────────────────────────────++describe('registry pull secret — WRC materialization onto a recipe workload', () => {+ let deploymentName = ''++ it('WRC renders the workload Deployment with the injected reference', async () => {+ if (!recipeInstalled) return++ const dep = await waitFor(+ () =>+ kubectlJson<{ items?: Array<{ metadata?: { name?: string } }> }>(+ `get deployments -n ${SANDBOX_NS} -l clerum.io/recipe=${RECIPE_NAME}`+ ),+ v => (v?.items?.length ?? 0) > 0,+ 120_000+ )+ expect(dep, `WRC never rendered a Deployment for recipe ${RECIPE_NAME}`).not.toBeNull()++ deploymentName = dep!.items![0].metadata!.name!+ const names = pullSecretNamesOnDeployment(deploymentName, SANDBOX_NS)+ expect(names, `Deployment ${deploymentName} disappeared`).not.toBeNull()+ expect(names, `no imagePullSecrets on ${deploymentName}`).toContain(PULL_SECRET)+ }, 150_000)++ it('the reference is INJECTED, not declared by the recipe', () => {+ if (!recipeInstalled || !deploymentName) return++ // If the recipe declared the name, the Issue #637 ownership gate would classify it+ // `denied` (the Secret is deliberately unlabelled to that model) and tear the whole+ // workload down. The reference on the Pod spec above must therefore come from WRC's+ // post-filter injection, which is only true if the CRD does not carry it.+ const recipe = kubectlJson<{+ spec?: { workloads?: Array<{ imagePullSecrets?: string[] }> }+ }>(`get workflowrecipe ${RECIPE_NAME} -n ${SANDBOX_NS}`)+ expect(recipe, `WorkflowRecipe ${RECIPE_NAME} not found`).not.toBeNull()++ for (const workload of recipe!.spec?.workloads ?? []) {+ expect(+ workload.imagePullSecrets ?? [],+ 'the recipe CRD declares the platform Secret; injection is no longer being proven'+ ).not.toContain(PULL_SECRET)+ }+ })++ it('the workload Pod reaches Ready', async () => {+ if (!recipeInstalled) return++ const pods = await waitFor(+ () => podsFor(`clerum.io/recipe=${RECIPE_NAME}`, SANDBOX_NS),+ list => list.length > 0 && list.some(p => p.ready),+ 240_000+ )+ expect(+ pods,+ `no Ready Pod for recipe ${RECIPE_NAME}; last seen ${JSON.stringify(+ podsFor(`clerum.io/recipe=${RECIPE_NAME}`, SANDBOX_NS)+ )}`+ ).not.toBeNull()+ }, 300_000)+})++// ─── 3. McpServer -> HCC -> Deployment, and a real private pull ─────────────++describe('registry pull secret — McpServer delegation, HCC materialization, real pull', () => {+ let deploymentName = ''+ let podName = ''++ it('evicts the private image from the node so the pull cannot be served from cache', async () => {+ if (!ready()) return++ // docker refuses to remove an image a running container still uses, so a workload on+ // the same image makes a cold node impossible. Wait a little first — a container from an+ // earlier block that is still terminating clears on its own — then give up honestly+ // rather than deleting nothing and "proving" a pull that never happened.+ // `null` means the node command itself failed, which is NOT the same as "no container";+ // only an empty result proves the image is free, so a broken `minikube ssh` times out+ // here and skips rather than being read as a green light to evict.+ const free = await waitFor(+ () => nodeExec(`docker ps --filter ancestor=${mcpImage} --format '{{.ID}}'`),+ inUse => inUse === '',+ 60_000,+ 5_000+ )+ if (free === null) {+ console.log(+ `[pull-secret-runtime] ${mcpImage} is still held by a running container (or the node is unreachable) — cannot cold-start the node`+ )+ return+ }++ nodeExec(`docker rmi -f ${mcpImage}`)+ const remaining = nodeExec(`docker images -q ${mcpImage}`)+ nodeWasCold = !remaining+ if (!nodeWasCold) {+ console.log(`[pull-secret-runtime] failed to evict ${mcpImage} from the node docker cache`)+ }+ }, 120_000)++ it('installs the private MCP-server plugin', async () => {+ if (!ready()) return++ const { status, data } = await adminRequest('POST', '/api/v1/admin/registry/install', {+ serverName: MCP_NAME,+ contextRef: CONTEXT_REF,+ registryEntryName: MCP_ENTRY,+ registryEntryVersion: MCP_ENTRY_VERSION,+ })+ expect(status, `install failed: ${JSON.stringify(data)}`).toBe(201)+ mcpInstalled = true+ }, 120_000)++ it('the McpServer CRD carries the pull-secret reference', () => {+ if (!mcpInstalled) return++ const server = kubectlJson<{+ spec?: { image?: string; imagePullSecrets?: Array<{ name?: string }> }+ }>(`get mcpserver ${MCP_NAME} -n ${MCP_SERVERS_NS}`)+ expect(server, `McpServer ${MCP_NAME} not found`).not.toBeNull()+ expect(server!.spec?.image, 'fixture is not a platform-registry image').toContain(registryHost)+ expect(+ (server!.spec?.imagePullSecrets ?? []).map(r => r.name),+ 'control-api did not attach the pull-secret reference to the McpServer CRD'+ ).toContain(PULL_SECRET)+ })++ it('HCC materializes the reference onto the Deployment it owns', async () => {+ if (!mcpInstalled) return++ // HCC copies the McpServer spec verbatim onto a Deployment it owns; this is the hop a+ // MockGateway cannot exercise. The managed-by label is asserted so the test cannot pass+ // on some other controller's Deployment that happens to share the name.+ const dep = await waitFor(+ () => kubectlJson<PodTemplateHolder>(`get deployment ${MCP_NAME} -n ${MCP_SERVERS_NS}`),+ v => v !== null,+ 180_000+ )+ expect(dep, `HCC never created a Deployment for McpServer ${MCP_NAME}`).not.toBeNull()+ deploymentName = MCP_NAME++ expect(dep!.metadata?.labels?.[MANAGED_BY_LABEL]).toBe('host-context-controller')+ expect(+ (dep!.spec?.template?.spec?.imagePullSecrets ?? []).map(r => r.name),+ 'HCC dropped the pull-secret reference'+ ).toContain(PULL_SECRET)+ }, 200_000)++ it('the Pod reaches Ready', async () => {+ if (!mcpInstalled || !deploymentName) return++ const pods = await waitFor(+ () => podsFor(`app=${MCP_NAME}`, MCP_SERVERS_NS),+ list => list.length > 0 && list.some(p => p.ready),+ 240_000+ )+ // Record the Pod name even when readiness fails, so the pull assertion below reports its+ // OWN failure ("no Pulled event …") instead of chain-skipping. A missing credential+ // should surface as two independent failures, not one plus a silent skip.+ const observed = pods ?? podsFor(`app=${MCP_NAME}`, MCP_SERVERS_NS)+ podName = (observed.find(p => p.ready) ?? observed[0])?.name ?? ''+ expect(+ pods,+ `no Ready Pod for McpServer ${MCP_NAME}; last seen ${JSON.stringify(observed)}`+ ).not.toBeNull()+ }, 300_000)++ it('the kubelet performed a REAL authenticated pull, not a cache hit', () => {+ if (!mcpInstalled || !podName) return+ if (!nodeWasCold) {+ // Asserting a genuine pull against a warm node proves nothing: `IfNotPresent` would+ // short-circuit and the credential would never be exercised. Say so instead of+ // silently downgrading the assertion.+ console.log(+ '[pull-secret-runtime] node was not cold — skipping the genuine-pull assertion (this run does NOT prove the private pull)'+ )+ return+ }++ const message = pulledEventMessage(podName, MCP_SERVERS_NS, mcpImage)+ expect(message, `no Pulled event for ${mcpImage} on pod ${podName}`).not.toBeNull()++ // A cache hit and a genuine pull are distinguishable only in this message.+ expect(+ message,+ 'kubelet served the image from cache — the credential was never used'+ ).not.toContain('already present on machine')+ expect(message).toContain('Successfully pulled image')+ expect(message, 'pull event carries no transferred byte count').toMatch(/Image size: \d+ bytes/)+ })+})++// ─── 4. Pre-persistence failure ─────────────────────────────────────────────++describe('registry pull secret — a provisioning failure is pre-persistence', () => {+ it('fails the install and persists NO WorkflowRecipe', async () => {+ if (!ready()) return++ let planted = false+ try {+ planted = plantForeignSandboxUiPullSecret()+ if (!planted) {+ console.log('[pull-secret-runtime] could not plant the foreign Secret — skipping')+ return+ }++ const { status, data } = await adminRequest('POST', '/api/v1/admin/registry/install-recipe', {+ recipeName: PREPERSIST_RECIPE_NAME,+ registryEntryName: RECIPE_ENTRY,+ registryEntryVersion: RECIPE_ENTRY_VERSION,+ })++ expect(status, `expected the install to be refused, got ${JSON.stringify(data)}`).toBe(409)+ const body = data as { error?: string; reason?: string }+ expect(body.error).toBe('registry_pull_secret_provision_failed')+ expect(body.reason).toBe('foreign_secret_unusable')++ // The whole point: the credential could not be provisioned, so the CRD that would+ // reference it must never have been written. A 4xx with a persisted recipe behind it+ // is the silent ImagePullBackOff this mechanism exists to remove.+ // `2>/dev/null` because NotFound is the expected, passing outcome here — without it+ // kubectl's error line lands in the run log and reads like a failure.+ const persisted = kubectlOrNull(+ `get workflowrecipe ${PREPERSIST_RECIPE_NAME} -n ${SANDBOX_NS} -o name 2>/dev/null`+ )+ expect(persisted, 'the failed install left a WorkflowRecipe behind').toBeNull()+ } finally {+ // Unconditional — a leaked foreign Secret 409s every later private install here.+ await restoreSandboxUiPullSecret()+ }+ }, 180_000)+})diff --git a/tests/e2e/package-lock.json b/tests/e2e/package-lock.jsonindex 9783ece5b..e4d7a4e28 100644--- a/tests/e2e/package-lock.json+++ b/tests/e2e/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-e2e-tests",- "version": "0.1.56",+ "version": "0.1.57","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-e2e-tests",- "version": "0.1.56",+ "version": "0.1.57","devDependencies": {"@types/jsonwebtoken": "^9.0.10","@types/node": "^22.0.0",diff --git a/tests/e2e/package.json b/tests/e2e/package.jsonindex 01259ad7f..7dc4237dc 100644--- a/tests/e2e/package.json+++ b/tests/e2e/package.json@@ -1,6 +1,6 @@{"name": "clerum-e2e-tests",- "version": "0.1.56",+ "version": "0.1.57","private": true,"type": "module","scripts": {