Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat: add credential rotation for existing MCP connectors (#223)
Alfredo Lopeze2ea9050ecfd
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex cb0f7a33b..1bf20ca32 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.392",+ "version": "0.1.393","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.392",+ "version": "0.1.393","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 6d18bd0d2..1376f982e 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.392",+ "version": "0.1.393","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/k8s.ts b/control-api/src/k8s.tsindex e7dfdfd11..9d5ea9d6f 100644--- a/control-api/src/k8s.ts+++ b/control-api/src/k8s.ts@@ -659,7 +659,7 @@ export type RecipePodInfo = {}>}-function extractHttpStatus(err: unknown): number | null {+export function extractHttpStatus(err: unknown): number | null {if (!err || typeof err !== 'object') return nullconst maybe = err as {statusCode?: numberdiff --git a/control-api/src/routes/admin/secrets.ts b/control-api/src/routes/admin/secrets.tsindex 6ccf14c23..c6c1a7ffa 100644--- a/control-api/src/routes/admin/secrets.ts+++ b/control-api/src/routes/admin/secrets.ts@@ -4,7 +4,7 @@ import { config } from '../../config.js'import { asyncHandler } from '../../http/asyncHandler.js'import { enforceNamespace } from '../../http/namespaceAudit.js'import { isValidDNSSubdomain } from '../../http/rfc1123.js'-import { K8sGateway } from '../../k8s.js'+import { K8sGateway, extractHttpStatus } from '../../k8s.js'import {OWNER_RECIPE_LABEL_KEY,SHARED_LABEL_KEY,@@ -23,6 +23,13 @@ const BEDROCK_CREDENTIAL_KEYS: readonly string[] = PROVIDER_CREDENTIAL_SLOTS.bed)const VERTEX_SERVICE_ACCOUNT_KEY: string = PROVIDER_CREDENTIAL_SLOTS.vertex[0].dataKey+// The ownership label every WorkflowRecipe Secret carries. Declared at module+// scope so the recipe-secret routes below and the mcp-secret rotation guard+// read the SAME constant: a literal duplicated in either place would silently+// stop the guard from firing the day the other one changes.+const RECIPE_SECRET_LABEL_KEY = 'clerum.io/recipe-secret'+const RECIPE_SECRET_LABEL_VALUE = 'true'+// The plaintext data being written, merging base64 `data` and plaintext// `stringData` (stringData wins, matching Kubernetes Secret semantics).function effectiveSecretData(body: unknown): Record<string, string> {@@ -338,6 +345,147 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {}))+ // Rotate credentials on an EXISTING MCP Server Secret (issue #223).+ //+ // Body: { data: Record<string, string> } — only the keys the operator means+ // to rotate. Keys sent here are added or replaced; every other key on the+ // Secret survives untouched, because one connector Secret can hold several+ // credentials and rotating one must not wipe the rest. The merge is a+ // server-side RFC 7396 merge-patch (atomic, no read/replace race), which is+ // why this namespace's Role grants `secrets: patch`.+ //+ // Restarting the connector is NOT this route's job: HCC watches Secrets and+ // rolls the affected Deployments through the credentials-revision annotation.+ // `affectedConnectors` names the McpServers that reference this Secret, so+ // the UI can tell the operator exactly what is about to restart.+ //+ // The response is names-only. No secret value is ever echoed back — not in+ // plaintext, not in base64, and not as a hash of the values.+ //+ // Namespace is always `config.mcpServersNamespace`; any caller-supplied+ // namespace is ignored.+ router.put(+ '/admin/mcp-secrets/:name',+ enforceNamespace(config.mcpServersNamespace),+ asyncHandler(async (req, res) => {+ const name = (req.params.name || '').trim()+ const { data } = req.body as { data?: Record<string, string> }++ if (!name) {+ res.status(400).json({ error: 'name is required' })+ return+ }+ if (!isValidDNSSubdomain(name)) {+ res.status(400).json({+ error: 'Invalid secret name: must be lowercase alphanumeric and hyphens, max 253 chars',+ })+ return+ }+ if (!data || typeof data !== 'object' || Object.keys(data).length === 0) {+ res+ .status(400)+ .json({ error: 'data is required and must contain at least one key-value pair' })+ return+ }+ for (const [key, val] of Object.entries(data)) {+ if (typeof val !== 'string') {+ res.status(400).json({ error: `data["${key}"] must be a string` })+ return+ }+ // A blank value is an operator slip, not a delete instruction: this+ // route writes the keys the operator chose to rotate, and retiring a+ // key is DELETE's job. Skipping it silently would report a rotation+ // that never happened.+ if (!val.trim()) {+ res.status(400).json({ error: `data["${key}"] must not be empty` })+ return+ }+ }++ const targetNs = config.mcpServersNamespace++ // Rotation targets a Secret that already exists — creating one is POST's+ // job. Read it first so a missing Secret is a 404 instead of a silent+ // upsert, and so the ownership guard below sees the stored labels.+ let existing: {+ metadata?: { labels?: Record<string, string> }+ data?: Record<string, string>+ }+ try {+ existing = (await gateway.getSecret(name, targetNs)) as typeof existing+ } catch (err) {+ if (extractHttpStatus(err) === 404) {+ res.status(404).json({ error: `Secret "${name}" not found in ${targetNs}` })+ return+ }+ // 403 (Role missing the verb), 5xx, timeouts: propagate. Dressing them+ // up as 404 would tell the operator "no such credential" when the truth+ // is that the API server refused the read.+ throw err+ }++ // `mcp-server` is a shared namespace: WorkflowRecipe Secrets live here too+ // (see RECIPE_SECRET_NAMESPACES below) behind their own ownership gate.+ // Without this guard, rotating through the connector route would be a way+ // around that gate.+ if (existing.metadata?.labels?.[RECIPE_SECRET_LABEL_KEY] === RECIPE_SECRET_LABEL_VALUE) {+ res.status(409).json({+ error: `Secret "${name}" is owned by a WorkflowRecipe; rotate it through /admin/recipe-secrets`,+ })+ return+ }++ await gateway.mergeSecret({ name, namespace: targetNs, stringData: data })++ const keys = [...new Set([...Object.keys(existing.data || {}), ...Object.keys(data)])].sort(+ (a, b) => a.localeCompare(b)+ )++ // The credential IS rotated at this point. Emit the audit record NOW,+ // before anything that could throw — a rotation that actually happened+ // must never go unlogged just because a later, secondary step failed.+ // Key NAMES are safe to log; values never are.+ console.log(+ JSON.stringify({+ event: 'mcp-secret-rotated',+ name,+ namespace: targetNs,+ rotatedKeys: Object.keys(data).sort((a, b) => a.localeCompare(b)),+ })+ )++ // affectedConnectors is a best-effort convenience for the UI ("who+ // restarts"), NOT part of the rotation's success. The Secret is already+ // written and HCC will roll the affected Deployments regardless. So a+ // failure to LIST connectors must not turn a successful rotation into a+ // 500 that would make the operator think the credential is unchanged (and+ // possibly re-rotate). Fail loud in the log, then return the rotation as+ // the success it is, with an empty list the UI renders as "unknown".+ let affectedConnectors: string[] = []+ try {+ affectedConnectors = (await gateway.listResource('mcpservers', targetNs))+ .filter(+ item =>+ (item as { spec?: { envSecret?: { name?: string } } }).spec?.envSecret?.name === name+ )+ .map(item => (item as { metadata?: { name?: string } }).metadata?.name)+ .filter((connector): connector is string => typeof connector === 'string')+ .sort((a, b) => a.localeCompare(b))+ } catch (err) {+ console.warn(+ JSON.stringify({+ event: 'mcp-secret-rotated-affected-connectors-unavailable',+ name,+ namespace: targetNs,+ error: err instanceof Error ? err.message : String(err),+ })+ )+ }++ res.status(200).json({ name, namespace: targetNs, keys, affectedConnectors })+ })+ )+// Delete an MCP Server Secret. Used by the Control UI as a best-effort// rollback when CRD creation fails after the Secret was already created// (see PR-A / A2 — Secret-first + CRD-second transactional create).@@ -362,8 +510,6 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {// it. WRC's reconciler refuses projection for any other recipe; the// boundary holds even against malicious third-party recipe authors.- const RECIPE_SECRET_LABEL_KEY = 'clerum.io/recipe-secret'- const RECIPE_SECRET_LABEL_VALUE = 'true'const RECIPE_SECRET_NAMESPACES = new Set([config.sandboxNamespace,config.mcpServersNamespace,diff --git a/control-api/test/app.mcpSecretsAuthBoundary.test.ts b/control-api/test/app.mcpSecretsAuthBoundary.test.tsnew file mode 100644index 000000000..eb3afa61d--- /dev/null+++ b/control-api/test/app.mcpSecretsAuthBoundary.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest'+import request from 'supertest'+import { createApp } from '../src/app.js'+import { MockGateway } from './mockGateway.js'++/**+ * Credential rotation (issue #223) writes Secrets in the mcp-server namespace.+ * The route lives behind requireAuthForControlUI like every other /admin route;+ * this suite pins that boundary from the outside, with the real middleware in+ * place — routes.mcpSecrets.test.ts mounts the router alone and therefore+ * cannot see it.+ */+describe('PUT /api/v1/admin/mcp-secrets/:name auth boundary', () => {+ it('rejects an unauthenticated rotation with 401', async () => {+ const app = createApp(new MockGateway('mcp-server') as never)++ const res = await request(app)+ .put('/api/v1/admin/mcp-secrets/linear-credentials')+ .send({ data: { LINEAR_API_KEY: 'rotated-value' } })++ expect(res.status).toBe(401)+ expect(res.body).toEqual({ error: 'Unauthorized' })+ })+})diff --git a/control-api/test/routes.mcpSecrets.test.ts b/control-api/test/routes.mcpSecrets.test.tsindex 88902d92b..569ae3b82 100644--- a/control-api/test/routes.mcpSecrets.test.ts+++ b/control-api/test/routes.mcpSecrets.test.ts@@ -3,6 +3,15 @@ import express from 'express'import request from 'supertest'import { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'+/** The write shape the admin routes hand to the gateway. */+type SecretWrite = {+ name: string+ namespace?: string+ type?: string+ stringData?: Record<string, string>+ data?: Record<string, string>+}+/*** Minimal mock gateway with methods used by the POST /admin/mcp-secrets handler.*/@@ -12,9 +21,40 @@ function createGateway() {createSecret: vi.fn(async (body: unknown) => body),updateSecret: vi.fn(async (body: unknown) => body),deleteSecret: vi.fn(async (_name: string, _namespace?: string) => ({ deleted: true })),+ getSecret: vi.fn(+ async (+ name: string,+ namespace?: string+ ): Promise<{+ metadata: { name: string; namespace?: string; labels: Record<string, string> }+ data: Record<string, string>+ }> => ({+ metadata: { name, namespace, labels: {} },+ // base64 of 'old-value' — the stored form of an existing key.+ data: { EXISTING_KEY: 'b2xkLXZhbHVl' },+ })+ ),+ // Mirrors the real client: patchNamespacedSecret answers with the WHOLE+ // Secret, values included. A handler that echoed this back would leak+ // every stored credential, so the leak assertions below are meaningful.+ mergeSecret: vi.fn(async (body: SecretWrite) => ({+ metadata: { name: body.name, namespace: 'mcp-server' },+ data: Object.fromEntries(+ Object.entries(body.stringData ?? {}).map(([key, value]) => [+ key,+ Buffer.from(value, 'utf8').toString('base64'),+ ])+ ),+ })),+ listResource: vi.fn(async (_plural: string, _namespace?: string) => [] as unknown[]),}}+/** A K8s client error carrying an HTTP status, as extractHttpStatus reads it. */+function k8sError(statusCode: number, message: string): Error & { statusCode: number } {+ return Object.assign(new Error(message), { statusCode })+}+function makeApp(gateway: ReturnType<typeof createGateway>) {const app = express()app.use(express.json())@@ -335,3 +375,261 @@ describe('DELETE /admin/mcp-secrets/:name', () => {expect(res.body.error).toContain('K8s API timeout')})})++describe('PUT /admin/mcp-secrets/:name (credential rotation, issue #223)', () => {+ // ── Happy path + merge semantics ─────────────────────────────────────────++ it('merges the sent keys and preserves the ones it did not send', async () => {+ const gateway = createGateway()+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/linear-credentials')+ .send({ data: { LINEAR_API_KEY: 'rotated-value' } })+ .expect(200)++ // Only the rotated key travels to the API server; EXISTING_KEY is never+ // resent, and merge-patch leaves it in place server-side.+ expect(gateway.mergeSecret).toHaveBeenCalledOnce()+ const arg = gateway.mergeSecret.mock.calls[0][0] as {+ name: string+ namespace: string+ stringData: Record<string, string>+ type?: string+ }+ expect(arg.name).toBe('linear-credentials')+ expect(arg.namespace).toBe('mcp-server')+ expect(arg.stringData).toEqual({ LINEAR_API_KEY: 'rotated-value' })+ // Secret type is immutable and the Secret already exists: sending it would+ // only add a way to fail.+ expect(arg.type).toBeUndefined()++ // The response reports the resulting key names — the union of stored and+ // rotated — so the operator sees the Secret did not shrink.+ expect(res.body.keys).toEqual(['EXISTING_KEY', 'LINEAR_API_KEY'])+ expect(res.body.name).toBe('linear-credentials')+ expect(res.body.namespace).toBe('mcp-server')+ })++ it('always targets config.mcpServersNamespace and ignores a namespace in the body', async () => {+ const gateway = createGateway()+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/linear-credentials')+ .send({ namespace: 'kube-system', data: { LINEAR_API_KEY: 'rotated-value' } })+ .expect(200)++ expect(res.body.namespace).toBe('mcp-server')+ const [, readNs] = gateway.getSecret.mock.calls[0]+ expect(readNs).toBe('mcp-server')+ const arg = gateway.mergeSecret.mock.calls[0][0] as { namespace: string }+ expect(arg.namespace).toBe('mcp-server')+ })++ // ── No secret value ever leaves the process ──────────────────────────────++ it('never returns secret values, in plaintext or base64', async () => {+ const gateway = createGateway()+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/linear-credentials')+ .send({ data: { LINEAR_API_KEY: 'rotated-value' } })+ .expect(200)++ const serialized = JSON.stringify(res.body)+ expect(serialized).not.toContain('rotated-value')+ expect(serialized).not.toContain(Buffer.from('rotated-value', 'utf8').toString('base64'))+ // The stored key the caller never sent must not leak either.+ expect(serialized).not.toContain('b2xkLXZhbHVl')+ expect(serialized).not.toContain('old-value')+ // Key NAMES are the contract; values are not.+ expect(res.body.keys).toContain('LINEAR_API_KEY')+ })++ // ── affectedConnectors ───────────────────────────────────────────────────++ it('names every connector that references the secret', async () => {+ const gateway = createGateway()+ gateway.listResource.mockResolvedValueOnce([+ { metadata: { name: 'linear' }, spec: { envSecret: { name: 'linear-credentials' } } },+ {+ metadata: { name: 'linear-readonly' },+ spec: { envSecret: { name: 'linear-credentials' } },+ },+ { metadata: { name: 'github' }, spec: { envSecret: { name: 'github-credentials' } } },+ { metadata: { name: 'filesystem' }, spec: {} },+ ])+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/linear-credentials')+ .send({ data: { LINEAR_API_KEY: 'rotated-value' } })+ .expect(200)++ expect(res.body.affectedConnectors).toEqual(['linear', 'linear-readonly'])+ expect(gateway.listResource).toHaveBeenCalledWith('mcpservers', 'mcp-server')+ })++ it('reports an empty affectedConnectors when no connector references the secret', async () => {+ const gateway = createGateway()+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/orphan-credentials')+ .send({ data: { SOME_KEY: 'rotated-value' } })+ .expect(200)++ // Legitimate answer, and the UI must say "nothing will restart" rather+ // than promise a rollout that will not happen.+ expect(res.body.affectedConnectors).toEqual([])+ })++ // ── Existence: rotation is not an upsert ─────────────────────────────────++ it('returns 404 when the secret does not exist', async () => {+ const gateway = createGateway()+ gateway.getSecret.mockRejectedValueOnce(k8sError(404, 'secrets "nope" not found'))+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/nope')+ .send({ data: { SOME_KEY: 'rotated-value' } })+ .expect(404)++ expect(res.body.error).toContain('not found')+ expect(gateway.mergeSecret).not.toHaveBeenCalled()+ })++ it('propagates a non-404 read failure instead of disguising it as 404', async () => {+ const gateway = createGateway()+ gateway.getSecret.mockRejectedValueOnce(k8sError(403, 'secrets is forbidden'))+ const app = makeApp(gateway)++ // A missing RBAC verb must not read as "no such credential".+ const res = await request(app)+ .put('/admin/mcp-secrets/linear-credentials')+ .send({ data: { LINEAR_API_KEY: 'rotated-value' } })+ .expect(500)++ expect(res.body.error).toContain('forbidden')+ expect(gateway.mergeSecret).not.toHaveBeenCalled()+ })++ // ── Ownership guard: mcp-server is a shared namespace ────────────────────++ it('refuses to rotate a WorkflowRecipe-owned secret (409)', async () => {+ const gateway = createGateway()+ gateway.getSecret.mockResolvedValueOnce({+ metadata: {+ name: 'recipe-creds',+ namespace: 'mcp-server',+ labels: { 'clerum.io/recipe-secret': 'true' },+ },+ data: {},+ })+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/recipe-creds')+ .send({ data: { SOME_KEY: 'rotated-value' } })+ .expect(409)++ expect(res.body.error).toContain('WorkflowRecipe')+ expect(gateway.mergeSecret).not.toHaveBeenCalled()+ })++ // ── Payload validation ───────────────────────────────────────────────────++ it('rejects an invalid K8s secret name', async () => {+ const gateway = createGateway()+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/Invalid_Name')+ .send({ data: { SOME_KEY: 'rotated-value' } })+ .expect(400)++ expect(res.body.error).toContain('Invalid secret name')+ expect(gateway.getSecret).not.toHaveBeenCalled()+ })++ it('rejects a missing data field', async () => {+ const gateway = createGateway()+ const app = makeApp(gateway)++ const res = await request(app).put('/admin/mcp-secrets/linear-credentials').send({}).expect(400)++ expect(res.body.error).toContain('data is required')+ })++ it('rejects an empty data object', async () => {+ const gateway = createGateway()+ const app = makeApp(gateway)++ await request(app).put('/admin/mcp-secrets/linear-credentials').send({ data: {} }).expect(400)++ expect(gateway.mergeSecret).not.toHaveBeenCalled()+ })++ it('rejects a non-string value', async () => {+ const gateway = createGateway()+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/linear-credentials')+ .send({ data: { LINEAR_API_KEY: 42 } })+ .expect(400)++ expect(res.body.error).toContain('must be a string')+ })++ it('rejects a blank value instead of silently skipping the key', async () => {+ const gateway = createGateway()+ const app = makeApp(gateway)++ // Blanking is an operator slip, not a delete instruction. Skipping it+ // would report a rotation that never happened.+ const res = await request(app)+ .put('/admin/mcp-secrets/linear-credentials')+ .send({ data: { LINEAR_API_KEY: ' ' } })+ .expect(400)++ expect(res.body.error).toContain('must not be empty')+ expect(gateway.mergeSecret).not.toHaveBeenCalled()+ })++ // ── Gateway failure ──────────────────────────────────────────────────────++ it('still returns 200 when listing connectors fails AFTER a successful merge (M1)', async () => {+ const gateway = createGateway()+ // The rotation itself succeeds; only the secondary affectedConnectors+ // lookup fails. The operator must see the rotation as the success it is,+ // not a 500 that suggests the credential is unchanged.+ gateway.listResource.mockRejectedValueOnce(new Error('mcpservers list forbidden'))+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/linear-credentials')+ .send({ data: { LINEAR_API_KEY: 'rotated-value' } })+ .expect(200)++ expect(gateway.mergeSecret).toHaveBeenCalledOnce()+ expect(res.body.name).toBe('linear-credentials')+ expect(res.body.affectedConnectors).toEqual([])+ })++ it('returns 500 when gateway.mergeSecret throws', async () => {+ const gateway = createGateway()+ gateway.mergeSecret.mockRejectedValueOnce(new Error('K8s API timeout'))+ const app = makeApp(gateway)++ const res = await request(app)+ .put('/admin/mcp-secrets/linear-credentials')+ .send({ data: { LINEAR_API_KEY: 'rotated-value' } })+ .expect(500)++ expect(res.body.error).toContain('K8s API timeout')+ })+})diff --git a/control-ui/app/mcp-servers/[name]/edit/page.tsx b/control-ui/app/mcp-servers/[name]/edit/page.tsxindex e23b294f4..29330fefb 100644--- a/control-ui/app/mcp-servers/[name]/edit/page.tsx+++ b/control-ui/app/mcp-servers/[name]/edit/page.tsx@@ -9,11 +9,34 @@ import { DashboardLayout } from '@components/DashboardLayout'import { EgressEditor } from '@components/EgressEditor'import { IconCable } from '@components/Sidebar/icons'import { useToast } from '@components/Toast'+import { UpdateConnectorCredentials } from '@components/UpdateConnectorCredentials'import { CONTROL_ROUTES } from '@constants/routes'import { getMcpServer, updateMcpServer } from '@lib/api'-import type { EgressBinding, McpServerResource } from '@lib/api'+import type { EgressBinding, EnvSecret, EnvSecretKeyMapping, McpServerResource } from '@lib/api'import type { EgressEditorStatus } from '@lib/egressModel'+/**+ * Narrows `server.spec.envSecret` (typed as `unknown` on the generic+ * `AnyRecord` spec) into the shape UpdateConnectorCredentials needs. A+ * malformed or partial envSecret (missing name, keys not an array, or no+ * usable key mappings) is treated the same as "no envSecret" — there is+ * nothing safely rotatable through this form either way.+ */+function resolveEnvSecret(spec: Record<string, unknown> | undefined): EnvSecret | undefined {+ const raw = spec?.envSecret+ if (!raw || typeof raw !== 'object') return undefined+ const candidate = raw as { name?: unknown; keys?: unknown }+ if (typeof candidate.name !== 'string' || !Array.isArray(candidate.keys)) return undefined+ const keys = candidate.keys.filter(+ (k): k is EnvSecretKeyMapping =>+ Boolean(k) &&+ typeof (k as EnvSecretKeyMapping).secretKey === 'string' &&+ typeof (k as EnvSecretKeyMapping).envVar === 'string'+ )+ if (keys.length === 0) return undefined+ return { name: candidate.name, keys }+}+export default function EditMcpServerPage() {const router = useRouter()const params = useParams<{ name: string }>()@@ -111,8 +134,8 @@ export default function EditMcpServerPage() {</div></div>) : server ? (- <form className="cu-connector-edit-form" onSubmit={handleSave}>- <div className="cu-create-content cu-connector-edit-content">+ <div className="cu-connector-edit-form">+ <form className="cu-create-content cu-connector-edit-content" onSubmit={handleSave}><div className="cu-connector-edit-meta"><div><strong>Image:</strong>{' '}@@ -158,8 +181,13 @@ export default function EditMcpServerPage() {{saving ? 'Saving...' : 'Save egress'}</button></div>- </div>- </form>+ </form>++ <UpdateConnectorCredentials+ serverName={name}+ envSecret={resolveEnvSecret(server.spec as Record<string, unknown> | undefined)}+ />+ </div>) : null}</CreateFlowPanel></DashboardLayout>diff --git a/control-ui/components/UpdateConnectorCredentials/index.tsx b/control-ui/components/UpdateConnectorCredentials/index.tsxnew file mode 100644index 000000000..5a120dcfc--- /dev/null+++ b/control-ui/components/UpdateConnectorCredentials/index.tsx@@ -0,0 +1,359 @@+'use client'++import React, { useEffect, useState } from 'react'+import { useConfirmDialog } from '@components/ConfirmDialog'+import { useToast } from '@components/Toast'+import { Button, Field, FormSection, TextInput } from '@components/ui'+import { getMcpServer, getMcpServers, updateMcpSecret } from '@lib/api'+import type { McpServerCondition } from '@lib/api'+import type { RotationPhase, UpdateConnectorCredentialsProps } from './types'++// This timeout MUST stay strictly greater than the HCC's own readiness budget+// (host-context-controller reconciler.ts: pollReadiness, 24 attempts × 5s =+// 120s), plus room for the SecretInformer round-trip and one poll interval.+//+// The two budgets are not interchangeable: when a rollout fails, the HCC is the+// one that writes the verdict — DeploymentReady=False with the rollout numbers+// — at the END of its budget. If this timeout expired first, or at the same+// moment, the operator would be shown a bare "timed out" instead of the+// diagnosis that was about to arrive, and would have to go dig it out of the+// CRD by hand. Giving up before the system has finished answering is the+// difference between an actionable failure and a shrug.+// Exported so the tests drive fake timers off THESE values instead of keeping+// their own copy: a duplicated budget silently stops testing the real one the+// first time either side changes.+export const POLL_INTERVAL_MS = 3_000+export const POLL_TIMEOUT_MS = 180_000++// The `reason` the HCC stamps on DeploymentReady=False ONLY when the readiness+// poll has exhausted its budget — the terminal, actionable failure. Every other+// False (notably `WaitingForReplicas`) is a transitory rollout state. Must match+// host-context-controller/src/reconciler.ts.+export const ROLLOUT_INCOMPLETE_REASON = 'RolloutIncomplete'++// Slack subtracted from the client-side cutoff to absorb clock skew between the+// browser and the Kubernetes API server (which stamps lastTransitionTime). Must+// stay well under a real rollout's duration so a stale condition is still+// excluded. 5s comfortably covers ordinary NTP drift.+export const CLOCK_SKEW_TOLERANCE_MS = 5_000++function buildConfirmMessage(secretName: string, affected: string[] | null): string {+ if (affected === null) {+ return `This rotates the credential value(s) you entered in Secret "${secretName}" and restarts any connector that references it.`+ }+ if (affected.length === 0) {+ return `This rotates the credential value(s) you entered in Secret "${secretName}". No connector currently references this Secret, so nothing will restart.`+ }+ return `This rotates the credential value(s) you entered in Secret "${secretName}" and restarts: ${affected.join(', ')}.`+}++/**+ * Returns the McpServer's DeploymentReady condition ONLY if it transitioned+ * strictly after `cutoffIso` — the instant captured client-side right before+ * the rotation PUT was sent. A condition timestamped at or before the PUT is+ * the rollout's PREVIOUS state (e.g. the old pod staying Ready while the HCC+ * has not reconciled the new Secret yet); treating a stale True as success+ * would report a rotation that never happened (issue #223 plan, Fase 3 §6).+ */+function findFreshDeploymentReady(+ conditions: McpServerCondition[] | undefined,+ cutoffIso: string+): McpServerCondition | undefined {+ const condition = conditions?.find(c => c.type === 'DeploymentReady')+ if (!condition) return undefined+ const isFresh = new Date(condition.lastTransitionTime).getTime() > new Date(cutoffIso).getTime()+ return isFresh ? condition : undefined+}++export function UpdateConnectorCredentials({+ serverName,+ envSecret,+}: UpdateConnectorCredentialsProps) {+ const { showToast } = useToast()+ const { confirm, confirmDialog } = useConfirmDialog()++ const [draft, setDraft] = useState<Record<string, string>>({})+ const [validationError, setValidationError] = useState('')+ // Best-effort preview of "who restarts", shown in the pre-save confirm+ // dialog (requisito 5). The authoritative list only exists after the PUT+ // (Fase 1 regla 9) — this mirrors the server's own+ // `spec.envSecret.name === thisSecret` filter against the live connector+ // list so the operator sees the same answer before committing.+ const [previewAffected, setPreviewAffected] = useState<string[] | null>(null)++ const [phase, setPhase] = useState<RotationPhase>('idle')+ const [phaseMessage, setPhaseMessage] = useState('')+ const [rotationCutoff, setRotationCutoff] = useState<string | null>(null)+ const [rotationAffected, setRotationAffected] = useState<string[]>([])++ useEffect(() => {+ if (!envSecret) return+ let cancelled = false+ getMcpServers()+ .then(({ items }) => {+ if (cancelled) return+ const names = (items || [])+ .filter(item => {+ const candidate = item.spec?.envSecret as { name?: unknown } | undefined+ return Boolean(candidate) && candidate?.name === envSecret.name+ })+ .map(item => item.metadata?.name)+ .filter((n): n is string => typeof n === 'string')+ .sort((a, b) => a.localeCompare(b))+ setPreviewAffected(names)+ })+ .catch(() => {+ // Best-effort preview only. A failure here just falls back to the+ // generic (unnamed) confirm message — the authoritative list always+ // arrives from the PUT response once the operator confirms and saves.+ if (!cancelled) setPreviewAffected(null)+ })+ return () => {+ cancelled = true+ }+ }, [envSecret])++ // Poll THIS connector's own McpServer CRD until DeploymentReady resolves,+ // fails, or the bounded timeout expires. Success is NEVER declared from the+ // PUT's 200 alone (Fase 3 §4 corolario vinculante).+ useEffect(() => {+ if (phase !== 'rotating' || !rotationCutoff) return+ let cancelled = false+ const startedAt = Date.now()++ async function poll() {+ let latest: Awaited<ReturnType<typeof getMcpServer>>+ try {+ latest = await getMcpServer(serverName)+ } catch (e) {+ if (cancelled) return+ // A transient read failure resolves nothing either way — surface it+ // but keep polling until the bounded cap below fires.+ setPhaseMessage(+ `Could not check rollout status (${e instanceof Error ? e.message : 'request failed'}). Retrying…`+ )+ return+ }+ if (cancelled) return+ const fresh = findFreshDeploymentReady(latest.status?.conditions, rotationCutoff!)+ if (!fresh) return+ if (fresh.status === 'True') {+ setPhase('success')+ return+ }+ // A `False` DeploymentReady is NOT automatically a failure. The HCC writes+ // `False` with reason `WaitingForReplicas` synchronously right after the+ // rollout starts — the normal transitory state of EVERY rollout — and only+ // escalates to the terminal reason `RolloutIncomplete` once its readiness+ // poll exhausts its budget (host-context-controller reconciler.ts). Treating+ // the transitory `False` as failure would abort almost every successful+ // rotation on the first poll, seconds before the new pod goes Ready. So only+ // the terminal verdict counts as failure; any other non-True state+ // (WaitingForReplicas, Unknown) means "still rolling out" — keep polling+ // until success, the terminal failure, or the bounded timeout. This mirrors+ // the `reason === 'RolloutIncomplete'` discriminator the e2e helpers already+ // use (assertRolloutNeverSucceeds).+ if (fresh.status === 'False' && fresh.reason === ROLLOUT_INCOMPLETE_REASON) {+ setPhase('failed')+ setPhaseMessage(fresh.message || 'The connector rollout did not complete.')+ }+ }++ const id = setInterval(() => {+ if (Date.now() - startedAt >= POLL_TIMEOUT_MS) {+ clearInterval(id)+ if (!cancelled) {+ setPhase('timeout')+ setPhaseMessage(+ `The rollout did not finish within ${Math.round(POLL_TIMEOUT_MS / 1000)}s. Run ` ++ `"kubectl get mcpserver ${serverName} -o yaml" to see the current DeploymentReady ` ++ 'condition, or try the rotation again.'+ )+ }+ return+ }+ void poll()+ }, POLL_INTERVAL_MS)++ return () => {+ cancelled = true+ clearInterval(id)+ }+ }, [phase, rotationCutoff, serverName])++ if (!envSecret) {+ return (+ <FormSection title="Update credentials">+ <p className="cu-muted">+ This connector has no Kubernetes Secret configured for credentials — there is nothing to+ rotate here.+ </p>+ </FormSection>+ )+ }++ function updateField(secretKey: string, value: string) {+ setDraft(prev => ({ ...prev, [secretKey]: value }))+ if (validationError) setValidationError('')+ }++ async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {+ event.preventDefault()+ if (phase === 'saving' || phase === 'rotating') return++ const data: Record<string, string> = {}+ for (const key of envSecret!.keys) {+ const value = draft[key.secretKey]+ if (value && value.trim() !== '') data[key.secretKey] = value+ }+ if (Object.keys(data).length === 0) {+ setValidationError('Enter at least one credential value to rotate.')+ return+ }+ setValidationError('')++ const confirmed = await confirm({+ title: 'Rotate credentials',+ message: buildConfirmMessage(envSecret!.name, previewAffected),+ confirmLabel: 'Rotate & restart',+ tone: 'danger',+ })+ if (!confirmed) return++ // Captured BEFORE the PUT fires — the correlation anchor the poll below+ // uses to tell "this rotation's" DeploymentReady from a stale prior one.+ //+ // `lastTransitionTime` is stamped by the Kubernetes API server's clock,+ // while this cutoff is the browser's. If the browser runs slightly ahead of+ // the server (ordinary NTP skew), a genuinely fresh condition could carry a+ // timestamp just *before* this cutoff and be wrongly discarded, wedging the+ // UI until the 180s timeout. Back the anchor off by a small tolerance so+ // clock skew can't hide the rotation's own outcome. The window we widen is+ // harmless: a truly stale condition predates the PUT by the full rollout,+ // far more than this margin.+ const cutoff = new Date(Date.now() - CLOCK_SKEW_TOLERANCE_MS).toISOString()+ setPhase('saving')+ setPhaseMessage('')+ try {+ const result = await updateMcpSecret(envSecret!.name, data)+ setDraft({})+ setRotationAffected(result.affectedConnectors)+ setRotationCutoff(cutoff)+ setPhase('rotating')+ } catch (e) {+ setPhase('failed')+ setPhaseMessage(e instanceof Error ? e.message : 'Failed to rotate credentials')+ showToast('Failed to rotate credentials.', { tone: 'error' })+ }+ }++ function resetToIdle() {+ setPhase('idle')+ setPhaseMessage('')+ setRotationCutoff(null)+ setRotationAffected([])+ }++ const busy = phase === 'saving' || phase === 'rotating'+ const restartTargets = rotationAffected.length > 0 ? rotationAffected.join(', ') : serverName++ return (+ <FormSection+ title="Update credentials"+ description={+ <>+ Rotate values stored in Secret <code>{envSecret.name}</code>. Values are write-only — this+ screen never shows a stored credential, only key names.+ </>+ }+ >+ {confirmDialog}++ <div className="cu-table-wrap">+ <table className="cu-table">+ <thead>+ <tr>+ <th>Secret key</th>+ <th>Env var</th>+ </tr>+ </thead>+ <tbody>+ {envSecret.keys.map(k => (+ <tr key={k.secretKey}>+ <td>+ <code>{k.secretKey}</code>+ </td>+ <td>+ <code>{k.envVar}</code>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>++ <form className="cu-form-stack" onSubmit={handleSubmit}>+ {envSecret.keys.map(k => (+ <Field key={k.secretKey} htmlFor={`mcp-cred-${k.secretKey}`} label={k.secretKey}>+ <TextInput+ id={`mcp-cred-${k.secretKey}`}+ type="password"+ autoComplete="new-password"+ placeholder="Leave blank to keep current value"+ value={draft[k.secretKey] || ''}+ onChange={e => updateField(k.secretKey, e.target.value)}+ disabled={busy}+ />+ </Field>+ ))}++ {validationError ? (+ <div className="cu-banner cu-banner--error" role="alert">+ {validationError}+ </div>+ ) : null}++ {phase === 'rotating' ? (+ <div className="cu-banner cu-banner--info" role="status">+ Rotating credentials — waiting for {restartTargets} to restart with the new value.+ {phaseMessage ? ` ${phaseMessage}` : ''}+ </div>+ ) : null}++ {phase === 'success' ? (+ <div className="cu-banner cu-banner--ok" role="status">+ Credentials rotated. {restartTargets} restarted and is serving the new credential.+ </div>+ ) : null}++ {phase === 'failed' ? (+ <div className="cu-banner cu-banner--error" role="alert">+ Rotation failed: {phaseMessage}+ </div>+ ) : null}++ {phase === 'timeout' ? (+ <div className="cu-banner cu-banner--warning" role="alert">+ {phaseMessage}+ </div>+ ) : null}++ <div className="cu-create-actions">+ {phase === 'success' || phase === 'failed' || phase === 'timeout' ? (+ <Button type="button" onClick={resetToIdle}>+ {phase === 'success' ? 'Done' : 'Rotate again'}+ </Button>+ ) : (+ <Button type="submit" variant="primary" disabled={busy}>+ {phase === 'saving'+ ? 'Saving…'+ : phase === 'rotating'+ ? 'Rotating…'+ : 'Rotate credentials'}+ </Button>+ )}+ </div>+ </form>+ </FormSection>+ )+}diff --git a/control-ui/components/UpdateConnectorCredentials/types.ts b/control-ui/components/UpdateConnectorCredentials/types.tsnew file mode 100644index 000000000..af962b03f--- /dev/null+++ b/control-ui/components/UpdateConnectorCredentials/types.ts@@ -0,0 +1,30 @@+import type { EnvSecret } from '../../lib/api'++export type UpdateConnectorCredentialsProps = {+ /**+ * McpServer CRD name — the connector currently being edited. Also the+ * resource polled via getMcpServer() once a rotation is submitted: success+ * is derived exclusively from THIS connector's own DeploymentReady+ * condition, never from the PUT's 200 alone (issue #223 plan, Fase 3 §4).+ */+ serverName: string+ /**+ * server.spec.envSecret, or undefined when the connector has no+ * Kubernetes-Secret-backed credentials. The panel renders explanatory copy+ * instead of a form when this is unset.+ */+ envSecret: EnvSecret | undefined+}++/**+ * - idle: form is editable, nothing in flight.+ * - saving: the PUT to /admin/mcp-secrets/:name is in flight.+ * - rotating: the PUT returned 200; polling getMcpServer() for a fresh+ * DeploymentReady condition.+ * - success: a fresh DeploymentReady=True was observed after the PUT.+ * - failed: the PUT itself failed, OR a fresh DeploymentReady=False was+ * observed after the PUT.+ * - timeout: the bounded poll window elapsed without a fresh terminal+ * condition. Never reported as success.+ */+export type RotationPhase = 'idle' | 'saving' | 'rotating' | 'success' | 'failed' | 'timeout'diff --git a/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx b/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsxnew file mode 100644index 000000000..19f1eab4c--- /dev/null+++ b/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx@@ -0,0 +1,413 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'+import { ToastProvider } from '@components/Toast'+import {+ POLL_INTERVAL_MS,+ POLL_TIMEOUT_MS,+ UpdateConnectorCredentials,+} from '@components/UpdateConnectorCredentials'+import { getMcpServer, getMcpServers, updateMcpSecret } from '@lib/api'+import type { EnvSecret, McpServerResource } from '@lib/api'++vi.mock('@lib/api', () => ({+ getMcpServer: vi.fn(),+ getMcpServers: vi.fn(),+ updateMcpSecret: vi.fn(),+}))++const mockGetMcpServer = vi.mocked(getMcpServer)+const mockGetMcpServers = vi.mocked(getMcpServers)+const mockUpdateMcpSecret = vi.mocked(updateMcpSecret)++const SERVER_NAME = 'my-connector'+// secretKey and envVar are deliberately different strings so table/label+// assertions can't accidentally pass by matching the wrong column.+const ENV_SECRET: EnvSecret = {+ name: 'linear-credentials',+ keys: [+ { secretKey: 'api-key', envVar: 'LINEAR_API_KEY' },+ { secretKey: 'workspace-id', envVar: 'LINEAR_WORKSPACE' },+ ],+}++function serverWithCondition(condition?: {+ status: 'True' | 'False'+ message: string+ lastTransitionTime: string+ // Explicit reason so tests can distinguish the TRANSITORY False+ // (`WaitingForReplicas`, the normal mid-rollout state) from the TERMINAL+ // False (`RolloutIncomplete`). Defaults preserve the previous behavior.+ reason?: string+}): McpServerResource {+ return {+ metadata: { name: SERVER_NAME },+ status: condition+ ? {+ conditions: [+ {+ type: 'DeploymentReady',+ status: condition.status,+ reason:+ condition.reason ??+ (condition.status === 'True' ? 'RolloutComplete' : 'RolloutIncomplete'),+ message: condition.message,+ lastTransitionTime: condition.lastTransitionTime,+ },+ ],+ }+ : { conditions: [] },+ }+}++/** Drains chained microtasks (promise resolutions across multiple `await`+ * boundaries) without relying on real timers — safe to call under+ * `vi.useFakeTimers()`, unlike `waitFor`/`findBy*`, which poll via+ * `setTimeout` and would hang until timers are advanced. */+async function flush(ticks = 4) {+ for (let i = 0; i < ticks; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await act(async () => {+ await Promise.resolve()+ })+ }+}++// No default value on purpose: `renderPanel(undefined)` must render the+// no-envSecret state, but a JS default parameter substitutes ENV_SECRET for+// an explicit `undefined` argument, silently defeating that test. Callers+// always pass explicitly.+async function renderPanel(envSecret: EnvSecret | undefined) {+ const utils = render(+ <ToastProvider>+ <UpdateConnectorCredentials serverName={SERVER_NAME} envSecret={envSecret} />+ </ToastProvider>+ )+ // Flush the best-effort "who else uses this Secret" preview fetch+ // (getMcpServers) that fires on mount so it doesn't leak a pending state+ // update into a later assertion.+ await flush(2)+ return utils+}++/** Fills `keys` (secretKey -> value), submits, and confirms the rotation+ * dialog — draining the microtask chain in between so callers land on a+ * settled `phase`. */+async function submitRotation(keys: Record<string, string>) {+ for (const [secretKey, value] of Object.entries(keys)) {+ fireEvent.change(screen.getByLabelText(secretKey), { target: { value } })+ }+ fireEvent.click(screen.getByRole('button', { name: 'Rotate credentials' }))+ const dialog = screen.getByRole('alertdialog')+ fireEvent.click(within(dialog).getByRole('button', { name: 'Rotate & restart' }))+ await flush()+}++beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))+ mockGetMcpServers.mockResolvedValue({ items: [] })+})++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+ vi.useRealTimers()+})++describe('UpdateConnectorCredentials — no envSecret', () => {+ it('shows explanatory copy instead of a form when the connector has no managed credentials', async () => {+ await renderPanel(undefined)+ expect(+ screen.getByText(/has no Kubernetes Secret configured for credentials/i)+ ).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Rotate credentials' })).not.toBeInTheDocument()+ expect(screen.queryByRole('table')).not.toBeInTheDocument()+ })+})++describe('UpdateConnectorCredentials — masked inputs', () => {+ it('renders one empty, masked, no-autocomplete input per secret key and the key→env mapping', async () => {+ await renderPanel(ENV_SECRET)++ expect(screen.getByText(ENV_SECRET.name)).toBeInTheDocument()+ const table = screen.getByRole('table')+ for (const key of ENV_SECRET.keys) {+ expect(within(table).getByText(key.secretKey)).toBeInTheDocument()+ expect(within(table).getByText(key.envVar)).toBeInTheDocument()+ const input = screen.getByLabelText(key.secretKey) as HTMLInputElement+ expect(input).toHaveAttribute('type', 'password')+ expect(input).toHaveAttribute('autocomplete', 'new-password')+ expect(input.value).toBe('')+ }+ })++ it('never renders a stored credential value — inputs stay empty through a full rotation cycle', async () => {+ mockUpdateMcpSecret.mockResolvedValue({+ name: ENV_SECRET.name,+ namespace: 'mcp-server',+ keys: ['api-key'],+ affectedConnectors: [SERVER_NAME],+ })+ mockGetMcpServer.mockResolvedValue(+ serverWithCondition({+ status: 'True',+ message: 'ready',+ lastTransitionTime: '2026-01-01T00:00:05.000Z',+ })+ )++ await renderPanel(ENV_SECRET)+ await submitRotation({ 'api-key': 'sk-super-secret' })++ // The value the operator typed must never come back out of the form —+ // not as a rendered value, not as a placeholder.+ expect(screen.queryByText('sk-super-secret')).not.toBeInTheDocument()+ const input = screen.getByLabelText('api-key') as HTMLInputElement+ expect(input.value).toBe('')+ })+})++describe('UpdateConnectorCredentials — partial payload', () => {+ it('sends only the filled keys, never the untouched ones', async () => {+ mockUpdateMcpSecret.mockResolvedValue({+ name: ENV_SECRET.name,+ namespace: 'mcp-server',+ keys: ['api-key', 'workspace-id'],+ affectedConnectors: [SERVER_NAME],+ })+ mockGetMcpServer.mockResolvedValue(serverWithCondition(undefined))++ await renderPanel(ENV_SECRET)+ await submitRotation({ 'api-key': 'new-key-value' })++ expect(mockUpdateMcpSecret).toHaveBeenCalledTimes(1)+ expect(mockUpdateMcpSecret).toHaveBeenCalledWith(ENV_SECRET.name, {+ 'api-key': 'new-key-value',+ })+ })+})++describe('UpdateConnectorCredentials — client-side validation', () => {+ it('blocks submit and shows a validation error when no key is filled', async () => {+ await renderPanel(ENV_SECRET)++ fireEvent.click(screen.getByRole('button', { name: 'Rotate credentials' }))++ expect(screen.getByText('Enter at least one credential value to rotate.')).toBeInTheDocument()+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()+ expect(mockUpdateMcpSecret).not.toHaveBeenCalled()+ })+})++// ─── Polling / DeploymentReady correlation — the CRD contract (Fase 3 §6) ───+describe('UpdateConnectorCredentials — rollout polling', () => {+ it('reports success once a FRESH DeploymentReady=True is observed after the PUT', async () => {+ mockUpdateMcpSecret.mockResolvedValue({+ name: ENV_SECRET.name,+ namespace: 'mcp-server',+ keys: ['api-key'],+ affectedConnectors: [SERVER_NAME],+ })+ // First poll: a False condition that predates the PUT (stale) — must NOT+ // be read as an outcome of this rotation.+ mockGetMcpServer.mockResolvedValueOnce(+ serverWithCondition({+ status: 'False',+ message: 'rolling out',+ lastTransitionTime: '2025-12-31T23:59:00.000Z',+ })+ )+ // Second poll: True, timestamped AFTER the PUT.+ mockGetMcpServer.mockResolvedValueOnce(+ serverWithCondition({+ status: 'True',+ message: 'ready',+ lastTransitionTime: '2026-01-01T00:00:05.000Z',+ })+ )++ await renderPanel(ENV_SECRET)+ await submitRotation({ 'api-key': 'new-key-value' })++ expect(screen.getByText(/Rotating credentials/i)).toBeInTheDocument()+ expect(screen.queryByText(/Credentials rotated/i)).not.toBeInTheDocument()++ await act(async () => {+ await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS)+ })+ // Stale False must not have resolved anything yet.+ expect(screen.queryByText(/Credentials rotated/i)).not.toBeInTheDocument()+ expect(screen.queryByText(/Rotation failed/i)).not.toBeInTheDocument()++ await act(async () => {+ await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS)+ })+ expect(screen.getByText(/Credentials rotated\./i)).toBeInTheDocument()+ })++ it('keeps waiting through a FRESH transitory False (WaitingForReplicas) and only succeeds on True', async () => {+ // The real production sequence, which the old hardcoded-reason helper could+ // not express: right after the PUT the HCC writes DeploymentReady=False with+ // reason WaitingForReplicas (fresh, post-PUT) for the whole rollout window,+ // then True once the new pod is Ready. The UI must NOT read the transitory+ // False as failure — doing so would abort almost every successful rotation.+ mockUpdateMcpSecret.mockResolvedValue({+ name: ENV_SECRET.name,+ namespace: 'mcp-server',+ keys: ['api-key'],+ affectedConnectors: [SERVER_NAME],+ })+ // First two polls: transitory False, timestamped AFTER the PUT.+ mockGetMcpServer+ .mockResolvedValueOnce(+ serverWithCondition({+ status: 'False',+ reason: 'WaitingForReplicas',+ message: 'Waiting for pods to become ready',+ lastTransitionTime: '2026-01-01T00:00:02.000Z',+ })+ )+ .mockResolvedValueOnce(+ serverWithCondition({+ status: 'False',+ reason: 'WaitingForReplicas',+ message: 'Waiting for pods to become ready',+ lastTransitionTime: '2026-01-01T00:00:02.000Z',+ })+ )+ // Third poll: converged.+ .mockResolvedValue(+ serverWithCondition({+ status: 'True',+ message: 'ready',+ lastTransitionTime: '2026-01-01T00:00:10.000Z',+ })+ )++ await renderPanel(ENV_SECRET)+ await submitRotation({ 'api-key': 'new-key-value' })++ // Two polls of transitory False must NOT be reported as failure.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS)+ })+ expect(screen.queryByText(/Rotation failed/i)).not.toBeInTheDocument()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS)+ })+ expect(screen.queryByText(/Rotation failed/i)).not.toBeInTheDocument()+ expect(screen.getByText(/Rotating credentials/i)).toBeInTheDocument()++ // Third poll converges to success.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS)+ })+ expect(screen.getByText(/Credentials rotated\./i)).toBeInTheDocument()+ })++ it('reports failure only on the TERMINAL False (reason RolloutIncomplete)', async () => {+ mockUpdateMcpSecret.mockResolvedValue({+ name: ENV_SECRET.name,+ namespace: 'mcp-server',+ keys: ['api-key'],+ affectedConnectors: [SERVER_NAME],+ })+ mockGetMcpServer.mockResolvedValue(+ serverWithCondition({+ status: 'False',+ reason: 'RolloutIncomplete',+ message: 'Rollout did not converge — ready 0/1, unavailable 1',+ lastTransitionTime: '2026-01-01T00:02:05.000Z',+ })+ )++ await renderPanel(ENV_SECRET)+ await submitRotation({ 'api-key': 'new-key-value' })++ await act(async () => {+ await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS)+ })+ expect(screen.getByText(/Rotation failed:.*ready 0\/1/)).toBeInTheDocument()+ })++ it('keeps waiting when DeploymentReady=True predates the PUT (stale success must not count)', async () => {+ mockUpdateMcpSecret.mockResolvedValue({+ name: ENV_SECRET.name,+ namespace: 'mcp-server',+ keys: ['api-key'],+ affectedConnectors: [SERVER_NAME],+ })+ mockGetMcpServer.mockResolvedValue(+ serverWithCondition({+ status: 'True',+ message: 'ready (old rollout)',+ lastTransitionTime: '2020-01-01T00:00:00.000Z',+ })+ )++ await renderPanel(ENV_SECRET)+ await submitRotation({ 'api-key': 'new-key-value' })++ await act(async () => {+ await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 3)+ })++ expect(screen.queryByText(/Credentials rotated/i)).not.toBeInTheDocument()+ expect(screen.getByText(/Rotating credentials/i)).toBeInTheDocument()+ })++ it('reports failure with the condition message when DeploymentReady=False after the PUT', async () => {+ mockUpdateMcpSecret.mockResolvedValue({+ name: ENV_SECRET.name,+ namespace: 'mcp-server',+ keys: ['api-key'],+ affectedConnectors: [SERVER_NAME],+ })+ mockGetMcpServer.mockResolvedValue(+ serverWithCondition({+ status: 'False',+ message: 'pod CrashLoopBackOff: 0/1 ready',+ lastTransitionTime: '2026-01-01T00:00:03.000Z',+ })+ )++ await renderPanel(ENV_SECRET)+ await submitRotation({ 'api-key': 'new-key-value' })++ await act(async () => {+ await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS)+ })++ expect(+ screen.getByText(/Rotation failed: pod CrashLoopBackOff: 0\/1 ready/)+ ).toBeInTheDocument()+ expect(screen.queryByText(/Credentials rotated/i)).not.toBeInTheDocument()+ })++ it('reports a bounded timeout — never success — when the condition never transitions', async () => {+ mockUpdateMcpSecret.mockResolvedValue({+ name: ENV_SECRET.name,+ namespace: 'mcp-server',+ keys: ['api-key'],+ affectedConnectors: [SERVER_NAME],+ })+ // Always stale: predates the PUT on every single poll.+ mockGetMcpServer.mockResolvedValue(+ serverWithCondition({+ status: 'False',+ message: 'rolling out',+ lastTransitionTime: '2020-01-01T00:00:00.000Z',+ })+ )++ await renderPanel(ENV_SECRET)+ await submitRotation({ 'api-key': 'new-key-value' })++ await act(async () => {+ await vi.advanceTimersByTimeAsync(POLL_TIMEOUT_MS + POLL_INTERVAL_MS)+ })++ expect(screen.getByText(/did not finish within/i)).toBeInTheDocument()+ expect(screen.queryByText(/Credentials rotated/i)).not.toBeInTheDocument()+ })+})diff --git a/control-ui/e2e/qa-recorder-connector-edit.spec.ts b/control-ui/e2e/qa-recorder-connector-edit.spec.tsindex 2daa6850e..deb9dd5e1 100644--- a/control-ui/e2e/qa-recorder-connector-edit.spec.ts+++ b/control-ui/e2e/qa-recorder-connector-edit.spec.ts@@ -48,6 +48,65 @@ async function createEmptyContext(page: Page, contextName: string): Promise<void).toBeVisible({ timeout: 20_000 })}+// Creates a stdio connector backed by a single-key Kubernetes Secret (the+// "Use Kubernetes Secret for credentials" path of the create form) so the+// credential-rotation journey below has a real envSecret to rotate against.+async function createSecretBackedConnector(+ page: Page,+ connectorName: string,+ contextName: string,+ secretName: string,+ secretKey: string,+ envVar: string,+ initialValue: string+): Promise<void> {+ await page.getByRole('link', { name: 'Connectors', exact: true }).click()+ await expect(page).toHaveURL(/\/connectors$/, { timeout: 20_000 })+ await page.getByRole('button', { name: 'Create Connector', exact: true }).click()+ await expect(page).toHaveURL(/\/connectors\/new$/, { timeout: 20_000 })++ await page.getByPlaceholder('my-mcp-server').fill(connectorName)+ await page+ .getByPlaceholder('us-central1-docker.pkg.dev/my-project/repo/mcp-server:latest')+ .fill('qa-recorder/example:dev')+ await page+ .getByPlaceholder('Optional description of this connector')+ .fill('QA recorder credential-rotation connector')++ const contextDropdown = page.locator('.cu-selection-dropdown__button')+ await expect(contextDropdown).toBeEnabled({ timeout: 20_000 })+ await contextDropdown.click()+ await expect(page.getByPlaceholder('Search contexts...')).toBeVisible({ timeout: 20_000 })+ const contextOption = page.getByRole('option', { name: contextName, exact: true })+ await expect(contextOption).toBeVisible({ timeout: 20_000 })+ await contextOption.click()++ await page.getByRole('button', { name: 'Continue', exact: true }).click()++ await fieldSelect(page, 'Transport Type', 'stdio')+ await fieldSelect(page, 'Managed', 'false')++ await page.getByRole('button', { name: 'Continue', exact: true }).click()++ await expect(page.getByText('External Egress', { exact: true })).toBeVisible({ timeout: 20_000 })+ await page.getByRole('button', { name: 'Continue', exact: true }).click()++ await page+ .getByRole('checkbox', { name: 'Use Kubernetes Secret for credentials', exact: true })+ .check()+ await page.getByPlaceholder('brave-search-credentials').fill(secretName)+ await page.getByRole('button', { name: 'Add Key Mapping', exact: true }).click()+ await page.getByPlaceholder('api-key').fill(secretKey)+ await page.getByPlaceholder('BRAVE_API_KEY').fill(envVar)+ await page.getByPlaceholder('sk-...').fill(initialValue)++ await page.getByRole('button', { name: 'Create connector', exact: true }).click()+ await expect(page.getByText('Connector created successfully.', { exact: true })).toBeVisible({+ timeout: 20_000,+ })+ await expect(page).toHaveURL(/\/connectors$/, { timeout: 20_000 })+}+async function createDiscoveryConnector(page: Page,connectorName: string,@@ -157,4 +216,103 @@ test.describe('optional QA recorder: Control UI connector edit', () => {await api(page.request, 'DELETE', `/api/v1/admin/contexts/${encodeURIComponent(contextName)}`)}})++ // Issue #223: rotates a connector's credential through the "Update+ // credentials" section and rides the polling out to a terminal state.+ // Precondition-only navigation (page.goto to the edit screen) is fine, but+ // the rotation itself — filling the new value, confirming the restart+ // warning, saving, watching the status settle — is driven exclusively by+ // real user actions against the live control-api/HCC, never a direct PUT,+ // never a mocked backend, never `waitForTimeout`.+ test('records rotating a connector credential and reaching a terminal rollout state', async ({+ page,+ }, testInfo) => {+ requireRecorderConfirm(+ 'QA_RECORDER_CONFIRM_MUTATIONS',+ 'This journey creates a context, a Secret-backed connector, rotates the credential through the UI, and deletes them all.'+ )+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)++ const credentials = adminCredentials()+ const contextName = uniqueE2EName('qa-recorder-context')+ const connectorName = uniqueE2EName('qa-recorder-connector')+ const secretName = uniqueE2EName('qa-recorder-secret')+ const secretKey = 'api-key'+ const envVar = 'QA_RECORDER_API_KEY'++ try {+ await loginThroughUi(page, credentials)++ await createEmptyContext(page, contextName)+ await createSecretBackedConnector(+ page,+ connectorName,+ contextName,+ secretName,+ secretKey,+ envVar,+ 'initial-value-123'+ )++ await page.goto(`${CONTROL_UI_URL}/connectors/${encodeURIComponent(connectorName)}/edit`)+ await expect(+ page.getByRole('heading', { name: `Edit Connector: ${connectorName}`, exact: true })+ ).toBeVisible({ timeout: 20_000 })++ // The section names the Secret and the key -> env var mapping — names+ // only, never the stored value.+ await expect(page.getByText(secretName, { exact: true })).toBeVisible({ timeout: 20_000 })+ const mappingTable = page.locator('table', { hasText: secretKey })+ await expect(mappingTable).toBeVisible({ timeout: 20_000 })+ await expect(mappingTable.getByText(secretKey, { exact: true })).toBeVisible()+ await expect(mappingTable.getByText(envVar, { exact: true })).toBeVisible()+ await expect(page.getByText('initial-value-123')).toHaveCount(0)++ // Real user action: type into the masked, empty input — never+ // pre-filled with the stored value.+ const credentialInput = page.locator(`#mcp-cred-${secretKey}`)+ await expect(credentialInput).toBeVisible({ timeout: 20_000 })+ await expect(credentialInput).toHaveAttribute('type', 'password')+ await expect(credentialInput).toHaveValue('')+ await credentialInput.fill('rotated-value-456')++ await page.getByRole('button', { name: 'Rotate credentials', exact: true }).click()++ // Explicit confirmation gate before anything is sent to the server.+ const confirmDialog = page.getByRole('alertdialog', { name: 'Rotate credentials' })+ await expect(confirmDialog).toBeVisible({ timeout: 20_000 })+ await confirmDialog.getByRole('button', { name: 'Rotate & restart', exact: true }).click()++ // The PUT landing shows "rotating", never a verdict by itself — the+ // verdict only comes from the CRD poll below.+ await expect(page.getByText(/Rotating credentials/)).toBeVisible({ timeout: 20_000 })++ // This rotates to a VALID credential, so the connector must come back+ // healthy: the terminal state is SUCCESS. A bounded "did not finish+ // within" is tolerated as cluster slowness. But "Rotation failed:" is NOT+ // an acceptable outcome here — it would mean the UI reported the normal+ // transitory DeploymentReady=False/WaitingForReplicas as a failure (the+ // B1 defect). Accepting it (as this spec used to) let the bug pass in+ // green; asserting its absence makes the test catch a regression.+ await expect(+ page.getByText(/Credentials rotated\./).or(page.getByText(/did not finish within/))+ ).toBeVisible({ timeout: 150_000 })+ await expect(page.getByText(/Rotation failed:/)).toHaveCount(0)++ await screenshotAndLog(page, testInfo, 'control-ui-connector-credential-rotation')+ } finally {+ await api(+ page.request,+ 'DELETE',+ `/api/v1/admin/mcp-servers/${encodeURIComponent(connectorName)}`+ )+ await api(+ page.request,+ 'DELETE',+ `/api/v1/admin/mcp-secrets/${encodeURIComponent(secretName)}`+ )+ await api(page.request, 'DELETE', `/api/v1/admin/contexts/${encodeURIComponent(contextName)}`)+ }+ })})diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex a569ae34f..885ed34a1 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -792,9 +792,26 @@ export type HostResource = {conditions?: HostStatusCondition[]}}+/**+ * Condition entry on `status.conditions[]` of the McpServer CRD, as written by+ * the HCC reconciler (host-context-controller/src/reconciler.ts). `status` is+ * the K8s-standard string tri-state, not a boolean. `lastTransitionTime` only+ * advances when `status` itself changes (writeStatusCondition) — the UI relies+ * on that to tell "this rollout" apart from a stale prior condition (issue #223,+ * Fase 3 requisito 6).+ */+export type McpServerCondition = {+ type: string+ status: 'True' | 'False' | 'Unknown'+ reason: string+ message: string+ lastTransitionTime: string+}+export type McpServerResource = {metadata?: Metadataspec?: AnyRecord+ status?: { conditions?: McpServerCondition[] }}export type ContextUser = {id: string@@ -1317,6 +1334,29 @@ export async function deleteMcpSecret(name: string) {}>}+/**+ * Rotates one or more keys on an EXISTING MCP Server Secret (issue #223).+ * `data` carries only the keys the operator wants to rotate — every other key+ * already on the Secret survives untouched (server-side merge-patch). The+ * response is names-only: `keys` lists the resulting key names (never+ * values), and `affectedConnectors` names every McpServer whose+ * `spec.envSecret.name` matches this Secret, so the UI can tell the operator+ * exactly what is about to restart. Saving does NOT restart anything itself —+ * the HCC's SecretInformer reacts to the Secret change and rolls the affected+ * Deployments; the caller must poll getMcpServer() for DeploymentReady to know+ * whether the rollout actually landed (see control-ui/components/UpdateConnectorCredentials).+ */+export async function updateMcpSecret(name: string, data: Record<string, string>) {+ return apiSend('PUT', `/api/v1/admin/mcp-secrets/${encodeURIComponent(name)}`, {+ data,+ }) as Promise<{+ name: string+ namespace: string+ keys: string[]+ affectedConnectors: string[]+ }>+}+export type RecipeSecretOwnership =| { kind: 'shared' }| { kind: 'owner-recipe'; recipeName: string }diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 5a3548a48..d102ab4ed 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.361",+ "version": "0.1.362","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.361",+ "version": "0.1.362","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex c6155ff42..53126bbb8 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.361",+ "version": "0.1.362","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/deploy/base/mcp-server/rbac.yaml b/deploy/base/mcp-server/rbac.yamlindex c2d5ff354..27369ac1f 100644--- a/deploy/base/mcp-server/rbac.yaml+++ b/deploy/base/mcp-server/rbac.yaml@@ -15,9 +15,20 @@ rules:verbs: ["get", "list"]# Secrets: required for registry install flow with credentials# (api-key/bearer-token/oauth2 tokens stored as K8s Secrets in mcp-server ns)+ #+ # `patch` (issue #223) backs connector credential rotation:+ # PUT /admin/mcp-secrets/:name uses gateway.mergeSecret(), an RFC 7396+ # merge-patch the API server applies atomically, so rotating one key cannot+ # wipe the other credentials on the same Secret and two concurrent rotations+ # cannot race. The alternative — read-then-replace, as PUT /admin/secrets+ # does in the secrets namespace — carries exactly that race.+ #+ # Scope note: RBAC has no wildcards in resourceNames, so this verb applies to+ # every Secret in this namespace, and it also enables removeSecretKey().+ # No route other than the rotation endpoint uses either today.- apiGroups: [""]resources: ["secrets"]- verbs: ["get", "list", "create", "update", "delete"]+ verbs: ["get", "list", "create", "update", "patch", "delete"]---apiVersion: rbac.authorization.k8s.io/v1kind: RoleBindingdiff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 2e04d1e84..e5333af94 100644--- a/host-context-controller/package-lock.json+++ b/host-context-controller/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-host-context-controller",- "version": "0.1.158",+ "version": "0.1.159","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.158",+ "version": "0.1.159","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/image-policy": "file:../packages/image-policy",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 32eca539e..221dc92d7 100644--- a/host-context-controller/package.json+++ b/host-context-controller/package.json@@ -1,6 +1,6 @@{"name": "clerum-host-context-controller",- "version": "0.1.158",+ "version": "0.1.159","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/__tests__/reconciler.credentialsRotation.test.ts b/host-context-controller/src/__tests__/reconciler.credentialsRotation.test.tsnew file mode 100644index 000000000..f8d6857cb--- /dev/null+++ b/host-context-controller/src/__tests__/reconciler.credentialsRotation.test.ts@@ -0,0 +1,550 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import * as k8s from '@kubernetes/client-node'+import {+ asAppsApi,+ asCoreApi,+ asCustomApi,+ createMockAppsApi,+ createMockCoreApi,+ createMockCustomApi,+} from '../../test/__fixtures__/testMocks'+import { McpServerReconciler } from '../reconciler'+import { McpServerCRD } from '../types'++vi.mock('../config', () => ({+ config: {+ devMode: false,+ port: 8081,+ namespace: 'mcp-server',+ hostNamespace: 'mcp-host',+ mcpServerImagePullPolicy: 'IfNotPresent',+ egressProxyImage: 'clerum/nginx-egress-proxy:0.1.0',+ stdioBridgeImage: 'clerum/stdio-bridge:test',+ stdioBridgeResources: {+ requests: { cpu: '50m', memory: '64Mi' },+ limits: { cpu: '200m', memory: '128Mi' },+ },+ devMcpServers: [],+ devContexts: [],+ devAuthTokens: new Map(),+ },+}))++const CREDENTIALS_REVISION_ANNOTATION = 'clerum.io/credentials-revision'++function makeServer(withEnvSecret = true): McpServerCRD {+ return {+ name: 'linear',+ namespace: 'mcp-server',+ uid: 'uid-linear-1234',+ spec: {+ contextRef: 'ctx1',+ image: 'linear-mcp:v1',+ transport: { type: 'streamableHttp', port: 3000, url: 'http://linear.mcp-server.svc:3000' },+ ...(withEnvSecret && {+ envSecret: {+ name: 'linear-credentials',+ keys: [{ secretKey: 'api-key', envVar: 'LINEAR_API_KEY' }],+ },+ }),+ },+ }+}++/** base64 of `value`, the form a Secret's `data` actually carries. */+function stored(value: string): string {+ return Buffer.from(value, 'utf8').toString('base64')+}++function createdDeployment(appsApi: ReturnType<typeof createMockAppsApi>): k8s.V1Deployment {+ const call = appsApi.createNamespacedDeployment.mock.calls[0]+ return (call[0] as { body: k8s.V1Deployment }).body+}++function credentialsRevisionOf(deployment: k8s.V1Deployment): string | undefined {+ return deployment.spec?.template?.metadata?.annotations?.[CREDENTIALS_REVISION_ANNOTATION]+}++/**+ * Every DeploymentReady condition written to the CRD, oldest first. Conditions+ * travel as a JSON Patch on the status subresource, so this digs the condition+ * out of the patch document.+ */+function deploymentReadyWrites(customApi: ReturnType<typeof createMockCustomApi>): Array<{+ status: string+ reason: string+ message: string+}> {+ return customApi.patchNamespacedCustomObjectStatus.mock.calls+ .flatMap(call => {+ const body = (call[0] as { body?: unknown }).body+ return Array.isArray(body) ? body : []+ })+ .flatMap((op: unknown) => {+ const value = (op as { value?: unknown }).value+ const conditions = Array.isArray(value)+ ? value+ : ((value as { conditions?: unknown[] })?.conditions ?? [])+ return Array.isArray(conditions) ? conditions : []+ })+ .filter((c: unknown) => (c as { type?: string }).type === 'DeploymentReady')+ .map((c: unknown) => c as { status: string; reason: string; message: string })+}++/** A Deployment whose rollout has fully converged. */+function convergedDeployment(name?: string) {+ return {+ metadata: { name, resourceVersion: '1', generation: 2, labels: {} },+ spec: { replicas: 1 },+ status: {+ observedGeneration: 2,+ replicas: 1,+ updatedReplicas: 1,+ readyReplicas: 1,+ unavailableReplicas: 0,+ },+ }+}++describe('connector credentials revision (issue #223)', () => {+ const appsApi = createMockAppsApi()+ const coreApi = createMockCoreApi()+ const customApi = createMockCustomApi()+ let reconciler: McpServerReconciler++ beforeEach(() => {+ vi.clearAllMocks()+ coreApi.readNamespacedSecret.mockResolvedValue({+ metadata: { name: 'linear-credentials' },+ data: { 'api-key': stored('old-key') },+ })+ reconciler = new McpServerReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(coreApi),+ customApi: asCustomApi(customApi),+ })+ })++ it('stamps the pod template with a revision derived from the secret content', async () => {+ await reconciler.reconcile(makeServer())++ const revision = credentialsRevisionOf(createdDeployment(appsApi))+ expect(revision).toMatch(/^[0-9a-f]{64}$/)+ })++ it('produces the same revision when only the key ORDER differs', async () => {+ coreApi.readNamespacedSecret.mockResolvedValue({+ data: { 'api-key': stored('k1'), 'webhook-secret': stored('k2') },+ })+ await reconciler.reconcile(makeServer())+ const first = credentialsRevisionOf(createdDeployment(appsApi))++ vi.clearAllMocks()+ coreApi.readNamespacedSecret.mockResolvedValue({+ data: { 'webhook-secret': stored('k2'), 'api-key': stored('k1') },+ })+ await reconciler.reconcile(makeServer())+ const second = credentialsRevisionOf(createdDeployment(appsApi))++ // Key order is an artifact of how the API server answered, not a change in+ // credentials: it must never roll a pod.+ expect(second).toBe(first)+ })++ it('produces a different revision when a credential VALUE changes', async () => {+ await reconciler.reconcile(makeServer())+ const before = credentialsRevisionOf(createdDeployment(appsApi))++ vi.clearAllMocks()+ coreApi.readNamespacedSecret.mockResolvedValue({+ data: { 'api-key': stored('rotated-key') },+ })+ await reconciler.reconcile(makeServer())+ const after = credentialsRevisionOf(createdDeployment(appsApi))++ // This difference IS the rollout: same pod template otherwise.+ expect(after).not.toBe(before)+ })++ it('writes no annotation for a connector without envSecret', async () => {+ await reconciler.reconcile(makeServer(false))++ const annotations = createdDeployment(appsApi).spec?.template?.metadata?.annotations+ expect(annotations?.[CREDENTIALS_REVISION_ANNOTATION]).toBeUndefined()+ })++ it('keeps the new revision when replacing over an existing Deployment', async () => {+ // The update path: create answers 409, then read+replace runs the desired+ // object through preserveDeploymentAnnotations. The stale revision on the+ // live object must not win — otherwise a rotation would write the OLD+ // digest back and the pod would never roll.+ appsApi.createNamespacedDeployment.mockRejectedValueOnce(+ Object.assign(new Error('already exists'), { code: 409 })+ )+ appsApi.readNamespacedDeployment.mockResolvedValue({+ metadata: { name: 'linear', resourceVersion: '7', generation: 1, labels: {} },+ spec: {+ replicas: 1,+ template: {+ metadata: {+ annotations: {+ [CREDENTIALS_REVISION_ANNOTATION]: 'stale-revision',+ 'operator.io/keep-me': 'yes',+ },+ },+ },+ },+ status: { observedGeneration: 1, replicas: 1, updatedReplicas: 1, readyReplicas: 1 },+ })++ await reconciler.reconcile(makeServer())++ const replaced = appsApi.replaceNamespacedDeployment.mock.calls[0][0] as {+ body: k8s.V1Deployment+ }+ const annotations = replaced.body.spec?.template?.metadata?.annotations+ expect(annotations?.[CREDENTIALS_REVISION_ANNOTATION]).toMatch(/^[0-9a-f]{64}$/)+ expect(annotations?.[CREDENTIALS_REVISION_ANNOTATION]).not.toBe('stale-revision')+ // Unrelated operator annotations still survive the replace.+ expect(annotations?.['operator.io/keep-me']).toBe('yes')+ })+})++describe('generation-aware rollout readiness (issue #223)', () => {+ const appsApi = createMockAppsApi()+ const coreApi = createMockCoreApi()+ const customApi = createMockCustomApi()+ let reconciler: McpServerReconciler++ beforeEach(() => {+ vi.clearAllMocks()+ coreApi.readNamespacedSecret.mockResolvedValue({ data: { 'api-key': stored('old-key') } })+ reconciler = new McpServerReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(coreApi),+ customApi: asCustomApi(customApi),+ })+ })++ it('is NOT ready while the controller has not observed the current generation', async () => {+ appsApi.readNamespacedDeployment.mockResolvedValue({+ metadata: { generation: 3, labels: {} },+ spec: { replicas: 1 },+ // The old pod is still Ready — the trap the pre-#223 check fell into.+ status: { observedGeneration: 2, updatedReplicas: 1, readyReplicas: 1 },+ })++ await reconciler.reconcile(makeServer())++ expect(deploymentReadyWrites(customApi).at(-1)?.status).toBe('False')+ })++ it('is NOT ready while replicas are not yet updated', async () => {+ appsApi.readNamespacedDeployment.mockResolvedValue({+ metadata: { generation: 2, labels: {} },+ spec: { replicas: 2 },+ status: { observedGeneration: 2, updatedReplicas: 1, readyReplicas: 2 },+ })++ await reconciler.reconcile(makeServer())++ expect(deploymentReadyWrites(customApi).at(-1)?.status).toBe('False')+ })++ it('is NOT ready while a replica is unavailable', async () => {+ appsApi.readNamespacedDeployment.mockResolvedValue({+ metadata: { generation: 2, labels: {} },+ spec: { replicas: 1 },+ status: {+ observedGeneration: 2,+ updatedReplicas: 1,+ readyReplicas: 1,+ unavailableReplicas: 1,+ },+ })++ await reconciler.reconcile(makeServer())++ expect(deploymentReadyWrites(customApi).at(-1)?.status).toBe('False')+ })++ it('is ready only once the rollout has fully converged', async () => {+ appsApi.readNamespacedDeployment.mockResolvedValue(convergedDeployment('linear'))++ await reconciler.reconcile(makeServer())++ expect(deploymentReadyWrites(customApi).at(-1)?.status).toBe('True')+ })++ it('is NOT ready while a crash-looping new pod leaves the OLD pod behind (failed rollout, E2)', async () => {+ // The trap that a bare readyReplicas/unavailableReplicas check misses: with+ // replicas=1 + RollingUpdate(maxSurge=1, maxUnavailable=0), a new pod that+ // crash-loops on a bad credential never goes Ready, so K8s keeps the OLD+ // pod. That old pod holds readyReplicas=1 and availableReplicas=1, so+ // unavailableReplicas=0 and updatedReplicas=1 — everything looks converged+ // EXCEPT status.replicas, which stays at 2 (old + crash-looping new). This+ // is exactly the e2e E2 scenario; without `totalReplicas === updatedReplicas`+ // the poll reports the failed rotation as healthy.+ appsApi.readNamespacedDeployment.mockResolvedValue({+ metadata: { generation: 2, labels: {} },+ spec: { replicas: 1 },+ status: {+ observedGeneration: 2,+ replicas: 2, // old pod still present alongside the crash-looping new one+ updatedReplicas: 1,+ readyReplicas: 1, // the OLD pod masks the failure+ availableReplicas: 1,+ unavailableReplicas: 0,+ },+ })++ await reconciler.reconcile(makeServer())++ expect(deploymentReadyWrites(customApi).at(-1)?.status).toBe('False')+ })+})++/**+ * Composition tests. Each half works in isolation — the readiness check reads+ * the Deployment correctly, and updateStatusConditions writes the CRD+ * correctly — but before #223 nothing called the second after the first+ * converged, so a successful rotation never reached the CRD. These two tests+ * fail against that arrangement; they are the regression guard.+ */+describe('the readiness poll must publish its verdict on the CRD (issue #223)', () => {+ const appsApi = createMockAppsApi()+ const coreApi = createMockCoreApi()+ const customApi = createMockCustomApi()+ let reconciler: McpServerReconciler++ beforeEach(() => {+ vi.clearAllMocks()+ vi.useFakeTimers()+ coreApi.readNamespacedSecret.mockResolvedValue({ data: { 'api-key': stored('old-key') } })+ reconciler = new McpServerReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(coreApi),+ customApi: asCustomApi(customApi),+ })+ })++ afterEach(() => {+ vi.useRealTimers()+ })++ it('writes DeploymentReady=True once the poll sees the rollout converge', async () => {+ // Mid-rollout at reconcile time (the normal state right after a write),+ // converged by the time the poll runs.+ appsApi.readNamespacedDeployment+ .mockResolvedValueOnce({+ metadata: { generation: 2, labels: {} },+ spec: { replicas: 1 },+ status: { observedGeneration: 1, updatedReplicas: 0, readyReplicas: 1 },+ })+ .mockResolvedValue(convergedDeployment('linear'))++ await reconciler.reconcile(makeServer())+ await vi.advanceTimersByTimeAsync(5000)++ expect(deploymentReadyWrites(customApi).at(-1)?.status).toBe('True')+ })++ it('converges from the immediate False to a later True, instead of staying False', async () => {+ appsApi.readNamespacedDeployment+ .mockResolvedValueOnce({+ metadata: { generation: 2, labels: {} },+ spec: { replicas: 1 },+ status: { observedGeneration: 1, updatedReplicas: 0, readyReplicas: 1 },+ })+ .mockResolvedValue(convergedDeployment('linear'))++ await reconciler.reconcile(makeServer())+ const beforePoll = deploymentReadyWrites(customApi).map(c => c.status)+ await vi.advanceTimersByTimeAsync(5000)+ const afterPoll = deploymentReadyWrites(customApi).map(c => c.status)++ // Generation-aware readiness makes the immediate verdict False by+ // construction, so a terminal False here would mean every successful+ // rotation is reported as a failure.+ expect(beforePoll).toContain('False')+ expect(afterPoll.at(-1)).toBe('True')+ })++ it('gives up loudly on the CRD, with the rollout numbers, when it never converges', async () => {+ appsApi.readNamespacedDeployment.mockResolvedValue({+ metadata: { generation: 2, labels: {} },+ spec: { replicas: 1 },+ status: {+ observedGeneration: 2,+ updatedReplicas: 1,+ readyReplicas: 0,+ unavailableReplicas: 1,+ },+ })++ await reconciler.reconcile(makeServer())+ // 24 polls × 5s, the full budget.+ await vi.advanceTimersByTimeAsync(24 * 5000)++ const last = deploymentReadyWrites(customApi).at(-1)+ expect(last?.status).toBe('False')+ expect(last?.reason).toBe('RolloutIncomplete')+ // The message must carry evidence, not just "not ready".+ expect(last?.message).toContain('ready 0/1')+ expect(last?.message).toContain('unavailable 1')+ })++ it('still reaches the terminal RolloutIncomplete verdict when repeated reconciles fire during the poll window (status-update-loop, E2)', async () => {+ // Failed credential rotation: the crash-looping new pod leaves the OLD pod+ // behind, so the rollout never converges (total 2 vs updated 1) — the+ // exact E2 shape. Deployment generation never changes: same rollout.+ appsApi.readNamespacedDeployment.mockResolvedValue({+ metadata: { generation: 2, labels: {} },+ spec: { replicas: 1 },+ status: {+ observedGeneration: 2,+ replicas: 2,+ updatedReplicas: 1,+ readyReplicas: 1,+ availableReplicas: 1,+ unavailableReplicas: 0,+ },+ })++ await reconciler.reconcile(makeServer())++ // Every status write fires a MODIFIED watch event on the McpServer, which+ // fires another reconcile MID-POLL. Before the fix each of these calls+ // cancelled the running poll and reset its attempt budget, so the poll+ // never exhausted and RolloutIncomplete was never written — the CRD sat+ // at WaitingForReplicas until the UI's generic timeout. 12 × 10s = 120s,+ // the full 24 × 5s budget, with a reconcile landing every 2 polls.+ for (let i = 0; i < 12; i++) {+ await vi.advanceTimersByTimeAsync(2 * 5000)+ await reconciler.reconcile(makeServer())+ }++ const last = deploymentReadyWrites(customApi).at(-1)+ expect(last?.status).toBe('False')+ // The reconcile that follows the terminal write must not downgrade the+ // verdict back to WaitingForReplicas — the LAST write stays terminal.+ expect(last?.reason).toBe('RolloutIncomplete')+ expect(last?.message).toContain('total 2')+ })++ it('grants a NEW rotation (bumped Deployment generation) a fresh poll budget mid-window', async () => {+ const notConverged = (generation: number) => ({+ metadata: { generation, labels: {} },+ spec: { replicas: 1 },+ status: {+ observedGeneration: generation,+ replicas: 2,+ updatedReplicas: 1,+ readyReplicas: 1,+ availableReplicas: 1,+ unavailableReplicas: 0,+ },+ })+ appsApi.readNamespacedDeployment.mockResolvedValue(notConverged(2))++ await reconciler.reconcile(makeServer())+ // 12 polls into the first window…+ await vi.advanceTimersByTimeAsync(12 * 5000)+ // …a SECOND rotation lands: new generation, still not converging.+ appsApi.readNamespacedDeployment.mockResolvedValue(notConverged(3))+ await vi.advanceTimersByTimeAsync(13 * 5000)++ // 125s elapsed — past the original 24 × 5s budget — but the new rollout+ // got a fresh window when its generation appeared at t=65s, so a terminal+ // verdict now would blame the new rollout with the old rollout's clock.+ expect(deploymentReadyWrites(customApi).some(w => w.reason === 'RolloutIncomplete')).toBe(false)++ // The fresh window exhausts its own 24 polls after the generation change.+ await vi.advanceTimersByTimeAsync(11 * 5000)+ const last = deploymentReadyWrites(customApi).at(-1)+ expect(last?.reason).toBe('RolloutIncomplete')+ expect(last?.message).toContain('generation 3/3')+ })++ it('a NEW generation arriving while the LAST tick is in flight still gets its own window (in-flight tick race)', async () => {+ // The race the timer-only re-entrancy guard cannot see: pollReadiness()+ // is called by a reconcile WHILE the budget-exhausting tick is suspended+ // inside its Deployment read. The tick's data predates the reconcile's+ // Deployment write (the new generation), and after the tick goes terminal+ // nothing else re-arms the poll — McpServer has no periodic resync and no+ // Deployment watch — so the CRD would keep the OLD generation's+ // RolloutIncomplete forever even though the NEW rollout converges.+ const notConverged = (generation: number) => ({+ metadata: { generation, labels: {} },+ spec: { replicas: 1 },+ status: {+ observedGeneration: generation,+ replicas: 2,+ updatedReplicas: 1,+ readyReplicas: 1,+ availableReplicas: 1,+ unavailableReplicas: 0,+ },+ })+ const converged = (generation: number) => ({+ metadata: { generation, labels: {} },+ spec: { replicas: 1 },+ status: {+ observedGeneration: generation,+ replicas: 1,+ updatedReplicas: 1,+ readyReplicas: 1,+ unavailableReplicas: 0,+ },+ })++ // Generation 2 crash-loops and never converges.+ appsApi.readNamespacedDeployment.mockResolvedValue(notConverged(2))+ await reconciler.reconcile(makeServer())++ // Burn 23 of the 24 attempts of the window.+ await vi.advanceTimersByTimeAsync(23 * 5000)++ // Tick 24 — the budget-exhausting one — starts its Deployment read, and+ // we hold that read open: the tick is now suspended mid-await, with the+ // OLD generation's data about to come back.+ let releaseInFlightRead: ((deployment: unknown) => void) | undefined+ appsApi.readNamespacedDeployment.mockImplementationOnce(+ () =>+ new Promise(resolve => {+ releaseInFlightRead = resolve+ })+ )+ await vi.advanceTimersByTimeAsync(5000)+ if (releaseInFlightRead === undefined) {+ throw new Error(+ 'race precondition failed: tick 24 never started its Deployment read while suspended'+ )+ }++ // While that tick is in flight, the operator fixes the credential: the+ // reconcile writes the Deployment at generation 3 and, at the end of+ // performReconcile, calls pollReadiness() — landing exactly inside the+ // window the re-entrancy guard used to no-op.+ coreApi.readNamespacedSecret.mockResolvedValue({ data: { 'api-key': stored('fixed-key') } })+ appsApi.readNamespacedDeployment.mockResolvedValue(notConverged(3))+ await reconciler.reconcile(makeServer())++ // The suspended tick now completes with the data it read BEFORE the new+ // rollout existed: stale generation-2 numbers, budget exhausted.+ releaseInFlightRead(notConverged(2))+ await vi.advanceTimersByTimeAsync(0)++ // Generation 3 converges shortly after. Only a poll window that survived+ // the race can observe this.+ appsApi.readNamespacedDeployment.mockResolvedValue(converged(3))+ await vi.advanceTimersByTimeAsync(2 * 5000)++ // The final CRD verdict must belong to generation 3 — DeploymentReady=True.+ // A RolloutIncomplete write here would carry generation 2's stale numbers+ // and, with the window dead, would stick indefinitely.+ const writes = deploymentReadyWrites(customApi)+ expect(writes.at(-1)?.status).toBe('True')+ expect(writes.some(w => w.reason === 'RolloutIncomplete')).toBe(false)+ })+})diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex 5bf92cfa6..5730e5553 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -54,6 +54,7 @@ import {} from './types'import {applyNetworkPolicy,+ canonicalStringify,getErrorCode,preserveDeploymentAnnotations,preserveServiceAssignedFields,@@ -4273,11 +4274,6 @@ export class HostReconciler {}}-function canonicalStringify(obj: Record<string, unknown>): string {- const sorted = Object.keys(obj).sort()- return JSON.stringify(sorted.map(k => [k, obj[k]]))-}-/*** Kubernetes persists server metadata and defaulted Deployment/PodSpec fields* that HCC does not author. Remove only those known fields before comparingdiff --git a/host-context-controller/src/reconciler.test.ts b/host-context-controller/src/reconciler.test.tsindex 394e4b2af..92e74d6e8 100644--- a/host-context-controller/src/reconciler.test.ts+++ b/host-context-controller/src/reconciler.test.ts@@ -230,10 +230,12 @@ describe('PR-B B1 — validateSecret result shape', () => {})})- it('returns ok:true when the server has no envSecret', async () => {+ it('returns ok:true with an empty revision when the server has no envSecret', async () => {const server = makeServer({ name: 'no-secret' })const result = await reconciler.validateSecret(server)- expect(result).toEqual({ ok: true })+ // No credentials to hash, so no credentials-revision annotation is written+ // on the pod template (issue #223).+ expect(result).toEqual({ ok: true, revision: '' })})it('returns SecretNotFound when the Secret is missing (404)', async () => {@@ -304,8 +306,9 @@ describe('PR-B B1 — validateSecret result shape', () => {}})- it('returns ok:true when all required keys are present', async () => {- // Base64 value doesn't matter — the validator only checks key presence.+ it('returns ok:true and the content revision when all required keys are present', async () => {+ // The base64 value does not matter for key-presence validation, but it IS+ // what the revision hashes (issue #223).coreApi.readNamespacedSecret.mockResolvedValueOnce({ data: { password: 'cGFzcw==' } })const server = makeServer({@@ -314,7 +317,7 @@ describe('PR-B B1 — validateSecret result shape', () => {})const result = await reconciler.validateSecret(server)- expect(result).toEqual({ ok: true })+ expect(result).toEqual({ ok: true, revision: expect.stringMatching(/^[0-9a-f]{64}$/) })})it('fails closed and removes managed runtime resources when secret validation fails', async () => {@@ -605,6 +608,49 @@ describe('PR-B B1 — writeStatusCondition', () => {)expect(sample?.value).toBe(0)})++ it('fences the patch with resourceVersion and retries on a 422 conflict (M2)', async () => {+ const existing = {+ type: 'DeploymentReady',+ status: 'False',+ reason: 'WaitingForReplicas',+ message: 'waiting',+ lastTransitionTime: '2020-01-01T00:00:00.000Z',+ }+ // First read at rv=v1; after the conflict, the re-read observes rv=v2 (a+ // concurrent writer bumped it).+ customApi.getNamespacedCustomObjectStatus+ .mockResolvedValueOnce({+ metadata: { resourceVersion: 'v1' },+ status: { conditions: [existing] },+ })+ .mockResolvedValueOnce({+ metadata: { resourceVersion: 'v2' },+ status: { conditions: [existing] },+ })+ // First patch loses the race (the resourceVersion `test` op fails → 422);+ // the retry succeeds.+ customApi.patchNamespacedCustomObjectStatus+ .mockRejectedValueOnce(Object.assign(new Error('the test operation failed'), { code: 422 }))+ .mockResolvedValueOnce({})++ const server = makeServer({ name: 'pg' })+ await reconciler.writeStatusCondition(server, {+ type: 'DeploymentReady',+ status: 'True',+ reason: 'ReplicasAvailable',+ message: 'ready',+ })++ // Re-read and re-patched instead of losing the write.+ expect(customApi.getNamespacedCustomObjectStatus).toHaveBeenCalledTimes(2)+ expect(customApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledTimes(2)+ // Both patches are fenced; the successful retry uses the RE-READ version.+ const firstBody = customApi.patchNamespacedCustomObjectStatus.mock.calls[0][0].body+ const secondBody = customApi.patchNamespacedCustomObjectStatus.mock.calls[1][0].body+ expect(firstBody[0]).toEqual({ op: 'test', path: '/metadata/resourceVersion', value: 'v1' })+ expect(secondBody[0]).toEqual({ op: 'test', path: '/metadata/resourceVersion', value: 'v2' })+ })})describe('ownership-safe fail-closed cleanup', () => {diff --git a/host-context-controller/src/reconciler.ts b/host-context-controller/src/reconciler.tsindex b1c1c5d62..56f299e00 100644--- a/host-context-controller/src/reconciler.ts+++ b/host-context-controller/src/reconciler.ts@@ -11,6 +11,7 @@*/import * as k8s from '@kubernetes/client-node'import { IntOrString } from '@kubernetes/client-node/dist/types.js'+import { createHash } from 'crypto'import { classifyPluginImage } from '@clerum/image-policy'import { isWorkflowRecipeDefaultAllowedCapability } from '@clerum/workflow-recipe-capability-policy'import { config } from './config'@@ -18,6 +19,7 @@ import { MANAGED_BY_LABEL, MANAGED_BY_VALUE, MCPSERVER_LABEL } from './constantsimport { mcpserverMissingSecret } from './metrics'import { McpServerCRD, McpServerStatus } from './types'import {+ canonicalStringify,getErrorCode,preserveDeploymentAnnotations,preserveObjectAnnotations,@@ -30,7 +32,20 @@ import {* classifies the failure so the caller can surface it via status conditions.*/export type SecretValidationResult =- | { ok: true }+ | {+ ok: true+ /**+ * sha256 of the validated Secret's content (issue #223). Empty when the+ * McpServer has no envSecret. Travels into the pod template as the+ * credentials-revision annotation, which is what makes a credential+ * rotation roll the pod: env vars come from `secretKeyRef` and Kubernetes+ * only injects those when the container starts.+ *+ * It is derived from the very Secret this validation read, so the digest+ * can never describe a different revision than the one that was checked.+ */+ revision: string+ }| {ok: falsereason: 'SecretNotFound' | 'SecretMissingKey' | 'SecretAccessDenied' | 'ReadError'@@ -60,6 +75,12 @@ type McpServerReconcilerDeps = {const PRE_DEPLOY_ANNOTATION = 'clerum.io/pre-deploy'const NETWORK_READY_ANNOTATION = 'clerum.io/network-ready'+// Issue #223: sha256 of the envSecret content, carried on the POD TEMPLATE (not+// the Deployment object) so that changing it changes the pod template hash and+// Kubernetes performs a rolling restart on its own. Same mechanism the per-Host+// channel-readers use in hostReconciler.ts.+const CREDENTIALS_REVISION_ANNOTATION = 'clerum.io/credentials-revision'+// Codex P0 fix (PR #101): sanitization constants for remote.authHeaders.// Only standard HTTP header token chars — letters, digits, and '-'. Rejecting// anything else prevents smuggling headers like `X: foo\r\nAuthorization`.@@ -74,6 +95,59 @@ function throwCleanupFailures(failures: unknown[], message: string): void {}}+/**+ * State of the readiness poll window for one McpServer (issue #223).+ *+ * A "window" is one bounded observation of a single Deployment rollout:+ * maxAttempts ticks of intervalMs each. The window survives repeated+ * reconciles — see `readinessPolls` below for why that is load-bearing.+ */+interface ReadinessPollState {+ /**+ * Timer for the next tick; undefined while a tick is executing its awaits+ * (the handle is consumed the moment the callback fires) and once the+ * window reached a terminal verdict.+ */+ timer: ReturnType<typeof setTimeout> | undefined+ /**+ * True while a tick is executing. `timer` alone cannot distinguish "tick+ * running RIGHT NOW" from "window ended", and the difference is+ * load-bearing for pollReadiness() re-entrancy (see `recheckRequested`).+ */+ ticking: boolean+ /**+ * Set by pollReadiness() when it is called while a tick is in flight. The+ * caller (a reconcile) may have JUST rewritten the Deployment — e.g. a+ * corrected credential rotation bumping the generation — and the in-flight+ * tick's read, started earlier, cannot have seen that write. While this+ * flag is set the tick must NOT commit a terminal verdict (ready or+ * exhausted): it defers one interval so the next read, which starts after+ * that Deployment write, observes the new generation and resets the+ * window. Without this, the exhausting tick could publish RolloutIncomplete+ * with the SUPERSEDED generation's numbers and — since McpServer has no+ * periodic resync or Deployment watch — nothing would ever re-arm the poll+ * for the new rollout (issue #223).+ */+ recheckRequested: boolean+ /**+ * Deployment generation the current window is watching; null until the+ * first tick reads it. A change means a NEW rollout (e.g. another+ * credential rotation), which resets the window so the new rollout gets+ * its own full budget.+ */+ generation: number | null+ /** Ticks consumed by the current window. */+ attempts: number+ /** True once the terminal RolloutIncomplete verdict was written for `generation`. */+ exhausted: boolean+ /**+ * Rollout numbers from the exhausting tick. reconcile() re-writes them so+ * the terminal condition stays sticky instead of being downgraded to+ * WaitingForReplicas by the very reconcile the terminal write triggers.+ */+ detail: string+}+export class McpServerReconciler {private readonly appsApi: k8s.AppsV1Apiprivate readonly coreApi: k8s.CoreV1Api@@ -86,8 +160,20 @@ export class McpServerReconciler {/** G7: Tracks the initial `managed` value per McpServer to enforce immutability. */private readonly managedSnapshot: Map<string, boolean> = new Map()- /** Active readiness poll timers — keyed by server name so they can be cancelled. */- private readonly readinessTimers: Map<string, ReturnType<typeof setTimeout>> = new Map()+ /**+ * Readiness poll state per server name (issue #223, E2 status-update-loop).+ *+ * Entries outlive individual reconciles ON PURPOSE. Every status write this+ * reconciler makes fires a MODIFIED watch event on the McpServer, which+ * fires another reconcile, which calls pollReadiness() again. When that+ * call cancelled and re-armed the poll (the pre-fix behavior), the attempt+ * budget restarted on every status write, so a rollout that never converges+ * NEVER exhausted its budget and the terminal RolloutIncomplete verdict was+ * never written to the CRD. This map lets pollReadiness() detect a live+ * window and leave it alone, and lets reconcile() keep an exhausted verdict+ * sticky for the same Deployment generation.+ */+ private readonly readinessPolls: Map<string, ReadinessPollState> = new Map()/*** Tail promise of the in-flight reconcile chain per server name. Serializes@@ -131,71 +217,214 @@ export class McpServerReconciler {private clearStatus(name: string): void {this.statusMap.delete(name)this.managedSnapshot.delete(name)- const timer = this.readinessTimers.get(name)- if (timer) {- clearTimeout(timer)- this.readinessTimers.delete(name)+ const poll = this.readinessPolls.get(name)+ if (poll) {+ if (poll.timer !== undefined) clearTimeout(poll.timer)+ this.readinessPolls.delete(name)}}/**- * Check deployment readiness by inspecting replicas.+ * Read a Deployment's rollout state, generation-aware.+ *+ * `readyReplicas > 0` is NOT enough (issue #223): during a rolling update the+ * OLD pod is still Ready, so a new pod that never starts would be reported as+ * healthy. A rollout has actually converged only when the controller has+ * observed the current generation AND every replica is updated, ready, and+ * available.+ *+ * `totalReplicas === updatedReplicas` is the part that catches a FAILED+ * rollout of a credential rotation (issue #223, E2): with replicas=1 and the+ * default RollingUpdate (maxSurge=1, maxUnavailable=0), a new pod that+ * crash-loops on a bad credential never becomes Ready, so Kubernetes keeps+ * the OLD pod. That old pod holds readyReplicas=1 and availableReplicas=1, so+ * unavailableReplicas stays 0 and updatedReplicas reaches 1 — every other+ * signal looks converged. Only `status.replicas` (total managed pods) reveals+ * the leftover: it stays at 2 while the new pod crash-loops, and drops to 1+ * only once the rollout truly completes. Without this check the poll would+ * report a failed rotation as healthy and never write RolloutIncomplete.+ *+ * `detail` carries the numbers into status conditions so a stuck rollout says+ * what is stuck instead of just "not ready".+ *+ * `generation` is the Deployment's `metadata.generation`, exposed so the+ * readiness poll can tell "same rollout, keep counting" apart from "NEW+ * rollout, fresh window" (issue #223, E2). It plays no part in the+ * readiness verdict above. null when the Deployment could not be read.*/- private async checkDeploymentReady(name: string, namespace: string): Promise<boolean> {+ private async readDeploymentRollout(+ name: string,+ namespace: string+ ): Promise<{ ready: boolean; detail: string; generation: number | null }> {try {const deployment = await this.appsApi.readNamespacedDeployment({ name, namespace })- const ready = (deployment.status?.readyReplicas ?? 0) > 0- return ready- } catch {- return false+ const desired = deployment.spec?.replicas ?? 1+ const generation = deployment.metadata?.generation ?? 0+ const observedGeneration = deployment.status?.observedGeneration ?? 0+ const updatedReplicas = deployment.status?.updatedReplicas ?? 0+ const readyReplicas = deployment.status?.readyReplicas ?? 0+ const totalReplicas = deployment.status?.replicas ?? 0+ const unavailableReplicas = deployment.status?.unavailableReplicas ?? 0++ const ready =+ observedGeneration >= generation &&+ updatedReplicas === desired &&+ readyReplicas === desired &&+ totalReplicas === updatedReplicas &&+ unavailableReplicas === 0++ return {+ ready,+ generation,+ detail:+ `generation ${observedGeneration}/${generation}, ` ++ `updated ${updatedReplicas}/${desired}, ready ${readyReplicas}/${desired}, ` ++ `total ${totalReplicas}, unavailable ${unavailableReplicas}`,+ }+ } catch (error: unknown) {+ const message = error instanceof Error ? error.message : String(error)+ return { ready: false, generation: null, detail: `Deployment read failed: ${message}` }}}/*** Poll deployment readiness until ready or maxAttempts reached.- * Cancels any existing poll for the same server name.+ *+ * Re-entrancy is the whole point (issue #223, E2 status-update-loop):+ * reconcile() runs after every MODIFIED watch event — including the events+ * caused by our OWN status writes — and calls this on every pass where the+ * Deployment is not ready yet. A live window is therefore NEVER cancelled+ * or re-armed here; it keeps counting toward its budget so a rollout that+ * never converges reaches the terminal RolloutIncomplete verdict after+ * maxAttempts × intervalMs. A NEW rollout (bumped Deployment generation,+ * e.g. another credential rotation) is detected inside the poll tick+ * itself, which resets the window so the new rollout gets its own budget.+ *+ * A call that lands while a tick is EXECUTING (mid-await) is not silently+ * dropped either: it flags `recheckRequested` so the tick defers any+ * terminal verdict until a read taken AFTER the caller's Deployment write+ * confirms the generation — otherwise the exhausting tick could seal the+ * window with a superseded generation's numbers and the new rollout would+ * never be observed (see ReadinessPollState.recheckRequested).*/- private pollReadiness(- name: string,- namespace: string,- intervalMs = 5000,- maxAttempts = 12- ): void {- // Cancel any existing poll for this server- const existing = this.readinessTimers.get(name)- if (existing) {- clearTimeout(existing)- this.readinessTimers.delete(name)+ private pollReadiness(server: McpServerCRD, intervalMs = 5000, maxAttempts = 24): void {+ const { name, namespace } = server++ const previous = this.readinessPolls.get(name)+ if (previous !== undefined && (previous.timer !== undefined || previous.ticking)) {+ // A window is already running for this server — leave it alone+ // (re-arming would reset the attempt budget: the E2 status-update-loop).+ // But if its tick is executing RIGHT NOW, the tick's Deployment read may+ // predate the Deployment write that triggered THIS call (a new+ // generation), so a silent no-op could let the tick end the window on+ // stale data. Record that a re-check is owed; the tick honors it before+ // committing any terminal verdict.+ if (previous.ticking) {+ previous.recheckRequested = true+ }+ return}- let attempts = 0-- const poll = async () => {- attempts++- const ready = await this.checkDeploymentReady(name, namespace)+ // Fresh window. Carry over the generation and terminal verdict of a+ // previous exhausted window: if the Deployment has NOT changed since,+ // the new window must not mistake it for a new rollout, and reconcile()+ // keeps reporting the sticky RolloutIncomplete meanwhile.+ const state: ReadinessPollState = {+ timer: undefined,+ ticking: false,+ recheckRequested: false,+ generation: previous?.generation ?? null,+ attempts: 0,+ exhausted: previous?.exhausted ?? false,+ detail: previous?.detail ?? '',+ }+ this.readinessPolls.set(name, state)++ const poll = async (): Promise<void> => {+ // The timer handle was consumed the moment this callback fired; reflect+ // that, and mark the tick as in flight so a concurrent pollReadiness()+ // can tell "tick running" apart from "window ended" during our awaits.+ state.timer = undefined+ state.ticking = true+ const rollout = await this.readDeploymentRollout(name, namespace)++ // The McpServer may have been deleted (clearStatus) while we were+ // reading. A cancelled window must not keep ticking or write status+ // for a CRD that is gone.+ if (this.readinessPolls.get(name) !== state) return++ // Generation change ⇒ a NEW rollout: it deserves its own full budget,+ // and any terminal verdict for the old generation no longer applies.+ // A failed read (generation null) never resets the window — otherwise+ // a flapping API server would grant infinite budget.+ if (rollout.generation !== null && rollout.generation !== state.generation) {+ state.generation = rollout.generation+ state.attempts = 0+ state.exhausted = false+ state.detail = ''+ }+ state.attempts++++ // A pollReadiness() call landed while this tick was mid-await: the+ // Deployment may have been rewritten AFTER our read (that reconcile+ // writes the Deployment BEFORE calling pollReadiness()), so a terminal+ // verdict from this tick's data could blame a superseded generation —+ // and nothing else would ever re-arm the poll for the new one. Defer+ // the verdict one interval: the next read starts after that Deployment+ // write, so it MUST observe the new generation and reset the window+ // above. A same-generation echo merely delays the verdict by one tick;+ // the budget is NOT reset, so the E2 status-update-loop stays fixed.+ if (state.recheckRequested) {+ state.recheckRequested = false+ if (rollout.ready || state.attempts >= maxAttempts) {+ state.ticking = false+ state.timer = setTimeout(poll, intervalMs)+ return+ }+ }- if (ready) {+ if (rollout.ready) {+ state.ticking = falsethis.setStatus(name, { deployed: true, ready: true, message: 'Running' })- this.readinessTimers.delete(name)- console.log(`[Reconciler] McpServer "${name}" is now ready (after ${attempts} poll(s))`)+ this.readinessPolls.delete(name)+ console.log(+ `[Reconciler] McpServer "${name}" is now ready (after ${state.attempts} poll(s))`+ )+ // The poll MUST write the CRD, not just in-memory status (issue #223).+ // With generation-aware readiness the check right after a replace is+ // always false, so this is the ONLY place a converged rollout is ever+ // recorded — without it every successful credential rotation would sit+ // at DeploymentReady=False forever and the UI would report a timeout.+ await this.updateStatusConditions(server, true)return}- if (attempts >= maxAttempts) {- this.readinessTimers.delete(name)+ if (state.attempts >= maxAttempts) {+ // Terminal verdict for THIS generation. The entry stays in the map+ // (timer undefined since tick start, ticking cleared here — BEFORE+ // the status write below, so a reconcile arriving during that await+ // opens a fresh observation window instead of flagging a re-check+ // this dying tick would never honor) so reconcile() keeps the verdict+ // sticky and a later pollReadiness() call may re-observe.+ state.ticking = false+ state.exhausted = true+ state.detail = rollout.detailconsole.warn(- `[Reconciler] McpServer "${name}" not ready after ${maxAttempts} polls — giving up`+ `[Reconciler] McpServer "${name}" not ready after ${maxAttempts} polls — giving up (${rollout.detail})`)+ // Give up loudly, on the CRD: a stuck rollout must be visible to the+ // operator with the numbers that prove it, never left as a stale+ // condition or a silent Unknown.+ await this.updateStatusConditions(server, false, rollout.detail)return}// Schedule next poll- const timer = setTimeout(poll, intervalMs)- this.readinessTimers.set(name, timer)+ state.ticking = false+ state.timer = setTimeout(poll, intervalMs)}- const timer = setTimeout(poll, intervalMs)- this.readinessTimers.set(name, timer)+ state.timer = setTimeout(poll, intervalMs)}// ─── Secret Validation ──────────────────────────────────────────────@@ -205,7 +434,8 @@ export class McpServerReconciler {* Returns a discriminated result describing success or the exact failure mode.*/async validateSecret(server: McpServerCRD): Promise<SecretValidationResult> {- if (!server.spec.envSecret) return { ok: true }+ // No envSecret: nothing to hash, and no credentials annotation is written.+ if (!server.spec.envSecret) return { ok: true, revision: '' }const secretName = server.spec.envSecret.name@@ -216,6 +446,9 @@ export class McpServerReconciler {})const data = secret.data || {}+ const revision = createHash('sha256')+ .update(canonicalStringify(data as Record<string, unknown>))+ .digest('hex')for (const keyMapping of server.spec.envSecret.keys) {if (!(keyMapping.secretKey in data)) {@@ -228,7 +461,7 @@ export class McpServerReconciler {}console.log(`[Reconciler] Secret "${secretName}" validated for McpServer ${server.name}`)- return { ok: true }+ return { ok: true, revision }} catch (error: unknown) {const code = getErrorCode(error)if (code === 404) {@@ -576,7 +809,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv}}- private buildDeployment(server: McpServerCRD): k8s.V1Deployment {+ private buildDeployment(server: McpServerCRD, credentialsRevision = ''): k8s.V1Deployment {// ── Platform hardening: sanitize CRD before building PodSpec ──this.sanitizeCrdSpec(server)@@ -734,7 +967,17 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvmatchLabels: { app: server.name },},template: {- metadata: { labels },+ metadata: {+ labels,+ // Issue #223: rotating a credential changes this digest, which+ // changes the pod template, which is what makes Kubernetes roll the+ // pod. Omitted when there is no envSecret — an annotation with an+ // empty value would be one more field to drift on for connectors+ // that have no credentials at all.+ ...(credentialsRevision && {+ annotations: { [CREDENTIALS_REVISION_ANNOTATION]: credentialsRevision },+ }),+ },spec: {automountServiceAccountToken: false,enableServiceLinks: false,@@ -963,8 +1206,8 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv/*** Ensure a Deployment exists and is up to date.*/- private async ensureDeployment(server: McpServerCRD): Promise<void> {- const deployment = this.buildDeployment(server)+ private async ensureDeployment(server: McpServerCRD, credentialsRevision = ''): Promise<void> {+ const deployment = this.buildDeployment(server, credentialsRevision)try {await this.appsApi.createNamespacedDeployment({@@ -1341,7 +1584,13 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv*/private async updateStatusConditions(server: McpServerCRD,- deploymentReady: boolean+ deploymentReady: boolean,+ /**+ * Rollout numbers from readDeploymentRollout, appended to the failure+ * message so a stuck rollout reports WHAT is stuck (issue #223). Callers+ * that only know the verdict omit it.+ */+ rolloutDetail?: string): Promise<void> {try {await this.writeStatusCondition(server, {@@ -1353,10 +1602,16 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvawait this.writeStatusCondition(server, {type: 'DeploymentReady',status: deploymentReady ? 'True' : 'False',- reason: deploymentReady ? 'ReplicasAvailable' : 'WaitingForReplicas',- message: deploymentReady- ? 'Deployment has ready replicas'- : 'Waiting for pods to become ready',+ reason: deploymentReady+ ? 'ReplicasAvailable'+ : rolloutDetail+ ? 'RolloutIncomplete'+ : 'WaitingForReplicas',+ message: rolloutDetail+ ? `Rollout did not converge — ${rolloutDetail}`+ : deploymentReady+ ? 'Deployment has ready replicas'+ : 'Waiting for pods to become ready',})console.log(`[Reconciler] Updated status conditions on "${server.name}" (DeploymentReady=${deploymentReady})`@@ -1388,103 +1643,140 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvserver: McpServerCRD,condition: Omit<McpServerCondition, 'lastTransitionTime'>): Promise<void> {- const now = new Date().toISOString()-- // Fetch current status to preserve existing conditions.- let existingConditions: McpServerCondition[] = []- let hasStatusObject = false- try {- const current = (await this.customApi.getNamespacedCustomObjectStatus({- group: 'clerum.io',- version: 'v1alpha1',- namespace: server.namespace,- plural: 'mcpservers',- name: server.name,- })) as { status?: { conditions?: McpServerCondition[] } }- hasStatusObject = typeof current.status === 'object' && current.status !== null- existingConditions = current.status?.conditions ?? []- } catch (error) {- if (getErrorCode(error) === 404) {+ // Optimistic-concurrency loop (M2). The patch REPLACES the whole+ // /status/conditions array with a value built from a snapshot read just+ // before. Without a version guard, a concurrent writer — the readiness poll+ // and a reconcile can both write status for the same server, and the poll+ // timer is NOT serialized through `inFlight` — would be silently clobbered+ // by whichever patch lands second, dropping the other's condition. A `test`+ // op on metadata.resourceVersion makes the API server reject the patch (422)+ // if anything changed since our read; we then re-read and retry, so no+ // writer's condition is lost.+ const MAX_ATTEMPTS = 4+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {+ const now = new Date().toISOString()++ // Fetch current status (and its resourceVersion) to preserve existing+ // conditions and to fence the write below.+ let existingConditions: McpServerCondition[] = []+ let hasStatusObject = false+ let resourceVersion: string | undefined+ try {+ const current = (await this.customApi.getNamespacedCustomObjectStatus({+ group: 'clerum.io',+ version: 'v1alpha1',+ namespace: server.namespace,+ plural: 'mcpservers',+ name: server.name,+ })) as {+ metadata?: { resourceVersion?: string }+ status?: { conditions?: McpServerCondition[] }+ }+ resourceVersion = current.metadata?.resourceVersion+ hasStatusObject = typeof current.status === 'object' && current.status !== null+ existingConditions = current.status?.conditions ?? []+ } catch (error) {+ if (getErrorCode(error) === 404) {+ console.warn(+ `[Reconciler] McpServer "${server.name}" deleted mid-reconcile — skipping status update`+ )+ return+ }console.warn(- `[Reconciler] McpServer "${server.name}" deleted mid-reconcile — skipping status update`+ `[Reconciler] Failed to read status for "${server.name}" — skipping status update for type "${condition.type}" to avoid clobbering other status fields:`,+ error)return}- console.warn(- `[Reconciler] Failed to read status for "${server.name}" — skipping status update for type "${condition.type}" to avoid clobbering other status fields:`,- error- )- return- }- const prior = existingConditions.find(c => c.type === condition.type)- const unchanged =- prior !== undefined &&- prior.status === condition.status &&- prior.reason === condition.reason &&- prior.message === condition.message-- // Update the missing-secret gauge for SecretResolved conditions.- // Do this BEFORE the no-op short-circuit so the gauge stays current- // across reconciles even when we skip the API patch.- if (condition.type === 'SecretResolved' && server.spec.envSecret) {- const labels = {- namespace: server.namespace,- name: server.name,- secret_name: server.spec.envSecret.name,+ const prior = existingConditions.find(c => c.type === condition.type)+ const unchanged =+ prior !== undefined &&+ prior.status === condition.status &&+ prior.reason === condition.reason &&+ prior.message === condition.message++ // Update the missing-secret gauge for SecretResolved conditions. Do this+ // BEFORE the no-op short-circuit so the gauge stays current across+ // reconciles even when we skip the API patch. Idempotent, so a retry+ // re-running it is harmless.+ if (condition.type === 'SecretResolved' && server.spec.envSecret) {+ const labels = {+ namespace: server.namespace,+ name: server.name,+ secret_name: server.spec.envSecret.name,+ }+ mcpserverMissingSecret.set(labels, condition.status === 'False' ? 1 : 0)}- mcpserverMissingSecret.set(labels, condition.status === 'False' ? 1 : 0)- }- // Skip the patch when the condition is identical to what's already on- // the CRD. Without this, every reconcile bumps the McpServer's- // resourceVersion, fires another watch event, triggers another- // reconcile — a tight self-loop that also amplifies NetworkPolicy- // optimistic-lock contention downstream.- if (unchanged) {- return- }+ // Skip the patch when the condition is identical to what's already on+ // the CRD. Without this, every reconcile bumps the McpServer's+ // resourceVersion, fires another watch event, triggers another+ // reconcile — a tight self-loop that also amplifies NetworkPolicy+ // optimistic-lock contention downstream.+ if (unchanged) {+ return+ }- const lastTransitionTime =- prior && prior.status === condition.status ? prior.lastTransitionTime : now+ const lastTransitionTime =+ prior && prior.status === condition.status ? prior.lastTransitionTime : now- const merged: McpServerCondition = {- type: condition.type,- status: condition.status,- reason: condition.reason,- message: condition.message,- lastTransitionTime,- }+ const merged: McpServerCondition = {+ type: condition.type,+ status: condition.status,+ reason: condition.reason,+ message: condition.message,+ lastTransitionTime,+ }- const nextConditions = [...existingConditions.filter(c => c.type !== condition.type), merged]+ const nextConditions = [...existingConditions.filter(c => c.type !== condition.type), merged]- const statusPatch = hasStatusObject- ? [{ op: 'add', path: '/status/conditions', value: nextConditions }]- : [{ op: 'add', path: '/status', value: { conditions: nextConditions } }]+ // The `test` op fences the write to the exact revision we read. If a+ // concurrent writer bumped resourceVersion in between, the API server+ // fails the patch (422) and we retry with a fresh read.+ const statusPatch = [+ ...(resourceVersion+ ? [{ op: 'test', path: '/metadata/resourceVersion', value: resourceVersion }]+ : []),+ hasStatusObject+ ? { op: 'add', path: '/status/conditions', value: nextConditions }+ : { op: 'add', path: '/status', value: { conditions: nextConditions } },+ ]- try {- // The generated client prefers JSON Patch for this endpoint. Send an- // actual patch document so status writes keep working across client- // upgrades instead of relying on merge-patch object bodies.- await this.customApi.patchNamespacedCustomObjectStatus({- group: 'clerum.io',- version: 'v1alpha1',- namespace: server.namespace,- plural: 'mcpservers',- name: server.name,- body: statusPatch,- })- } catch (error) {- if (getErrorCode(error) === 404) {+ try {+ // The generated client prefers JSON Patch for this endpoint. Send an+ // actual patch document so status writes keep working across client+ // upgrades instead of relying on merge-patch object bodies.+ await this.customApi.patchNamespacedCustomObjectStatus({+ group: 'clerum.io',+ version: 'v1alpha1',+ namespace: server.namespace,+ plural: 'mcpservers',+ name: server.name,+ body: statusPatch,+ })+ return+ } catch (error) {+ if (getErrorCode(error) === 404) {+ console.warn(+ `[Reconciler] McpServer "${server.name}" deleted mid-reconcile — status patch skipped`+ )+ return+ }+ // 409 (Conflict) or 422 (the resourceVersion `test` op failed) mean a+ // concurrent writer won the race. Re-read and retry rather than lose+ // our condition. Any other error, or the last attempt, falls through to+ // the best-effort log-and-swallow below.+ const code = getErrorCode(error)+ if ((code === 409 || code === 422) && attempt < MAX_ATTEMPTS) {+ continue+ }console.warn(- `[Reconciler] McpServer "${server.name}" deleted mid-reconcile — status patch skipped`+ `[Reconciler] Failed to write status condition ${condition.type}=${condition.status} on "${server.name}" (attempt ${attempt}/${MAX_ATTEMPTS}):`,+ error)return}- console.warn(- `[Reconciler] Failed to write status condition ${condition.type}=${condition.status} on "${server.name}":`,- error- )}}@@ -1623,7 +1915,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv}}await this.ensureService(server)- await this.ensureDeployment(server)+ await this.ensureDeployment(server, secretResult.revision)} catch (err) {this.setStatus(server.name, {deployed: false,@@ -1653,15 +1945,32 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv}// Check readiness after reconciliation- const ready = await this.checkDeploymentReady(server.name, server.namespace)+ const rollout = await this.readDeploymentRollout(server.name, server.namespace)+ const ready = rollout.readythis.setStatus(server.name, {deployed: true,ready,message: ready ? 'Running' : 'Deployment created, waiting for pods to become ready',})- // G11: Update status conditions on McpServer CRD- await this.updateStatusConditions(server, ready)+ // G11: Update status conditions on McpServer CRD. If the readiness poll+ // already exhausted its budget for THIS Deployment generation, keep the+ // terminal RolloutIncomplete verdict sticky: the terminal status write+ // itself fires a MODIFIED watch event and thus this very code path, and+ // writing a bare "waiting" condition here would downgrade the verdict+ // milliseconds after it was published — the operator (and the E2+ // scenario) would never observe the rollout failure. A NEW rollout+ // (different generation) drops the stickiness and reports fresh.+ const pollState = this.readinessPolls.get(server.name)+ const exhaustedDetail =+ !ready &&+ pollState !== undefined &&+ pollState.exhausted &&+ rollout.generation !== null &&+ pollState.generation === rollout.generation+ ? pollState.detail+ : undefined+ await this.updateStatusConditions(server, ready, exhaustedDetail)// PR-B B1: record SecretResolved=True + Ready=True after a successful// reconcile. This is additive to updateStatusConditions (NetworkReady /@@ -1684,9 +1993,12 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv: 'Deployment created, waiting for pods to become ready',})- // If not ready yet, poll until it becomes ready+ // If not ready yet, poll until it becomes ready. With generation-aware+ // readiness this is the normal path right after any Deployment write —+ // including a credential rotation — so the poll owns the terminal verdict+ // on the CRD.if (!ready) {- this.pollReadiness(server.name, server.namespace)+ this.pollReadiness(server)}}diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.tsindex d405c97ae..22d63b8b2 100644--- a/host-context-controller/src/utils.ts+++ b/host-context-controller/src/utils.ts@@ -190,3 +190,18 @@ export async function applyNetworkPolicy(replace: body => api.replaceNamespacedNetworkPolicy({ name, namespace, body }),})}++/**+ * Stable JSON for hashing: object keys are emitted in sorted order, so the+ * digest of a Secret's data depends on its content and not on the order the+ * API server happened to return the keys in.+ *+ * Shared by the Host channel-reader credentials revision and the McpServer+ * connector credentials revision (issue #223): both hash Secret content into a+ * pod-template annotation, and a divergence between the two canonical forms+ * would be invisible until a rollout silently stopped happening.+ */+export function canonicalStringify(obj: Record<string, unknown>): string {+ const sorted = Object.keys(obj).sort()+ return JSON.stringify(sorted.map(k => [k, obj[k]]))+}diff --git a/scripts/e2e/e2e-lib.sh b/scripts/e2e/e2e-lib.shindex 2aa2bf06d..bb05580fa 100755--- a/scripts/e2e/e2e-lib.sh+++ b/scripts/e2e/e2e-lib.sh@@ -843,6 +843,17 @@ print_results() {echo ""echo -e "${BOLD}Total: ${e2e_total} | ${GREEN}Pass: ${e2e_pass}${NC} | ${RED}Fail: ${e2e_fail}${NC}"echo ""+ # A run that executed ZERO tests is a failure, not a pass. "Nothing failed"+ # and "everything passed" are different claims, and only the second one earns+ # a green gate. Without this guard a fixture that dies before the first+ # assertion — a missing namespace, an image that never pulled, a filter that+ # matched nothing — prints "All tests passed!" and exits 0 over an empty+ # result set. Every e2e gate in this repo shares this function, so the+ # fail-open was underwriting all of them at once.+ if [ "${e2e_total}" -eq 0 ]; then+ echo -e "${RED}${BOLD}FAIL: zero tests executed — the harness never reached a real assertion${NC}" >&2+ return 1+ fiif [ "$e2e_fail" -eq 0 ]; thenecho -e "${GREEN}${BOLD}All tests passed!${NC}"return 0diff --git a/scripts/e2e/run-vitest-e2e.sh b/scripts/e2e/run-vitest-e2e.shindex 845aaca11..114776c01 100755--- a/scripts/e2e/run-vitest-e2e.sh+++ b/scripts/e2e/run-vitest-e2e.sh@@ -19,6 +19,17 @@ DEFAULT_VITEST_SUITES=(integration/mcp-proxy-routing.test.tsintegration/network-policies.test.tsintegration/profiles-chain.test.ts+ # Connector credential rotation (issue #223). This list is explicit, not a+ # glob over tests/e2e/ — a suite that is not named here simply never runs,+ # and a gate that never ran a test proves nothing.+ integration/mcp-secret-rotation-failure.test.ts+ integration/mcp-secret-rotation-preservation.test.ts+ integration/mcp-secret-rotation-isolation.test.ts+ integration/mcp-secret-rotation-shared.test.ts+ integration/mcp-secret-rotation-remote.test.ts+ integration/mcp-hcc-upgrade-rollout.test.ts+ integration/mcp-server-readiness-regression.test.ts+ integration/mcp-secrets-access-guard.test.tsmcp-host/approval-endpoints.test.tsmcp-host/artifacts.e2e.test.tsmcp-host/crd.test.tsdiff --git a/tests/e2e/fixtures/mock-mcp-server/package-lock.json b/tests/e2e/fixtures/mock-mcp-server/package-lock.jsonindex 5ef2d136d..28477bf53 100644--- a/tests/e2e/fixtures/mock-mcp-server/package-lock.json+++ b/tests/e2e/fixtures/mock-mcp-server/package-lock.json@@ -1,12 +1,12 @@{"name": "mock-mcp-server",- "version": "0.1.6",+ "version": "0.1.7","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "mock-mcp-server",- "version": "0.1.6",+ "version": "0.1.7","dependencies": {"@modelcontextprotocol/sdk": "^1.0.0","zod": "^3.23.0"diff --git a/tests/e2e/fixtures/mock-mcp-server/package.json b/tests/e2e/fixtures/mock-mcp-server/package.jsonindex 46f424d26..647cd7dd1 100644--- a/tests/e2e/fixtures/mock-mcp-server/package.json+++ b/tests/e2e/fixtures/mock-mcp-server/package.json@@ -1,6 +1,6 @@{"name": "mock-mcp-server",- "version": "0.1.6",+ "version": "0.1.7","private": true,"type": "module","scripts": {diff --git a/tests/e2e/fixtures/mock-mcp-server/src/index.ts b/tests/e2e/fixtures/mock-mcp-server/src/index.tsindex 44ebe7eba..b2319a12f 100644--- a/tests/e2e/fixtures/mock-mcp-server/src/index.ts+++ b/tests/e2e/fixtures/mock-mcp-server/src/index.ts@@ -9,7 +9,18 @@* - fetch_http: fetches an allowlisted public HTTPS URL for egress tests* - hang: sleeps long enough for timeout-bound workflow tests*- * Health check on a separate port.+ * Health check on a separate port. Also serves two additive, opt-in routes+ * used by the issue #223 credential-rotation E2E suites (see+ * tests/e2e/integration/mcpCredentialRotation.helpers.ts):+ * - GET /whoami-credential : echoes E2E_ROTATION_API_KEY as currently+ * injected into THIS pod's env — proves a rotated credential actually+ * reached a running container after rollout.+ * - GET /echo-headers : echoes received request headers as JSON — used+ * as the upstream target for a remote connector's authHeaders, to prove+ * the rotated value reaches the nginx egress proxy's outbound request.+ * Neither route is used by any existing consumer of this image, and the+ * startup gate below only fires for a reserved sentinel value no other+ * suite sets — both are inert unless a test opts in.*/import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'@@ -28,6 +39,25 @@ const FETCH_ALLOWED_HOSTS = new Set()const records = new Map<string, string>()+// ─── Issue #223: opt-in credential-rotation test gate ───────────────────────+// Must match ROTATION_CREDENTIAL_ENV_VAR / ROTATION_INVALID_SENTINEL in+// tests/e2e/integration/mcpCredentialRotation.helpers.ts. When the E2E+// scenario for a FAILED rollout (E2) rotates this env var to the reserved+// sentinel, the process refuses to start — a real crash-loop, not a+// simulated one, so the Deployment's rolling update genuinely never+// converges and host-context-controller's generation-aware readiness check+// has something true to observe. Absent (the default for every other+// consumer of this image), this is a no-op.+const ROTATION_CREDENTIAL_ENV_VAR = 'E2E_ROTATION_API_KEY'+const ROTATION_INVALID_SENTINEL = '__E2E_INVALID_CREDENTIAL__'+if (process.env[ROTATION_CREDENTIAL_ENV_VAR] === ROTATION_INVALID_SENTINEL) {+ console.error(+ `[MockMCP] ${ROTATION_CREDENTIAL_ENV_VAR} is the reserved invalid-credential sentinel — ` ++ 'refusing to start (issue #223 E2 fixture gate).'+ )+ process.exit(1)+}+function sleep(ms: number): Promise<void> {return new Promise(resolve => setTimeout(resolve, ms))}@@ -238,9 +268,23 @@ mcpHttpServer.listen(MCP_PORT, '0.0.0.0', () => {console.log(`[MockMCP] StreamableHTTP server listening on port ${MCP_PORT}`)})-// --- Health Check ---+// --- Health Check (+ issue #223 credential-rotation probe routes) ---++const healthServer = createServer((req, res) => {+ const url = req.url ?? '/'++ if (url === '/whoami-credential') {+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ key: process.env[ROTATION_CREDENTIAL_ENV_VAR] ?? null }))+ return+ }++ if (url === '/echo-headers') {+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ headers: req.headers }))+ return+ }-const healthServer = createServer((_req, res) => {res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({diff --git a/tests/e2e/integration/mcp-hcc-upgrade-rollout.test.ts b/tests/e2e/integration/mcp-hcc-upgrade-rollout.test.tsnew file mode 100644index 000000000..696469562--- /dev/null+++ b/tests/e2e/integration/mcp-hcc-upgrade-rollout.test.ts@@ -0,0 +1,302 @@+/**+ * E2E: connector credential rotation — E7 "Upgrade" / blast radius R1+ * (issue #223, Fase 4)+ *+ * The credentials-revision annotation is baked into EVERY McpServer's pod+ * template the first time a HCC that knows about it reconciles — not just+ * the ones being rotated (plan section 3, R1). This test reproduces the+ * actual upgrade: connectors first reconciled by a baseline (pre-#223) HCC+ * image, then the branch's HCC image takes over, and asserts:+ * - every connector WITH an envSecret rolls EXACTLY ONCE (Deployment+ * generation advances by exactly 1, not more)+ * - every connector WITHOUT an envSecret does not roll at all (generation+ * unchanged — no annotation ever gets written for it)+ *+ * Precondition this scenario cannot fabricate: a real image built from+ * origin/dev (pre-#223 HCC code), reachable by the cluster. There is no safe+ * way to simulate "the old reconciler" without one — faking it would make+ * this test validate nothing. Required via TEST_HCC_BASELINE_IMAGE; if unset+ * this suite FAILS LOUDLY (not skips) with exactly what to provide.+ *+ * This test mutates a shared, cluster-wide Deployment+ * (host-context-controller in control-plane) for the duration of ONE test,+ * and restores the original image before returning control — both in the+ * test body's own assertions and, as a safety net, in afterAll.+ *+ * Run:+ * TEST_HCC_BASELINE_IMAGE=<origin/dev HCC image> \+ * cd tests/e2e && npx vitest run integration/mcp-hcc-upgrade-rollout+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import {+ MCP_SERVERS_NAMESPACE,+ ROLLOUT_TIMEOUT_MS,+ TEST_CONTEXT_REF,+ adminLogin,+ clusterDiagnostics,+ deleteMcpServerFixture,+ deploymentCredentialsRevisionAnnotation,+ kubectl,+ kubectlApply,+ kubectlSafe,+ localMcpServerYaml,+ randomSuffix,+ requireControlApiUp,+ secretYaml,+ waitFor,+ waitForDeploymentRolloutComplete,+ waitForRolloutCondition,+} from './mcpCredentialRotation.helpers.js'++const HCC_NAMESPACE = 'control-plane'+const HCC_DEPLOYMENT = 'host-context-controller'+const HCC_CONTAINER = 'host-context-controller'+const HCC_ROLLOUT_TIMEOUT_MS = 120_000++const BASELINE_IMAGE = process.env.TEST_HCC_BASELINE_IMAGE ?? ''++const RUN_ID = randomSuffix()+const WITH_SECRET_SERVER = `e2e-rot-upgrade-with-${RUN_ID}`+const WITH_SECRET_NAME = `${WITH_SECRET_SERVER}-credentials`+const WITHOUT_SECRET_SERVER = `e2e-rot-upgrade-without-${RUN_ID}`++let controlApiUp = false+let adminToken = ''+let originalHccImage = ''++function currentHccImage(): string {+ return kubectl(+ `get deployment ${HCC_DEPLOYMENT} -n ${HCC_NAMESPACE} -o jsonpath='{.spec.template.spec.containers[?(@.name=="${HCC_CONTAINER}")].image}'`+ )+}++async function setHccImage(image: string): Promise<void> {+ kubectl(`set image deployment/${HCC_DEPLOYMENT} ${HCC_CONTAINER}=${image} -n ${HCC_NAMESPACE}`)+ await waitFor(+ `HCC Deployment "${HCC_DEPLOYMENT}" rollout to image ${image}`,+ () => {+ try {+ execRolloutStatus()+ return 'ok'+ } catch {+ return null+ }+ },+ HCC_ROLLOUT_TIMEOUT_MS,+ {+ intervalMs: 3_000,+ diagnostics: () =>+ clusterDiagnostics(HCC_NAMESPACE, [+ `describe deployment ${HCC_DEPLOYMENT} -n ${HCC_NAMESPACE}`,+ ]),+ }+ )+}++function execRolloutStatus(): void {+ kubectl(`rollout status deployment/${HCC_DEPLOYMENT} -n ${HCC_NAMESPACE} --timeout=10s`)+}++function deploymentGeneration(name: string): string {+ return kubectl(+ `get deployment ${name} -n ${MCP_SERVERS_NAMESPACE} -o jsonpath='{.metadata.generation}'`+ )+}++beforeAll(+ async () => {+ controlApiUp = await requireControlApiUp('mcp-hcc-upgrade-rollout')+ if (!controlApiUp) return++ if (!BASELINE_IMAGE) {+ throw new Error(+ 'TEST_HCC_BASELINE_IMAGE is required for E7 (upgrade / R1) and was not set. This scenario ' ++ 'reproduces a real upgrade from a PRE-issue-#223 host-context-controller image to the ' ++ 'branch\'s image — there is no safe way to fake "the old reconciler" without a real ' ++ 'baseline image. Build one from origin/dev (e.g. `git worktree add ... origin/dev && ' ++ 'scripts/minikube/build-images.sh host-context-controller` tagged distinctly, e.g. ' ++ 'clerum/host-context-controller:origin-dev-baseline) and load it into the same minikube ' ++ 'profile this suite runs against, then re-run with ' ++ 'TEST_HCC_BASELINE_IMAGE=clerum/host-context-controller:origin-dev-baseline. ' ++ 'Failing loud rather than skipping: a suite that quietly skips R1 coverage would let a ' ++ 'real regression in the upgrade path ship silently.'+ )+ }++ adminToken = await adminLogin()+ originalHccImage = currentHccImage()+ if (!originalHccImage) {+ throw new Error(+ `Could not read the current image of deployment/${HCC_DEPLOYMENT} in ${HCC_NAMESPACE} — ` ++ `cannot safely proceed without knowing what to restore.\n${clusterDiagnostics(+ HCC_NAMESPACE,+ [`describe deployment ${HCC_DEPLOYMENT} -n ${HCC_NAMESPACE}`]+ )}`+ )+ }+ // Connector creation happens INSIDE the first `it()`, after the HCC is+ // already switched to the baseline image — NOT here. If the connectors+ // were created while the branch HCC is still running (the normal state+ // when this suite starts, since T2 deploys the branch first), they would+ // get the credentials-revision annotation from THAT reconcile, and+ // preserveDeploymentAnnotations' `{...existing, ...desired}` merge would+ // let a stale annotation survive the switch to baseline — the "baseline+ // never writes it" assertion would pass for the wrong reason.+ },+ ROLLOUT_TIMEOUT_MS + HCC_ROLLOUT_TIMEOUT_MS + 30_000+)++afterAll(async () => {+ if (!controlApiUp) return+ // Safety net: if the test body's own restore step (below) failed partway,+ // this puts the cluster back for every OTHER suite that runs after it.+ // Idempotent — re-setting the same image is a no-op rollout.+ if (originalHccImage) {+ kubectlSafe(+ `set image deployment/${HCC_DEPLOYMENT} ${HCC_CONTAINER}=${originalHccImage} -n ${HCC_NAMESPACE}`+ )+ }+ deleteMcpServerFixture(WITH_SECRET_SERVER, WITH_SECRET_NAME)+ kubectlSafe(+ `delete mcpserver ${WITHOUT_SECRET_SERVER} -n ${MCP_SERVERS_NAMESPACE} --ignore-not-found --timeout=20s`+ )+})++describe('mcp-secret rotation — E7 upgrade (R1)', () => {+ it(+ 'baseline HCC (pre-#223) reconciles both connectors and never writes the credentials-revision annotation',+ async () => {+ if (!controlApiUp) return++ // Switch to the baseline image FIRST, then create the connectors, so+ // their FIRST-EVER reconcile is done by the pre-#223 reconciler. This+ // is what actually reproduces "connectors already existed when a+ // pre-#223 HCC was in charge" — the starting state E7 requires.+ await setHccImage(BASELINE_IMAGE)++ kubectlApply(+ secretYaml(WITH_SECRET_NAME, MCP_SERVERS_NAMESPACE, { 'api-key': 'upgrade-initial-value' })+ )+ kubectlApply(+ localMcpServerYaml({+ name: WITH_SECRET_SERVER,+ envSecretName: WITH_SECRET_NAME,+ keys: [{ secretKey: 'api-key', envVar: 'E2E_ROTATION_API_KEY' }],+ })+ )+ kubectlApply(localMcpServerYamlNoSecret(WITHOUT_SECRET_SERVER))++ // Wait for a REAL, positive signal that the baseline reconciler's+ // full-reconcile-on-startup actually swept THIS McpServer — never a+ // blind sleep. The line only exists once validateSecret() has run for+ // this specific server (reconciler.ts: `Secret "%s" validated for+ // McpServer %s`).+ await waitFor(+ `baseline HCC to log that it validated the Secret for "${WITH_SECRET_SERVER}"`,+ () => {+ const logs = kubectlSafe(`logs deploy/${HCC_DEPLOYMENT} -n ${HCC_NAMESPACE} --tail=500`)+ return logs &&+ logs.includes(+ `Secret "${WITH_SECRET_NAME}" validated for McpServer ${WITH_SECRET_SERVER}`+ )+ ? 'ok'+ : null+ },+ 60_000,+ {+ intervalMs: 2_000,+ diagnostics: () =>+ clusterDiagnostics(HCC_NAMESPACE, [+ `logs deploy/${HCC_DEPLOYMENT} -n ${HCC_NAMESPACE} --tail=200`,+ ]),+ }+ )++ const annotation = deploymentCredentialsRevisionAnnotation(+ MCP_SERVERS_NAMESPACE,+ WITH_SECRET_SERVER+ )+ expect(+ annotation,+ 'the baseline image already writes clerum.io/credentials-revision — ' ++ 'TEST_HCC_BASELINE_IMAGE is not actually pre-#223, this test cannot prove anything'+ ).toBeNull()++ // Settle both connectors under the baseline reconciler before the next+ // test snapshots their "before" generation — otherwise a still-rolling+ // baseline-created Deployment could bump generation on its own and be+ // mistaken for the upgrade's rollout. We wait on the DEPLOYMENT's own+ // rollout (availableReplicas), NOT the McpServer CRD's DeploymentReady+ // condition: the baseline is a PRE-#204 image whose startup-fleet coupling+ // can delay the CRD condition long past when the pod is actually Available,+ // so asserting the condition here fails for a reason that has nothing to do+ // with issue #223. The workload being settled is exactly what the+ // generation snapshot needs.+ waitForDeploymentRolloutComplete(MCP_SERVERS_NAMESPACE, WITH_SECRET_SERVER)+ waitForDeploymentRolloutComplete(MCP_SERVERS_NAMESPACE, WITHOUT_SECRET_SERVER)+ },+ HCC_ROLLOUT_TIMEOUT_MS + ROLLOUT_TIMEOUT_MS + 60_000+ )++ it(+ 'upgrading to the branch HCC rolls the envSecret connector EXACTLY ONCE and leaves the other untouched',+ async () => {+ if (!controlApiUp) return++ const withSecretGenBefore = deploymentGeneration(WITH_SECRET_SERVER)+ const withoutSecretGenBefore = deploymentGeneration(WITHOUT_SECRET_SERVER)++ const sinceMs = Date.now()+ await setHccImage(originalHccImage)++ const cond = await waitForRolloutCondition(WITH_SECRET_SERVER, adminToken, {+ expectStatus: 'True',+ sinceMs,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ })+ expect(cond.status).toBe('True')++ const annotation = deploymentCredentialsRevisionAnnotation(+ MCP_SERVERS_NAMESPACE,+ WITH_SECRET_SERVER+ )+ expect(annotation).toMatch(/^[0-9a-f]{64}$/)++ const withSecretGenAfter = deploymentGeneration(WITH_SECRET_SERVER)+ const withoutSecretGenAfter = deploymentGeneration(WITHOUT_SECRET_SERVER)++ const withSecretDelta = parseInt(withSecretGenAfter, 10) - parseInt(withSecretGenBefore, 10)+ expect(+ withSecretDelta,+ `expected exactly one rollout generation bump for the envSecret connector, got delta=${withSecretDelta} ` ++ `(before=${withSecretGenBefore}, after=${withSecretGenAfter})`+ ).toBe(1)++ expect(+ withoutSecretGenAfter,+ 'a connector with no envSecret rolled during the HCC upgrade — R1 blast radius is wider than expected'+ ).toBe(withoutSecretGenBefore)+ },+ ROLLOUT_TIMEOUT_MS + HCC_ROLLOUT_TIMEOUT_MS + 30_000+ )+})++function localMcpServerYamlNoSecret(name: string): string {+ return `apiVersion: clerum.io/v1alpha1+kind: McpServer+metadata:+ name: ${name}+ namespace: ${MCP_SERVERS_NAMESPACE}+spec:+ contextRef: ${TEST_CONTEXT_REF}+ description: "issue #223 upgrade E2E fixture — no envSecret, must never roll"+ image: clerum/mock-mcp-server:test+ transport:+ type: streamableHttp+ url: http://${name}.${MCP_SERVERS_NAMESPACE}.svc.cluster.local:3000/mcp+ port: 3000+ healthCheck:+ port: 3001+ enabled: true+`+}diff --git a/tests/e2e/integration/mcp-secret-rotation-failure.test.ts b/tests/e2e/integration/mcp-secret-rotation-failure.test.tsnew file mode 100644index 000000000..a0357c650--- /dev/null+++ b/tests/e2e/integration/mcp-secret-rotation-failure.test.ts@@ -0,0 +1,170 @@+/**+ * E2E: connector credential rotation — E2 "Rollout fallido" (issue #223, Fase 4)+ *+ * Rotates an existing connector's credential to a value that makes the+ * container crash on startup, then asserts the McpServer CRD's+ * `DeploymentReady` condition lands on `False` — and, critically, that the+ * test FAILS if the system ever reports success for that rotation.+ *+ * Pipeline under test:+ * admin login+ * → kubectl apply Secret + McpServer (precondition: connector Ready)+ * → PUT /api/v1/admin/mcp-secrets/:name with the reserved invalid sentinel+ * → HCC SecretInformer → reconcile → new pod template → rolling update+ * → mock-mcp-server refuses to start (real crash-loop, not simulated)+ * → generation-aware readiness never converges+ * → poll exhausts its budget and writes DeploymentReady=False,+ * reason=RolloutIncomplete, with the rollout numbers in the message+ *+ * Atajo prohibido que este test específicamente evita: aceptar el 200 del+ * PUT como señal de éxito. La única señal válida es la condición del CRD.+ *+ * Requires:+ * - minikube cluster with the credential-rotation feature deployed+ * - port-forward to control-api on :8090 (`make minikube-pf-all`)+ * - kubectl configured for context KUBECTL_CONTEXT (default clerum-test)+ *+ * Run:+ * cd tests/e2e && npx vitest run integration/mcp-secret-rotation-failure+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import {+ MCP_SERVERS_NAMESPACE,+ ROLLOUT_FAILURE_TIMEOUT_MS,+ ROLLOUT_TIMEOUT_MS,+ ROTATION_INVALID_SENTINEL,+ adminLogin,+ assertRolloutNeverSucceeds,+ clusterDiagnostics,+ deleteMcpServerFixture,+ deploymentReadyCondition,+ getMcpServerResource,+ kubectlApply,+ kubectlSafe,+ localMcpServerYaml,+ putMcpSecret,+ randomSuffix,+ requireControlApiUp,+ secretYaml,+ waitForRolloutCondition,+} from './mcpCredentialRotation.helpers.js'++const RUN_ID = randomSuffix()+const SERVER_NAME = `e2e-rot-fail-${RUN_ID}`+const SECRET_NAME = `${SERVER_NAME}-credentials`++let controlApiUp = false+let adminToken = ''++beforeAll(async () => {+ controlApiUp = await requireControlApiUp('mcp-secret-rotation-failure')+ if (!controlApiUp) return++ adminToken = await adminLogin()++ kubectlApply(+ secretYaml(SECRET_NAME, MCP_SERVERS_NAMESPACE, {+ 'api-key': 'initial-valid-value',+ })+ )+ kubectlApply(+ localMcpServerYaml({+ name: SERVER_NAME,+ envSecretName: SECRET_NAME,+ keys: [{ secretKey: 'api-key', envVar: 'E2E_ROTATION_API_KEY' }],+ })+ )+}, 30_000)++afterAll(() => {+ if (!controlApiUp) return+ deleteMcpServerFixture(SERVER_NAME, SECRET_NAME)+})++describe('mcp-secret rotation — E2 rollout fallido', () => {+ it(+ 'connector reaches Ready with the initial valid credential (precondition)',+ async () => {+ if (!controlApiUp) return++ const cond = await waitForRolloutCondition(SERVER_NAME, adminToken, {+ expectStatus: 'True',+ sinceMs: 0,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ })+ expect(cond.status).toBe('True')+ },+ ROLLOUT_TIMEOUT_MS + 10_000+ )++ it(+ 'PUT /admin/mcp-secrets rotates to an invalid credential and the CRD condition goes False — never True',+ async () => {+ if (!controlApiUp) return++ const beforeResource = await getMcpServerResource(SERVER_NAME, adminToken)+ const priorCondition = deploymentReadyCondition(beforeResource)+ expect(priorCondition?.status).toBe('True') // sanity: precondition test above actually landed++ const sinceMs = Date.now()+ const { status, data } = await putMcpSecret(+ SECRET_NAME,+ { 'api-key': ROTATION_INVALID_SENTINEL },+ adminToken+ )+ // The PUT itself is expected to succeed — control-api only writes the+ // Secret, it has no idea whether the value will let the container+ // start. Asserting 200 here is NOT the business signal; it only+ // confirms the mutation was accepted so the rollout below is real.+ expect(status, `PUT /admin/mcp-secrets/${SECRET_NAME} body=${JSON.stringify(data)}`).toBe(200)++ // The one and only valid success signal: the CRD condition. This+ // throws immediately if DeploymentReady is ever observed True after+ // `sinceMs` — that is exactly the false-positive this scenario exists+ // to catch — and throws with full diagnostics if the terminal False+ // is never written at all.+ const failedCondition = await assertRolloutNeverSucceeds(+ SERVER_NAME,+ adminToken,+ sinceMs,+ ROLLOUT_FAILURE_TIMEOUT_MS+ )+ expect(failedCondition.status).toBe('False')+ expect(failedCondition.reason).toBe('RolloutIncomplete')+ // The message must be diagnosable, never a silent Unknown (plan Fase 2,+ // point 5) — assert it actually carries rollout numbers, not a generic+ // placeholder string.+ expect(failedCondition.message).toMatch(/generation|updated|ready|unavailable/i)+ },+ ROLLOUT_FAILURE_TIMEOUT_MS + 15_000+ )++ it('the crash-looping pod never became Ready (kubectl-level corroboration)', () => {+ if (!controlApiUp) return++ // A failed credential rotation does NOT drop the Deployment's readyReplicas+ // to 0. With replicas=1 and the default RollingUpdate (maxSurge=1,+ // maxUnavailable=0), Kubernetes keeps the OLD pod Ready while the NEW pod+ // crash-loops on the bad credential — so `.status.readyReplicas` stays at 1+ // (the old pod). That is exactly the trap the HCC readiness fix closes, and+ // asserting readyReplicas===0 here would reproduce the same wrong+ // assumption. Corroborate the failure by the crash itself: at least one pod+ // backing this connector is NOT Ready.+ const readyFlags = kubectlSafe(+ `get pods -n ${MCP_SERVERS_NAMESPACE} -l app=${SERVER_NAME} ` ++ `-o jsonpath='{.items[*].status.containerStatuses[*].ready}'`+ )+ const notReadyCount = (readyFlags ?? '').split(/\s+/).filter(flag => flag === 'false').length+ expect(+ notReadyCount,+ `Expected at least one pod backing ${SERVER_NAME} to be NOT Ready (the new pod crash-looping ` ++ `on the invalid credential), but every container reports ready.\n${clusterDiagnostics(+ MCP_SERVERS_NAMESPACE,+ [+ `get pods -n ${MCP_SERVERS_NAMESPACE} -l app=${SERVER_NAME} -o wide`,+ `describe deployment ${SERVER_NAME} -n ${MCP_SERVERS_NAMESPACE}`,+ ]+ )}`+ ).toBeGreaterThanOrEqual(1)+ })+})diff --git a/tests/e2e/integration/mcp-secret-rotation-isolation.test.ts b/tests/e2e/integration/mcp-secret-rotation-isolation.test.tsnew file mode 100644index 000000000..c4f04c9a3--- /dev/null+++ b/tests/e2e/integration/mcp-secret-rotation-isolation.test.ts@@ -0,0 +1,184 @@+/**+ * E2E: connector credential rotation — E4 "Aislamiento" (issue #223, Fase 4)+ *+ * Rotates connector A's credential and asserts NEGATIVELY that nothing else+ * moved: connector B's McpServer CRD `resourceVersion`, connector B's+ * Deployment `generation`, and connector B's own (unrelated) Secret content+ * all stay byte-for-byte identical.+ *+ * Also carries C6 (plan section 6): the recipe-secret ownership guard on+ * `PUT /admin/mcp-secrets/:name` must key off the SAME label its real+ * producer writes — `POST /admin/recipe-secrets` — not a label the test+ * fabricates itself. A fixture-fabricated label would validate itself even+ * if the guard's constant drifted from the producer's; going through the+ * real endpoint is what makes this a trip-wire instead of a tautology.+ *+ * Atajos evitados: ninguna de las aserciones "no cambió" se basa en el 200+ * del PUT — todas leen el estado real (kubectl / CRD) antes y después.+ *+ * Run:+ * cd tests/e2e && npx vitest run integration/mcp-secret-rotation-isolation+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import {+ CONTROL_API_URL,+ MCP_SERVERS_NAMESPACE,+ ROLLOUT_TIMEOUT_MS,+ adminLogin,+ adminSessionHeader,+ deleteMcpServerFixture,+ fetchJson,+ kubectl,+ kubectlApply,+ kubectlSafe,+ localMcpServerYaml,+ postJson,+ putMcpSecret,+ randomSuffix,+ requireControlApiUp,+ secretDataHash,+ secretYaml,+ waitForRolloutCondition,+} from './mcpCredentialRotation.helpers.js'++const RUN_ID = randomSuffix()+const SERVER_A = `e2e-rot-iso-a-${RUN_ID}`+const SECRET_A = `${SERVER_A}-credentials`+const SERVER_B = `e2e-rot-iso-b-${RUN_ID}`+const SECRET_B = `${SERVER_B}-credentials`+const RECIPE_SECRET_NAME = `e2e-rot-recipe-secret-${RUN_ID}`++let controlApiUp = false+let adminToken = ''++beforeAll(async () => {+ controlApiUp = await requireControlApiUp('mcp-secret-rotation-isolation')+ if (!controlApiUp) return++ adminToken = await adminLogin()++ kubectlApply(secretYaml(SECRET_A, MCP_SERVERS_NAMESPACE, { 'api-key': 'a-initial-value' }))+ kubectlApply(+ localMcpServerYaml({+ name: SERVER_A,+ envSecretName: SECRET_A,+ keys: [{ secretKey: 'api-key', envVar: 'E2E_ROTATION_API_KEY' }],+ })+ )+ kubectlApply(secretYaml(SECRET_B, MCP_SERVERS_NAMESPACE, { 'api-key': 'b-initial-value' }))+ kubectlApply(+ localMcpServerYaml({+ name: SERVER_B,+ envSecretName: SECRET_B,+ keys: [{ secretKey: 'api-key', envVar: 'E2E_ROTATION_API_KEY' }],+ })+ )++ await Promise.all([+ waitForRolloutCondition(SERVER_A, adminToken, {+ expectStatus: 'True',+ sinceMs: 0,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ }),+ waitForRolloutCondition(SERVER_B, adminToken, {+ expectStatus: 'True',+ sinceMs: 0,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ }),+ ])+}, ROLLOUT_TIMEOUT_MS + 30_000)++afterAll(() => {+ if (!controlApiUp) return+ deleteMcpServerFixture(SERVER_A, SECRET_A)+ deleteMcpServerFixture(SERVER_B, SECRET_B)+ kubectlSafe(+ `delete secret ${RECIPE_SECRET_NAME} -n ${MCP_SERVERS_NAMESPACE} --ignore-not-found --timeout=10s`+ )+})++describe('mcp-secret rotation — E4 aislamiento', () => {+ it(+ 'rotating connector A does not touch connector B: resourceVersion, generation, and neighbor Secret content all unchanged',+ async () => {+ if (!controlApiUp) return++ const bResourceVersionBefore = kubectl(+ `get mcpserver ${SERVER_B} -n ${MCP_SERVERS_NAMESPACE} -o jsonpath='{.metadata.resourceVersion}'`+ )+ const bGenerationBefore = kubectl(+ `get deployment ${SERVER_B} -n ${MCP_SERVERS_NAMESPACE} -o jsonpath='{.metadata.generation}'`+ )+ const bSecretHashBefore = secretDataHash(MCP_SERVERS_NAMESPACE, SECRET_B)++ const sinceMs = Date.now()+ const { status } = await putMcpSecret(SECRET_A, { 'api-key': 'a-rotated-value' }, adminToken)+ expect(status).toBe(200)++ // Wait for A's OWN rollout to actually land — the negative assertions+ // below are only meaningful once the system had time to touch+ // anything it might mistakenly touch.+ await waitForRolloutCondition(SERVER_A, adminToken, {+ expectStatus: 'True',+ sinceMs,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ })++ const bResourceVersionAfter = kubectl(+ `get mcpserver ${SERVER_B} -n ${MCP_SERVERS_NAMESPACE} -o jsonpath='{.metadata.resourceVersion}'`+ )+ const bGenerationAfter = kubectl(+ `get deployment ${SERVER_B} -n ${MCP_SERVERS_NAMESPACE} -o jsonpath='{.metadata.generation}'`+ )+ const bSecretHashAfter = secretDataHash(MCP_SERVERS_NAMESPACE, SECRET_B)++ expect(+ bResourceVersionAfter,+ 'connector B McpServer resourceVersion changed — isolation broken'+ ).toBe(bResourceVersionBefore)+ expect(bGenerationAfter, 'connector B Deployment generation changed — isolation broken').toBe(+ bGenerationBefore+ )+ expect(bSecretHashAfter, "connector B's own Secret content changed — isolation broken").toBe(+ bSecretHashBefore+ )+ },+ ROLLOUT_TIMEOUT_MS + 15_000+ )++ it('C6: a Secret created through the REAL recipe-secrets endpoint is guarded — PUT /admin/mcp-secrets returns 409', async () => {+ if (!controlApiUp) return++ const { status: createStatus, data: createData } = await postJson(+ `${CONTROL_API_URL}/api/v1/admin/recipe-secrets`,+ {+ name: RECIPE_SECRET_NAME,+ data: { token: 'recipe-owned-value' },+ ownership: { kind: 'shared' },+ targetNamespace: MCP_SERVERS_NAMESPACE,+ },+ adminSessionHeader(adminToken)+ )+ expect(createStatus, `POST /admin/recipe-secrets failed: ${JSON.stringify(createData)}`).toBe(+ 201+ )++ // Confirm the real producer actually wrote the label the guard checks —+ // otherwise a 409 below would prove nothing about drift.+ const { status: listStatus, data: listData } = await fetchJson<{+ items: Array<{ name: string }>+ }>(`${CONTROL_API_URL}/api/v1/admin/recipe-secrets`, {+ headers: adminSessionHeader(adminToken),+ })+ expect(listStatus).toBe(200)+ expect(listData.items.map(i => i.name)).toContain(RECIPE_SECRET_NAME)++ const { status: putStatus, data: putData } = await putMcpSecret(+ RECIPE_SECRET_NAME,+ { token: 'attempted-bypass-value' },+ adminToken+ )+ expect(putStatus, `expected 409, got ${putStatus}: ${JSON.stringify(putData)}`).toBe(409)+ expect((putData as { error: string }).error).toMatch(/recipe-secrets/i)+ })+})diff --git a/tests/e2e/integration/mcp-secret-rotation-preservation.test.ts b/tests/e2e/integration/mcp-secret-rotation-preservation.test.tsnew file mode 100644index 000000000..918817413--- /dev/null+++ b/tests/e2e/integration/mcp-secret-rotation-preservation.test.ts@@ -0,0 +1,177 @@+/**+ * E2E: connector credential rotation — E3 "Preservación" (issue #223, Fase 4)+ *+ * Rotates ONE of two keys on a connector's Secret and asserts the other key+ * survives untouched. Also carries two of the plan's "tests de composición"+ * (section 6) that specifically need a REAL cluster round-trip, not a mock:+ *+ * C3 — gateway.mergeSecret() <-> the `patch` verb actually granted in the+ * cluster's RBAC. A unit test mocks the gateway and never touches+ * RBAC; the trip-wire here is exercising the REAL PUT. If the+ * deployed Role is missing `patch` on secrets, the request fails and+ * THIS test must fail loudly with the API server's own message — it+ * must not degrade to a skip or swallow the error.+ *+ * C2 — the namespace control-api WRITES the Secret in+ * (MCP_SERVERS_NAMESPACE) vs. the namespace the HCC informer WATCHES+ * (CONTEXT_MAPPER_NAMESPACE) are two independent env vars. If they+ * diverge, nothing rolls, in silence. The only way to catch that from+ * outside both processes is to rotate through the real endpoint and+ * confirm the informer actually reconciled — which is exactly what+ * waiting for a NEW DeploymentReady transition after the PUT proves.+ *+ * C4 — the credentials-revision annotation must hash the Secret's REAL+ * post-merge content, not a stale pre-merge read. Verified by reading+ * the Secret back from the cluster, hashing it with the exact+ * canonicalStringify+sha256 algorithm host-context-controller uses,+ * and comparing to the annotation actually on the pod template.+ *+ * Atajos prohibidos evitados aquí: no se escribe el Secret con kubectl (sólo+ * se lee, para el hash) y no se asume éxito por el 200 del PUT — la+ * preservación se verifica leyendo el Secret real, y el rollout se verifica+ * en el CRD.+ *+ * Run:+ * cd tests/e2e && npx vitest run integration/mcp-secret-rotation-preservation+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import {+ MCP_SERVERS_NAMESPACE,+ ROLLOUT_TIMEOUT_MS,+ adminLogin,+ canonicalStringify,+ deleteMcpServerFixture,+ deploymentCredentialsRevisionAnnotation,+ kubectlApply,+ kubectlJson,+ localMcpServerYaml,+ putMcpSecret,+ randomSuffix,+ requireControlApiUp,+ secretDataHash,+ secretYaml,+ waitForRolloutCondition,+} from './mcpCredentialRotation.helpers.js'++const RUN_ID = randomSuffix()+const SERVER_NAME = `e2e-rot-preserve-${RUN_ID}`+const SECRET_NAME = `${SERVER_NAME}-credentials`++let controlApiUp = false+let adminToken = ''++beforeAll(async () => {+ controlApiUp = await requireControlApiUp('mcp-secret-rotation-preservation')+ if (!controlApiUp) return++ adminToken = await adminLogin()++ kubectlApply(+ secretYaml(SECRET_NAME, MCP_SERVERS_NAMESPACE, {+ 'api-key': 'initial-api-key-value',+ 'webhook-secret': 'initial-webhook-secret-value',+ })+ )+ kubectlApply(+ localMcpServerYaml({+ name: SERVER_NAME,+ envSecretName: SECRET_NAME,+ keys: [+ { secretKey: 'api-key', envVar: 'E2E_ROTATION_API_KEY' },+ { secretKey: 'webhook-secret', envVar: 'E2E_ROTATION_WEBHOOK_SECRET' },+ ],+ })+ )++ await waitForRolloutCondition(SERVER_NAME, adminToken, {+ expectStatus: 'True',+ sinceMs: 0,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ })+}, ROLLOUT_TIMEOUT_MS + 30_000)++afterAll(() => {+ if (!controlApiUp) return+ deleteMcpServerFixture(SERVER_NAME, SECRET_NAME)+})++describe('mcp-secret rotation — E3 preservación + C2 + C3 + C4', () => {+ it(+ 'PUT with only api-key rotates that key, preserves webhook-secret, and triggers a real rollout (C2, C3)',+ async () => {+ if (!controlApiUp) return++ const sinceMs = Date.now()+ const { status, data } = await putMcpSecret(+ SECRET_NAME,+ { 'api-key': 'rotated-api-key-value' },+ adminToken+ )+ // C3: if the deployed Role lost the `patch` verb on secrets, mergeSecret+ // fails and this assertion fails loudly with the API server's message+ // embedded in the response body — never a silent skip or a swallowed+ // error. This IS the trip-wire the plan calls for.+ expect(status, `PUT /admin/mcp-secrets/${SECRET_NAME} failed: ${JSON.stringify(data)}`).toBe(+ 200+ )+ const body = data as { keys: string[]; affectedConnectors: string[] }+ expect(body.keys.sort()).toEqual(['api-key', 'webhook-secret'])+ expect(body.affectedConnectors).toContain(SERVER_NAME)++ // Read the Secret back from the cluster (never assume from the PUT body+ // — the response is names-only by contract).+ const secret = kubectlJson<{ data: Record<string, string> }>(+ `get secret ${SECRET_NAME} -n ${MCP_SERVERS_NAMESPACE}`+ )+ const rotatedValue = Buffer.from(secret.data['api-key'], 'base64').toString('utf-8')+ const preservedValue = Buffer.from(secret.data['webhook-secret'], 'base64').toString('utf-8')+ expect(rotatedValue).toBe('rotated-api-key-value')+ expect(preservedValue).toBe('initial-webhook-secret-value')++ // C2: the ONLY way to prove the write-side namespace (control-api's+ // MCP_SERVERS_NAMESPACE) and the watch-side namespace (HCC's+ // CONTEXT_MAPPER_NAMESPACE) actually agree in THIS cluster is to see+ // the informer react — a NEW DeploymentReady transition after the PUT.+ // If they diverged, this call times out with full diagnostics instead+ // of silently reporting "some rollout happened at some point."+ const cond = await waitForRolloutCondition(SERVER_NAME, adminToken, {+ expectStatus: 'True',+ sinceMs,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ })+ expect(cond.status).toBe('True')+ },+ ROLLOUT_TIMEOUT_MS + 15_000+ )++ it('C4: the pod template credentials-revision annotation matches the REAL post-merge Secret hash', () => {+ if (!controlApiUp) return++ const actualHash = secretDataHash(MCP_SERVERS_NAMESPACE, SECRET_NAME)+ const annotation = deploymentCredentialsRevisionAnnotation(MCP_SERVERS_NAMESPACE, SERVER_NAME)++ expect(+ annotation,+ 'Deployment pod template is missing clerum.io/credentials-revision'+ ).not.toBeNull()+ expect(annotation).toBe(actualHash)++ // Sanity: canonicalStringify really is order-independent, matching the+ // idempotence guarantee host-context-controller relies on (Fase 2 tests).+ expect(canonicalStringify({ b: '2', a: '1' })).toBe(canonicalStringify({ a: '1', b: '2' }))+ })++ it('rotating with the SAME value again is idempotent — no unnecessary rollout signal change', async () => {+ if (!controlApiUp) return++ const hashBefore = secretDataHash(MCP_SERVERS_NAMESPACE, SECRET_NAME)+ const { status } = await putMcpSecret(+ SECRET_NAME,+ { 'api-key': 'rotated-api-key-value' }, // same value as the prior rotation+ adminToken+ )+ expect(status).toBe(200)+ const hashAfter = secretDataHash(MCP_SERVERS_NAMESPACE, SECRET_NAME)+ expect(hashAfter).toBe(hashBefore)+ })+})diff --git a/tests/e2e/integration/mcp-secret-rotation-remote.test.ts b/tests/e2e/integration/mcp-secret-rotation-remote.test.tsnew file mode 100644index 000000000..cc9aa572f--- /dev/null+++ b/tests/e2e/integration/mcp-secret-rotation-remote.test.ts@@ -0,0 +1,143 @@+/**+ * E2E: connector credential rotation — E6 "Connector remoto" (issue #223, Fase 4)+ *+ * A remote McpServer's `authHeaders` forward an envSecret-backed credential+ * as an upstream header, resolved by nginx's envsubst at pod startup+ * (host-context-controller/src/reconciler.ts:644-660). This test rotates+ * that credential and makes a REAL request through the connector's own+ * egress-proxy Service, verifying the upstream actually received the NEW+ * value — not that "something changed on the Deployment".+ *+ * The upstream target must be a real internet HTTPS DNS host:+ * `sanitizeRemoteUrl()` (host-context-controller/src/reconciler.ts:348)+ * explicitly REJECTS any `*.svc` / `*.svc.cluster.local` hostname as an SSRF+ * guard, so this cannot point at another in-cluster fixture. It defaults to+ * https://httpbin.org/headers — the same public host this repo's+ * mock-mcp-server `fetch_http` egress-probe tool already allowlists by+ * default (EGRESS_PROBE_ALLOWED_HOSTS) — and can be overridden with+ * TEST_REMOTE_ECHO_URL if that host becomes unreliable in a given+ * environment. This is a real external-network dependency, not a mock.+ *+ * Atajo evitado: la petición no se hace contra el Secret ni contra el CRD —+ * se hace contra el proxy real, con las cabeceras reales que produjo nginx.+ *+ * Run:+ * cd tests/e2e && npx vitest run integration/mcp-secret-rotation-remote+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import {+ MCP_SERVERS_NAMESPACE,+ ROLLOUT_TIMEOUT_MS,+ adminLogin,+ deleteMcpServerFixture,+ kubectlApply,+ putMcpSecret,+ randomSuffix,+ remoteMcpServerYaml,+ requireControlApiUp,+ secretYaml,+ waitForRolloutCondition,+ withServicePortForward,+} from './mcpCredentialRotation.helpers.js'++const REMOTE_ECHO_URL = process.env.TEST_REMOTE_ECHO_URL ?? 'https://httpbin.org/headers'+const REMOTE_ECHO_PATH = new URL(REMOTE_ECHO_URL).pathname++const RUN_ID = randomSuffix()+const SERVER_NAME = `e2e-rot-remote-${RUN_ID}`+const SECRET_NAME = `${SERVER_NAME}-credentials`+const AUTH_HEADER_NAME = 'X-E2e-Rotation-Key'+const TRANSPORT_PORT = 3000++let controlApiUp = false+let adminToken = ''++beforeAll(async () => {+ controlApiUp = await requireControlApiUp('mcp-secret-rotation-remote')+ if (!controlApiUp) return++ adminToken = await adminLogin()++ kubectlApply(+ secretYaml(SECRET_NAME, MCP_SERVERS_NAMESPACE, { 'api-key': 'initial-remote-value' })+ )+ kubectlApply(+ remoteMcpServerYaml({+ name: SERVER_NAME,+ baseUrl: REMOTE_ECHO_URL,+ envSecretName: SECRET_NAME,+ keys: [{ secretKey: 'api-key', envVar: 'E2E_ROTATION_API_KEY' }],+ authHeaders: [{ header: AUTH_HEADER_NAME, valueTemplate: '${E2E_ROTATION_API_KEY}' }],+ transportPort: TRANSPORT_PORT,+ })+ )++ await waitForRolloutCondition(SERVER_NAME, adminToken, {+ expectStatus: 'True',+ sinceMs: 0,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ })+}, ROLLOUT_TIMEOUT_MS + 30_000)++afterAll(() => {+ if (!controlApiUp) return+ deleteMcpServerFixture(SERVER_NAME, SECRET_NAME)+})++/** httpbin (and intermediate proxies) may title-case header names differently than sent. */+function lowerCaseKeys(obj: Record<string, string>): Record<string, string> {+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k.toLowerCase(), v]))+}++async function fetchEchoedAuthHeader(): Promise<string | undefined> {+ return withServicePortForward(+ MCP_SERVERS_NAMESPACE,+ SERVER_NAME,+ TRANSPORT_PORT,+ async baseUrl => {+ const res = await fetch(`${baseUrl}${REMOTE_ECHO_PATH}`, {+ signal: AbortSignal.timeout(15_000),+ })+ expect(res.status, `proxy request to ${REMOTE_ECHO_URL} returned ${res.status}`).toBe(200)+ const json = (await res.json()) as { headers: Record<string, string> }+ return lowerCaseKeys(json.headers)[AUTH_HEADER_NAME.toLowerCase()]+ }+ )+}++describe('mcp-secret rotation — E6 connector remoto', () => {+ it('a real request through the proxy carries the INITIAL credential before rotation', async () => {+ if (!controlApiUp) return+ const header = await fetchEchoedAuthHeader()+ expect(header).toBe('initial-remote-value')+ }, 30_000)++ it(+ 'after rotation, the proxy is redeployed and a real request carries the NEW credential',+ async () => {+ if (!controlApiUp) return++ const sinceMs = Date.now()+ const { status, data } = await putMcpSecret(+ SECRET_NAME,+ { 'api-key': 'rotated-remote-value' },+ adminToken+ )+ expect(status, `PUT failed: ${JSON.stringify(data)}`).toBe(200)++ await waitForRolloutCondition(SERVER_NAME, adminToken, {+ expectStatus: 'True',+ sinceMs,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ })++ const header = await fetchEchoedAuthHeader()+ expect(+ header,+ 'the upstream echo endpoint did not observe the rotated credential — ' ++ 'either the pod did not roll, or it rolled with a stale envsubst value'+ ).toBe('rotated-remote-value')+ },+ ROLLOUT_TIMEOUT_MS + 30_000+ )+})diff --git a/tests/e2e/integration/mcp-secret-rotation-shared.test.ts b/tests/e2e/integration/mcp-secret-rotation-shared.test.tsnew file mode 100644index 000000000..00e5b44c2--- /dev/null+++ b/tests/e2e/integration/mcp-secret-rotation-shared.test.ts@@ -0,0 +1,154 @@+/**+ * E2E: connector credential rotation — E5 "Secret compartido" (issue #223, Fase 4)+ *+ * Two connectors reference the SAME envSecret. One rotation must roll BOTH+ * Deployments, and both must actually be serving the new credential+ * afterward — not just "Ready" per Kubernetes bookkeeping.+ *+ * Also carries C7 (plan section 6): `affectedConnectors` in the PUT response+ * must name BOTH connectors. A test fixture with an invented shape would+ * validate the filter tautologically; this hits the real+ * `gateway.listResource('mcpservers', ns)` shape, so if it ever diverges+ * from what the route assumes, `affectedConnectors` silently returns `[]`+ * and this test is what catches it.+ *+ * "Ambos responden" is verified by asking each connector's OWN pod, through+ * its own Service (transient port-forward, no shared infra), what value of+ * E2E_ROTATION_API_KEY it currently has injected — proving the pod actually+ * restarted with the new credential, not just that the Deployment object+ * looks converged.+ *+ * Run:+ * cd tests/e2e && npx vitest run integration/mcp-secret-rotation-shared+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import {+ MCP_SERVERS_NAMESPACE,+ ROLLOUT_TIMEOUT_MS,+ adminLogin,+ deleteMcpServerFixture,+ kubectlApply,+ localMcpServerYaml,+ putMcpSecret,+ randomSuffix,+ requireControlApiUp,+ secretYaml,+ waitForRolloutCondition,+ withServicePortForward,+} from './mcpCredentialRotation.helpers.js'++const RUN_ID = randomSuffix()+const SHARED_SECRET_NAME = `e2e-rot-shared-${RUN_ID}`+const SERVER_1 = `e2e-rot-shared-c1-${RUN_ID}`+const SERVER_2 = `e2e-rot-shared-c2-${RUN_ID}`++let controlApiUp = false+let adminToken = ''++beforeAll(async () => {+ controlApiUp = await requireControlApiUp('mcp-secret-rotation-shared')+ if (!controlApiUp) return++ adminToken = await adminLogin()++ kubectlApply(+ secretYaml(SHARED_SECRET_NAME, MCP_SERVERS_NAMESPACE, { 'api-key': 'initial-shared-value' })+ )+ kubectlApply(+ localMcpServerYaml({+ name: SERVER_1,+ envSecretName: SHARED_SECRET_NAME,+ keys: [{ secretKey: 'api-key', envVar: 'E2E_ROTATION_API_KEY' }],+ })+ )+ kubectlApply(+ localMcpServerYaml({+ name: SERVER_2,+ envSecretName: SHARED_SECRET_NAME,+ keys: [{ secretKey: 'api-key', envVar: 'E2E_ROTATION_API_KEY' }],+ })+ )++ await Promise.all([+ waitForRolloutCondition(SERVER_1, adminToken, {+ expectStatus: 'True',+ sinceMs: 0,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ }),+ waitForRolloutCondition(SERVER_2, adminToken, {+ expectStatus: 'True',+ sinceMs: 0,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ }),+ ])+}, ROLLOUT_TIMEOUT_MS + 30_000)++afterAll(() => {+ if (!controlApiUp) return+ // Only one Secret backs both connectors — delete it once, after both+ // McpServers are gone (kubectlSafe ignores already-deleted resources).+ deleteMcpServerFixture(SERVER_1, SHARED_SECRET_NAME)+ deleteMcpServerFixture(SERVER_2, SHARED_SECRET_NAME)+})++describe('mcp-secret rotation — E5 secret compartido + C7', () => {+ it(+ 'PUT names BOTH connectors in affectedConnectors (C7), and BOTH roll',+ async () => {+ if (!controlApiUp) return++ const sinceMs = Date.now()+ const { status, data } = await putMcpSecret(+ SHARED_SECRET_NAME,+ { 'api-key': 'rotated-shared-value' },+ adminToken+ )+ expect(status, `PUT failed: ${JSON.stringify(data)}`).toBe(200)+ const body = data as { affectedConnectors: string[] }+ expect(body.affectedConnectors.sort()).toEqual([SERVER_1, SERVER_2].sort())++ const [cond1, cond2] = await Promise.all([+ waitForRolloutCondition(SERVER_1, adminToken, {+ expectStatus: 'True',+ sinceMs,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ }),+ waitForRolloutCondition(SERVER_2, adminToken, {+ expectStatus: 'True',+ sinceMs,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ }),+ ])+ expect(cond1.status).toBe('True')+ expect(cond2.status).toBe('True')+ },+ ROLLOUT_TIMEOUT_MS + 20_000+ )++ it('both connectors actually serve the NEW credential after rollout ("ambos responden")', async () => {+ if (!controlApiUp) return++ for (const server of [SERVER_1, SERVER_2]) {+ const observedKey = await withServicePortForward(+ MCP_SERVERS_NAMESPACE,+ server,+ 3001,+ async baseUrl => {+ const res = await fetch(`${baseUrl}/whoami-credential`, {+ signal: AbortSignal.timeout(5_000),+ })+ expect(res.status, `${server} /whoami-credential returned ${res.status}`).toBe(200)+ const json = (await res.json()) as { key: string | null }+ return json.key+ },+ 20_000,+ // /whoami-credential lives on the mock's health server (3001), which the+ // connector's Service does not publish — forward to the Deployment/pod.+ 'deploy'+ )+ expect(observedKey, `${server} is not serving the rotated credential`).toBe(+ 'rotated-shared-value'+ )+ }+ }, 30_000)+})diff --git a/tests/e2e/integration/mcp-secrets-access-guard.test.ts b/tests/e2e/integration/mcp-secrets-access-guard.test.tsnew file mode 100644index 000000000..f699c544b--- /dev/null+++ b/tests/e2e/integration/mcp-secrets-access-guard.test.ts@@ -0,0 +1,65 @@+/**+ * E2E: connector credential rotation — E9 "Guardia de acceso" (issue #223, Fase 4)+ *+ * PUT /api/v1/admin/mcp-secrets/:name without an operator session must be+ * rejected — the same `requireAuthForControlUI` gate every other /admin+ * route goes through (control-api/src/app.ts:139-149). No fixture or mock+ * stands in for auth here: this hits the real route on the real cluster.+ *+ * Run:+ * cd tests/e2e && npx vitest run integration/mcp-secrets-access-guard+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import {+ MCP_SERVERS_NAMESPACE,+ kubectlApply,+ kubectlSafe,+ putMcpSecret,+ randomSuffix,+ requireControlApiUp,+ secretYaml,+} from './mcpCredentialRotation.helpers.js'++const RUN_ID = randomSuffix()+const SECRET_NAME = `e2e-rot-guard-${RUN_ID}`++let controlApiUp = false++beforeAll(async () => {+ controlApiUp = await requireControlApiUp('mcp-secrets-access-guard')+ if (!controlApiUp) return++ // Precondition only: a Secret must exist for the route to reach its auth+ // gate meaningfully (a 404 for "no such secret" would be a false pass).+ // Written via kubectl because this test's business is authorization, not+ // rotation — the PUT under test is the request WITHOUT a token, never+ // used to establish state.+ kubectlApply(secretYaml(SECRET_NAME, MCP_SERVERS_NAMESPACE, { 'api-key': 'guarded-value' }))+}, 15_000)++afterAll(() => {+ if (!controlApiUp) return+ kubectlSafe(+ `delete secret ${SECRET_NAME} -n ${MCP_SERVERS_NAMESPACE} --ignore-not-found --timeout=10s`+ )+})++describe('mcp-secret rotation — E9 guardia de acceso', () => {+ it('PUT without a session cookie is rejected (401/403), never 200', async () => {+ if (!controlApiUp) return++ const { status, data } = await putMcpSecret(SECRET_NAME, { 'api-key': 'attempted-bypass' })+ expect([401, 403], `expected 401/403, got ${status}: ${JSON.stringify(data)}`).toContain(status)+ })++ it('PUT with a garbage session cookie is rejected (401/403), never 200', async () => {+ if (!controlApiUp) return++ const { status, data } = await putMcpSecret(+ SECRET_NAME,+ { 'api-key': 'attempted-bypass-2' },+ 'not-a-real-session-jwt'+ )+ expect([401, 403], `expected 401/403, got ${status}: ${JSON.stringify(data)}`).toContain(status)+ })+})diff --git a/tests/e2e/integration/mcp-server-readiness-regression.test.ts b/tests/e2e/integration/mcp-server-readiness-regression.test.tsnew file mode 100644index 000000000..85ee3a3ff--- /dev/null+++ b/tests/e2e/integration/mcp-server-readiness-regression.test.ts@@ -0,0 +1,119 @@+/**+ * E2E: connector credential rotation — E8 "Regresión de readiness" / R2+ * (issue #223, Fase 4)+ *+ * The generation-aware readiness check (host-context-controller/src/reconciler.ts+ * readDeploymentRollout) is stricter than the old `readyReplicas > 0` check —+ * it now requires observedGeneration to have caught up AND+ * updated/ready/unavailable replica counts to all agree. That stricter gate+ * governs EVERY connector's rollout, not just rotations (plan section 3, R2).+ * This test has no rotation in it at all: a brand-new connector must still+ * reach Ready within the poll budget (24 attempts x 5s = 120s,+ * reconciler.ts pollReadiness).+ *+ * Run:+ * cd tests/e2e && npx vitest run integration/mcp-server-readiness-regression+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import {+ MCP_SERVERS_NAMESPACE,+ ROLLOUT_TIMEOUT_MS,+ adminLogin,+ clusterDiagnostics,+ kubectl,+ kubectlApply,+ kubectlJson,+ kubectlSafe,+ localMcpServerYaml,+ randomSuffix,+ requireControlApiUp,+ secretYaml,+ waitForRolloutCondition,+} from './mcpCredentialRotation.helpers.js'++const RUN_ID = randomSuffix()+const SERVER_NAME = `e2e-rot-readiness-${RUN_ID}`+const SECRET_NAME = `${SERVER_NAME}-credentials`++let controlApiUp = false+let adminToken = ''++beforeAll(async () => {+ controlApiUp = await requireControlApiUp('mcp-server-readiness-regression')+ if (!controlApiUp) return+ adminToken = await adminLogin()+}, 15_000)++afterAll(() => {+ if (!controlApiUp) return+ kubectlSafe(+ `delete mcpserver ${SERVER_NAME} -n ${MCP_SERVERS_NAMESPACE} --ignore-not-found --timeout=20s`+ )+ kubectlSafe(+ `delete secret ${SECRET_NAME} -n ${MCP_SERVERS_NAMESPACE} --ignore-not-found --timeout=10s`+ )+})++describe('mcp-secret rotation — E8 regresión de readiness (R2)', () => {+ it(+ 'a brand-new connector (no rotation involved) reaches Ready within the poll budget',+ async () => {+ if (!controlApiUp) return++ kubectlApply(+ secretYaml(SECRET_NAME, MCP_SERVERS_NAMESPACE, { 'api-key': 'readiness-check-value' })+ )+ const createdAt = Date.now()+ kubectlApply(+ localMcpServerYaml({+ name: SERVER_NAME,+ envSecretName: SECRET_NAME,+ keys: [{ secretKey: 'api-key', envVar: 'E2E_ROTATION_API_KEY' }],+ })+ )++ const cond = await waitForRolloutCondition(SERVER_NAME, adminToken, {+ expectStatus: 'True',+ sinceMs: createdAt,+ timeoutMs: ROLLOUT_TIMEOUT_MS,+ })+ expect(cond.status).toBe('True')+ expect(cond.reason).toBe('ReplicasAvailable')++ // Corroborate directly against the Deployment status — the same four+ // fields readDeploymentRollout requires to ALL hold simultaneously.+ const deployment = kubectlJson<{+ metadata: { generation: number }+ spec: { replicas: number }+ status: {+ observedGeneration: number+ updatedReplicas?: number+ readyReplicas?: number+ unavailableReplicas?: number+ }+ }>(`get deployment ${SERVER_NAME} -n ${MCP_SERVERS_NAMESPACE}`)++ const diag = () =>+ clusterDiagnostics(MCP_SERVERS_NAMESPACE, [+ `describe deployment ${SERVER_NAME} -n ${MCP_SERVERS_NAMESPACE}`,+ ])++ expect(deployment.status.observedGeneration, diag()).toBeGreaterThanOrEqual(+ deployment.metadata.generation+ )+ expect(deployment.status.updatedReplicas ?? 0, diag()).toBe(deployment.spec.replicas)+ expect(deployment.status.readyReplicas ?? 0, diag()).toBe(deployment.spec.replicas)+ expect(deployment.status.unavailableReplicas ?? 0, diag()).toBe(0)+ },+ ROLLOUT_TIMEOUT_MS + 15_000+ )++ it('the pod backing the connector is actually Running (not just "the Deployment object looks converged")', () => {+ if (!controlApiUp) return++ const phase = kubectl(+ `get pod -l app=${SERVER_NAME} -n ${MCP_SERVERS_NAMESPACE} -o jsonpath='{.items[0].status.phase}'`+ )+ expect(phase).toBe('Running')+ })+})diff --git a/tests/e2e/integration/mcpCredentialRotation.helpers.ts b/tests/e2e/integration/mcpCredentialRotation.helpers.tsnew file mode 100644index 000000000..a3190e4b9--- /dev/null+++ b/tests/e2e/integration/mcpCredentialRotation.helpers.ts@@ -0,0 +1,627 @@+/**+ * Shared helpers for the connector credential-rotation E2E suites+ * (issue #223, Fase 4 of the plan).+ *+ * These suites exercise the REAL `PUT /api/v1/admin/mcp-secrets/:name`+ * endpoint against a live minikube cluster and observe the HCC's reaction+ * through kubectl and the real `GET /api/v1/admin/mcp-servers/:name` — never+ * the other way around (writing the Secret with kubectl, or asserting on the+ * PUT's 200 alone, are the "atajos prohibidos" the plan calls out).+ *+ * See: .ralph/plans/2026-07-31-issue-223-mcp-connector-credential-rotation.md+ * Fase 4 ("Contrato E2E de la rotación") and section 6 ("Tests de+ * composición").+ *+ * Fail-loud contract:+ * - `requireControlApiUp()` throws if control-api is unreachable, unless+ * E2E_SKIP_IF_CLUSTER_UNREACHABLE=1 is set explicitly (mirrors the+ * opt-in-only skip already used by integration/channel-reader-via-api.test.ts).+ * - `waitFor()` never returns a "probably fine" result: it throws with a+ * kubectl diagnostic dump on timeout.+ * - Cleanup in `afterAll` blocks is the one place best-effort kubectl+ * deletes are allowed to swallow errors — that mirrors existing+ * convention and never masks a test's own assertions.+ */+import { execSync, spawn } from 'child_process'+import { createHash, randomBytes } from 'crypto'+import {+ CONTROL_API_URL,+ deleteJson,+ fetchJson,+ isServiceUp,+ postJson,+ putJson,+} from './helpers.integration.js'++export { CONTROL_API_URL, deleteJson, fetchJson, isServiceUp, postJson, putJson }++// ─── Configuration ──────────────────────────────────────────────────────────++export const KUBECTL_CONTEXT = process.env.KUBECTL_CONTEXT ?? 'clerum-test'+export const MCP_SERVERS_NAMESPACE = process.env.TEST_MCP_SERVERS_NAMESPACE ?? 'mcp-server'+export const TEST_CONTEXT_REF = process.env.TEST_CONTEXT_REF ?? 'context1'+export const MOCK_MCP_IMAGE = process.env.TEST_MOCK_MCP_IMAGE ?? 'clerum/mock-mcp-server:test'++// Must match the identically-named constants in+// tests/e2e/fixtures/mock-mcp-server/src/index.ts. Duplicated across the two+// build artifacts on purpose — a test-fixture container image can't import+// from the vitest project — and cross-referenced by comment on both sides so+// drift is visible in review. Same pattern as RECIPE_SECRET_LABEL_KEY in+// control-api/src/routes/admin/secrets.ts (module-scope constant, reused by+// every consumer instead of a duplicated literal).+export const ROTATION_CREDENTIAL_ENV_VAR = 'E2E_ROTATION_API_KEY'+export const ROTATION_INVALID_SENTINEL = '__E2E_INVALID_CREDENTIAL__'++// Generation-aware readiness budget is 24 attempts x 5s = 120s+// (host-context-controller/src/reconciler.ts pollReadiness). Happy-path+// rollouts converge much faster in practice; the failure path (E2) must run+// the budget all the way out before it is provably stuck, so it gets a+// larger ceiling.+export const ROLLOUT_TIMEOUT_MS = 90_000+export const ROLLOUT_FAILURE_TIMEOUT_MS = 150_000++export const SKIP_IF_UNREACHABLE = process.env.E2E_SKIP_IF_CLUSTER_UNREACHABLE === '1'++export function randomSuffix(): string {+ return randomBytes(3).toString('hex')+}++// ─── kubectl ────────────────────────────────────────────────────────────────++export function kubectl(args: string): string {+ return execSync(`kubectl --context=${KUBECTL_CONTEXT} ${args}`, {+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'pipe'],+ }).trim()+}++export function kubectlSafe(args: string): string | null {+ try {+ return kubectl(args)+ } catch {+ return null+ }+}++export function kubectlApply(yaml: string): string {+ return execSync(`kubectl --context=${KUBECTL_CONTEXT} apply -f -`, {+ encoding: 'utf-8',+ input: yaml,+ }).trim()+}++export function kubectlJson<T>(args: string): T {+ return JSON.parse(kubectl(`${args} -o json`)) as T+}++/** Best-effort diagnostic dump embedded in timeout errors — never throws itself. */+export function clusterDiagnostics(namespace: string, extra: string[] = []): string {+ const commands = [+ `get mcpservers -n ${namespace} -o wide`,+ `get deployments -n ${namespace} -o wide`,+ `get pods -n ${namespace} -o wide`,+ ...extra,+ ]+ return commands+ .map(cmd => `$ kubectl ${cmd}\n${kubectlSafe(cmd) ?? '(command failed — see stderr above)'}`)+ .join('\n\n')+}++// ─── waitFor ────────────────────────────────────────────────────────────────++export async function waitFor<T>(+ description: string,+ predicate: () => T | null | undefined | Promise<T | null | undefined>,+ timeoutMs: number,+ opts: { intervalMs?: number; diagnostics?: () => string } = {}+): Promise<T> {+ const intervalMs = opts.intervalMs ?? 1_500+ const start = Date.now()+ let lastErr: unknown+ while (Date.now() - start < timeoutMs) {+ try {+ const result = await predicate()+ if (result !== null && result !== undefined && result !== '' && result !== false) {+ return result as T+ }+ } catch (err) {+ lastErr = err+ }+ await new Promise(r => setTimeout(r, intervalMs))+ }+ const diag = opts.diagnostics ? `\n\n--- diagnostics ---\n${opts.diagnostics()}` : ''+ throw new Error(+ `Timed out waiting for: ${description} (${timeoutMs}ms). Last error: ${+ lastErr instanceof Error ? lastErr.message : String(lastErr)+ }${diag}`+ )+}++// ─── control-api admin auth ─────────────────────────────────────────────────++/** Cookie name control-api's admin session lives in — must match+ * control-api/src/middleware/controlUIAuth.ts (readCookie) and the+ * Set-Cookie written by control-api/src/routes/admin/auth.ts. */+export const ADMIN_SESSION_COOKIE = 'control_ui_admin_session'++/**+ * Cookie header for authenticated /admin requests.+ *+ * control-api's admin auth is cookie-only by design: the login handler+ * (control-api/src/routes/admin/auth.ts) puts the signed JWT EXCLUSIVELY in+ * an httpOnly `control_ui_admin_session` Set-Cookie — the response body+ * carries no token — and `requireAuthForControlUI`+ * (control-api/src/middleware/controlUIAuth.ts) reads it EXCLUSIVELY from+ * that cookie; `Authorization: Bearer` is never consulted. So the suites+ * authenticate the same way a browser would: replay the cookie value.+ * (The cookie's `Secure` flag only constrains browsers — an explicit Cookie+ * header sent over plain HTTP by the test client is delivered unchanged.)+ */+export function adminSessionHeader(session: string): Record<string, string> {+ return { Cookie: `${ADMIN_SESSION_COOKIE}=${session}` }+}++/**+ * Logs in as the admin and returns the session JWT extracted from the+ * login response's Set-Cookie header. Uses `fetch` directly (not postJson)+ * because the shared fetchJson helper deliberately exposes only+ * { status, data } — and the credential ONLY exists in a response header.+ */+export async function adminLogin(): Promise<string> {+ const adminUsername = process.env.TEST_ADMIN_USERNAME ?? 'admin'+ const adminPassword = process.env.TEST_ADMIN_PASSWORD ?? 'changeme123!'+ const res = await fetch(`${CONTROL_API_URL}/api/v1/admin/auth/login`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ username: adminUsername, password: adminPassword }),+ })+ if (res.status !== 200) {+ throw new Error(+ `admin login failed (status=${res.status}, body=${await res.text()}). Override with ` ++ `TEST_ADMIN_USERNAME / TEST_ADMIN_PASSWORD if the cluster's defaults differ.`+ )+ }+ const setCookies = res.headers.getSetCookie()+ for (const cookie of setCookies) {+ const match = cookie.match(new RegExp(`^${ADMIN_SESSION_COOKIE}=([^;]+)`))+ if (match) return match[1]+ }+ throw new Error(+ `admin login returned 200 but no "${ADMIN_SESSION_COOKIE}" Set-Cookie header. ` ++ `Set-Cookie headers received: ${JSON.stringify(setCookies)}. The control-api auth ` ++ `contract (httpOnly session cookie) may have changed — see control-api/src/routes/admin/auth.ts.`+ )+}++/**+ * Fail-loud cluster reachability check. Returns `false` ONLY when the+ * explicit opt-out env var is set — the caller then must skip the whole+ * suite by returning early from every `it()`, matching the established+ * `if (!controlApiUp) return` convention in this directory. Never a silent+ * default skip.+ */+export async function requireControlApiUp(suiteName: string): Promise<boolean> {+ const up = await isServiceUp(CONTROL_API_URL)+ if (up) return true+ const msg = `[${suiteName}] control-api not reachable at ${CONTROL_API_URL}`+ if (SKIP_IF_UNREACHABLE) {+ console.log(`${msg} — tests will be skipped (E2E_SKIP_IF_CLUSTER_UNREACHABLE=1)`)+ return false+ }+ throw new Error(+ `${msg}. This E2E suite requires control-api to be reachable. Run ` ++ '`make minikube-pf-control-ui` first, or set E2E_SKIP_IF_CLUSTER_UNREACHABLE=1 to skip.'+ )+}++// ─── mcp-secrets / mcp-servers HTTP contract ────────────────────────────────++export interface McpServerCondition {+ type: string+ status: 'True' | 'False' | 'Unknown'+ reason: string+ message: string+ lastTransitionTime: string+}++export interface McpServerResource {+ metadata: {+ name: string+ namespace: string+ resourceVersion?: string+ generation?: number+ }+ spec: Record<string, unknown>+ status?: { conditions?: McpServerCondition[] }+}++export interface McpSecretPutResponse {+ name: string+ namespace: string+ keys: string[]+ affectedConnectors: string[]+}++export async function putMcpSecret(+ name: string,+ data: Record<string, string>,+ session?: string+): Promise<{ status: number; data: McpSecretPutResponse | { error: string } }> {+ return putJson(+ `${CONTROL_API_URL}/api/v1/admin/mcp-secrets/${encodeURIComponent(name)}`,+ { data },+ session ? adminSessionHeader(session) : {}+ )+}++export async function getMcpServerResource(+ name: string,+ session: string+): Promise<McpServerResource> {+ const { status, data } = await fetchJson<McpServerResource>(+ `${CONTROL_API_URL}/api/v1/admin/mcp-servers/${encodeURIComponent(name)}`,+ { headers: adminSessionHeader(session) }+ )+ if (status !== 200) {+ throw new Error(+ `GET /admin/mcp-servers/${name} failed: status=${status} body=${JSON.stringify(data)}`+ )+ }+ return data+}++export function deploymentReadyCondition(+ resource: McpServerResource+): McpServerCondition | undefined {+ return resource.status?.conditions?.find(c => c.type === 'DeploymentReady')+}++/**+ * Poll GET /admin/mcp-servers/:name until DeploymentReady reaches+ * `expectStatus` with a `lastTransitionTime` strictly after `sinceMs`.+ *+ * The `sinceMs` correlation is load-bearing (plan Fase 3, requisito 6 /+ * hallazgo 1): without it, a condition left over from a PREVIOUS deploy would+ * satisfy the predicate instantly, before the rollout under test even began.+ */+export async function waitForRolloutCondition(+ name: string,+ token: string,+ opts: { expectStatus: 'True' | 'False'; sinceMs: number; timeoutMs: number }+): Promise<McpServerCondition> {+ return waitFor(+ `McpServer "${name}" DeploymentReady=${opts.expectStatus} with lastTransitionTime after ${new Date(+ opts.sinceMs+ ).toISOString()}`,+ async () => {+ const resource = await getMcpServerResource(name, token)+ const cond = deploymentReadyCondition(resource)+ if (!cond) return null+ const transitionMs = Date.parse(cond.lastTransitionTime)+ if (Number.isNaN(transitionMs) || transitionMs < opts.sinceMs) return null+ if (cond.status !== opts.expectStatus) return null+ return cond+ },+ opts.timeoutMs,+ {+ diagnostics: () =>+ clusterDiagnostics(MCP_SERVERS_NAMESPACE, [+ `get mcpserver ${name} -n ${MCP_SERVERS_NAMESPACE} -o yaml`,+ `describe deployment ${name} -n ${MCP_SERVERS_NAMESPACE}`,+ ]),+ }+ )+}++/**+ * E2's guardian: poll until the rollout reaches a TERMINAL failure+ * (`DeploymentReady=False`, `reason=RolloutIncomplete`) after `sinceMs`. If a+ * `True` transition after `sinceMs` is observed first, throws IMMEDIATELY —+ * that is the false-positive rollout this scenario exists to catch, and the+ * whole point is that the test must fail loudly on it, not eventually time+ * out on a stale expectation.+ */+export async function assertRolloutNeverSucceeds(+ name: string,+ token: string,+ sinceMs: number,+ timeoutMs: number+): Promise<McpServerCondition> {+ const start = Date.now()+ while (Date.now() - start < timeoutMs) {+ const resource = await getMcpServerResource(name, token)+ const cond = deploymentReadyCondition(resource)+ if (cond) {+ const transitionMs = Date.parse(cond.lastTransitionTime)+ if (!Number.isNaN(transitionMs) && transitionMs >= sinceMs) {+ if (cond.status === 'True') {+ throw new Error(+ `McpServer "${name}" reported DeploymentReady=True after rotating to a credential ` ++ `that must crash-loop the pod (${ROTATION_INVALID_SENTINEL}). This IS the false-positive ` ++ `rollout scenario E2 exists to catch — the system reported success on a broken rotation. ` ++ `Condition: ${JSON.stringify(cond)}`+ )+ }+ if (cond.reason === 'RolloutIncomplete') {+ return cond+ }+ }+ }+ await new Promise(r => setTimeout(r, 3_000))+ }+ throw new Error(+ `Timed out (${timeoutMs}ms) waiting for McpServer "${name}" to reach a terminal ` ++ `RolloutIncomplete failure after rotating to an invalid credential. Either the readiness ` ++ `poll never wrote a terminal condition to the CRD (composition bug — plan section 6, C1), or ` ++ `the rollout budget needs to be re-measured against this cluster.\n\n${clusterDiagnostics(+ MCP_SERVERS_NAMESPACE,+ [+ `get mcpserver ${name} -n ${MCP_SERVERS_NAMESPACE} -o yaml`,+ `describe deployment ${name} -n ${MCP_SERVERS_NAMESPACE}`,+ `get pods -l app=${name} -n ${MCP_SERVERS_NAMESPACE} -o wide`,+ ]+ )}`+ )+}++// ─── Secret content hash (C4) ───────────────────────────────────────────────++/**+ * Mirrors host-context-controller/src/utils.ts canonicalStringify EXACTLY:+ * sorted keys, JSON.stringify of [key, value] pairs. Any drift here would+ * silently defeat the C4 check (plan section 6): "no basta con que la+ * anotación cambió — hay que compararla con el hash real del Secret".+ */+export function canonicalStringify(obj: Record<string, unknown>): string {+ const sorted = Object.keys(obj).sort()+ return JSON.stringify(sorted.map(k => [k, obj[k]]))+}++/** sha256(canonicalStringify(secret.data)) — secret.data is base64, exactly as kubectl -o json returns it. */+export function secretDataHash(namespace: string, name: string): string {+ const secret = kubectlJson<{ data?: Record<string, string> }>(+ `get secret ${name} -n ${namespace}`+ )+ return createHash('sha256')+ .update(canonicalStringify(secret.data ?? {}))+ .digest('hex')+}++/**+ * Blocks until the Deployment's rollout completes (all updated replicas+ * available) or the timeout fires, via `kubectl rollout status`. This is a fact+ * of the Deployment object — independent of how any given HCC version writes+ * McpServer CRD status conditions. Use it when a test only needs the workload to+ * be settled (e.g. before snapshotting its generation), not the CRD condition:+ * a PRE-#204 baseline reconciler with startup-fleet coupling may take far longer+ * to publish DeploymentReady=True on the CRD than the pod takes to become+ * Available, so asserting the CRD condition there is both slow and brittle.+ * Throws (fail-loud) if the rollout does not complete within the timeout.+ */+export function waitForDeploymentRolloutComplete(+ namespace: string,+ deploymentName: string,+ timeoutSec = 120+): void {+ kubectl(`rollout status deployment/${deploymentName} -n ${namespace} --timeout=${timeoutSec}s`)+}++export function deploymentCredentialsRevisionAnnotation(+ namespace: string,+ deploymentName: string+): string | null {+ const value = kubectlSafe(+ `get deployment ${deploymentName} -n ${namespace} -o jsonpath='{.spec.template.metadata.annotations.clerum\\.io/credentials-revision}'`+ )+ // `kubectl -o jsonpath` of an ABSENT annotation prints an empty string, not an+ // error — so kubectlSafe returns "". An absent annotation is semantically+ // null (the revision was never written), which is what callers checking+ // "baseline never wrote it" assert against. A present annotation is always a+ // non-empty sha256, so this normalization never masks a real value.+ return value === '' ? null : value+}++// ─── CRD / Secret fixture builders ──────────────────────────────────────────++export function secretYaml(name: string, namespace: string, data: Record<string, string>): string {+ const stringDataLines = Object.entries(data)+ .map(([k, v]) => ` ${k}: ${JSON.stringify(v)}`)+ .join('\n')+ return `apiVersion: v1+kind: Secret+metadata:+ name: ${name}+ namespace: ${namespace}+type: Opaque+stringData:+${stringDataLines}+`+}++export function localMcpServerYaml(opts: {+ name: string+ namespace?: string+ image?: string+ envSecretName: string+ keys: Array<{ secretKey: string; envVar: string }>+}): string {+ const {+ name,+ namespace = MCP_SERVERS_NAMESPACE,+ image = MOCK_MCP_IMAGE,+ envSecretName,+ keys,+ } = opts+ const keyLines = keys+ .map(k => ` - secretKey: ${k.secretKey}\n envVar: ${k.envVar}`)+ .join('\n')+ return `apiVersion: clerum.io/v1alpha1+kind: McpServer+metadata:+ name: ${name}+ namespace: ${namespace}+spec:+ contextRef: ${TEST_CONTEXT_REF}+ description: "issue #223 credential-rotation E2E fixture"+ image: ${image}+ transport:+ type: streamableHttp+ url: http://${name}.${namespace}.svc.cluster.local:3000/mcp+ port: 3000+ healthCheck:+ port: 3001+ envSecret:+ name: ${envSecretName}+ keys:+${keyLines}+ enabled: true+`+}++export function remoteMcpServerYaml(opts: {+ name: string+ namespace?: string+ baseUrl: string+ envSecretName: string+ keys: Array<{ secretKey: string; envVar: string }>+ authHeaders: Array<{ header: string; valueTemplate: string }>+ transportPort?: number+}): string {+ const {+ name,+ namespace = MCP_SERVERS_NAMESPACE,+ baseUrl,+ envSecretName,+ keys,+ authHeaders,+ transportPort = 3000,+ } = opts+ const keyLines = keys+ .map(k => ` - secretKey: ${k.secretKey}\n envVar: ${k.envVar}`)+ .join('\n')+ const authHeaderLines = authHeaders+ .map(+ h => ` - header: ${h.header}\n valueTemplate: ${JSON.stringify(h.valueTemplate)}`+ )+ .join('\n')+ // The CRD requires every remote McpServer to declare at least one+ // egressBinding (mcpserver.yaml CEL rule: "Remote servers must declare at+ // least one egressBinding for egress NetworkPolicy"). Without it, admission+ // rejects the object before the HCC ever sees it. Derive the binding from the+ // real baseUrl so the generated NetworkPolicy actually permits the egress the+ // rotation test exercises, rather than hardcoding an unrelated host.+ const egressUrl = new URL(baseUrl)+ const egressDns = egressUrl.hostname+ const egressPort = Number(egressUrl.port) || (egressUrl.protocol === 'https:' ? 443 : 80)+ return `apiVersion: clerum.io/v1alpha1+kind: McpServer+metadata:+ name: ${name}+ namespace: ${namespace}+spec:+ contextRef: ${TEST_CONTEXT_REF}+ description: "issue #223 remote connector credential-rotation E2E fixture"+ image: placeholder-canonicalized-by-hcc+ transport:+ type: streamableHttp+ url: http://${name}.${namespace}.svc.cluster.local:${transportPort}/mcp+ port: ${transportPort}+ remote:+ baseUrl: ${baseUrl}+ authHeaders:+${authHeaderLines}+ egressBindings:+ - dns: ${egressDns}+ port: ${egressPort}+ protocol: TCP+ envSecret:+ name: ${envSecretName}+ keys:+${keyLines}+ enabled: true+`+}++// ─── Transient Service port-forward (E6) ────────────────────────────────────++/**+ * Opens a port-forward to `svc/<service>:<remotePort>` for the duration of+ * `fn`, then tears it down. Used to make a REAL HTTP request through a+ * connector's own Service — e.g. a remote connector's nginx egress proxy —+ * without adding it to the shared pf-all-stack.sh set. Fails loud (throws)+ * if the port-forward process exits before becoming ready, or never becomes+ * ready within `readyTimeoutMs`.+ */+export async function withServicePortForward<T>(+ namespace: string,+ service: string,+ remotePort: number,+ fn: (baseUrl: string) => Promise<T>,+ readyTimeoutMs = 20_000,+ // A connector's Service only publishes the transport port. To reach a port+ // the pod listens on but the Service does not expose — e.g. the mock's health+ // server on 3001 that serves /whoami-credential — forward to the Deployment+ // (which lands on the pod directly) instead of the Service.+ target: 'svc' | 'deploy' = 'svc'+): Promise<T> {+ const targetRef = `${target}/${service}`+ const localPort = 20_000 + Math.floor(Math.random() * 10_000)+ const child = spawn(+ 'kubectl',+ [+ '--context',+ KUBECTL_CONTEXT,+ '-n',+ namespace,+ 'port-forward',+ targetRef,+ `${localPort}:${remotePort}`,+ ],+ { stdio: ['ignore', 'pipe', 'pipe'] }+ )++ let ready = false+ let stderrBuf = ''+ let exited: { code: number | null; signal: NodeJS.Signals | null } | null = null+ child.stdout?.on('data', d => {+ if (d.toString().includes('Forwarding from')) ready = true+ })+ child.stderr?.on('data', d => {+ stderrBuf += d.toString()+ })+ child.on('exit', (code, signal) => {+ exited = { code, signal }+ })++ try {+ await waitFor(+ `port-forward ${targetRef}:${remotePort} in ${namespace} to become ready`,+ () => {+ if (exited) {+ const e = exited as { code: number | null; signal: NodeJS.Signals | null }+ throw new Error(+ `port-forward exited early (code=${e.code}, signal=${e.signal}): ${stderrBuf}`+ )+ }+ return ready ? 'ready' : null+ },+ readyTimeoutMs,+ { intervalMs: 250 }+ )+ return await fn(`http://127.0.0.1:${localPort}`)+ } finally {+ child.kill('SIGTERM')+ }+}++// ─── Cleanup ─────────────────────────────────────────────────────────────────++/** Best-effort teardown. Deliberately swallows errors — cleanup, not assertion. */+export function deleteMcpServerFixture(+ name: string,+ secretName: string,+ namespace = MCP_SERVERS_NAMESPACE+): void {+ kubectlSafe(`delete mcpserver ${name} -n ${namespace} --ignore-not-found --timeout=20s`)+ kubectlSafe(`delete secret ${secretName} -n ${namespace} --ignore-not-found --timeout=10s`)+}diff --git a/tests/e2e/package-lock.json b/tests/e2e/package-lock.jsonindex d1432aa50..325494e85 100644--- a/tests/e2e/package-lock.json+++ b/tests/e2e/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-e2e-tests",- "version": "0.1.52",+ "version": "0.1.53","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-e2e-tests",- "version": "0.1.52",+ "version": "0.1.53","devDependencies": {"@types/jsonwebtoken": "^9.0.10","@types/node": "^22.0.0",diff --git a/tests/e2e/package.json b/tests/e2e/package.jsonindex 5bd15e893..20427b6cb 100644--- a/tests/e2e/package.json+++ b/tests/e2e/package.json@@ -1,6 +1,6 @@{"name": "clerum-e2e-tests",- "version": "0.1.52",+ "version": "0.1.53","private": true,"type": "module","scripts": {