Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-ui): gate connector creation on ownership, not on status (R1-H1, R1-H2)
Jose Ramirez3c58b794d5dc
diff --git a/control-ui/app/mcp-servers/[name]/edit/page.tsx b/control-ui/app/mcp-servers/[name]/edit/page.tsxindex c0d80227e..eab363eba 100644--- a/control-ui/app/mcp-servers/[name]/edit/page.tsx+++ b/control-ui/app/mcp-servers/[name]/edit/page.tsx@@ -11,7 +11,10 @@ import { EgressEditor } from '@components/EgressEditor'import { IconCable } from '@components/Sidebar/icons'import { useToast } from '@components/Toast'import { UpdateConnectorCredentials } from '@components/UpdateConnectorCredentials'-import { resolveCredentialSurface } from '@components/UpdateConnectorCredentials/resolveCredentialSurface'+import {+ isRecipeOwned,+ resolveCredentialSurface,+} from '@components/UpdateConnectorCredentials/resolveCredentialSurface'import { CONTROL_ROUTES } from '@constants/routes'import { getMcpServer, updateMcpServer } from '@lib/api'import type { EgressBinding, EnvSecret, EnvSecretKeyMapping, McpServerResource } from '@lib/api'@@ -195,6 +198,11 @@ export default function EditMcpServerPage() {server.status?.conditions,server.spec as { managed?: boolean } | undefined)}+ // Ownership, passed separately from `surface` on purpose:+ // `surface` is derived from an observed condition and reads+ // 'rotate' whenever status is absent, Unknown or stale, so it+ // cannot gate the create path. This is the spec fact.+ recipeOwned={isRecipeOwned(server.spec as { managed?: boolean } | undefined)}/></div>) : null}diff --git a/control-ui/components/UpdateConnectorCredentials/index.tsx b/control-ui/components/UpdateConnectorCredentials/index.tsxindex a49721e65..7a1ded0d9 100644--- a/control-ui/components/UpdateConnectorCredentials/index.tsx+++ b/control-ui/components/UpdateConnectorCredentials/index.tsx@@ -83,6 +83,7 @@ export function UpdateConnectorCredentials({serverName,envSecret,surface = 'rotate',+ recipeOwned = false,}: UpdateConnectorCredentialsProps) {const { showToast } = useToast()const { confirm, confirmDialog } = useConfirmDialog()@@ -246,16 +247,25 @@ export function UpdateConnectorCredentials({}}, [phase, rotationCutoff, serverName])- // `secretCreated` gates BOTH set-mode sources, not just the `surface` prop.- // It latches the moment a create succeeds, and the Secret it created exists- // from then on — whether the form got here from a stale `surface` prop or- // from a rotate PUT that 404'd (`recreateRequired`). Leaving `recreateRequired`- // outside the guard made it a one-way latch: nothing resets it (resetToIdle- // does not), so after a successful recreate the form kept "set" copy, forced- // every key, and offered a confirm dialog promising to create a Secret that- // now exists.- const mode: 'set' | 'rotate' =- !secretCreated && (recreateRequired || surface === 'set') ? 'set' : 'rotate'+ // "The Secret is missing and this screen would have to create it." Two+ // sources feed it, and `secretCreated` gates BOTH — not just the `surface`+ // prop. That latch flips the moment a create succeeds, and the Secret it+ // created exists from then on, whether the form got here from a stale+ // `surface` prop or from a rotate PUT that 404'd (`recreateRequired`).+ // Leaving `recreateRequired` outside the guard made it a one-way latch:+ // nothing resets it (resetToIdle does not), so after a successful recreate+ // the form kept "set" copy, forced every key, and offered a confirm dialog+ // promising to create a Secret that now exists.+ const secretMissing = !secretCreated && (recreateRequired || surface === 'set')+ // Ownership is the can-create invariant, and it is NOT derived from the+ // observed condition — see the `recipeOwned` prop doc. A recipe-owned+ // connector reaches `secretMissing` only through the late PUT 404 (or a+ // caller handing it surface='set'), and neither may open the create form:+ // the Secret name belongs to the recipe, the POST route does not guard+ // ownership the way the PUT does, and HCC never rolls out a managed:false+ // connector, so the create would cross an ownership boundary AND never+ // converge. `mode` can therefore never be 'set' while `recipeOwned` is true.+ const mode: 'set' | 'rotate' = secretMissing && !recipeOwned ? 'set' : 'rotate'if (!envSecret) {return (@@ -272,7 +282,14 @@ export function UpdateConnectorCredentials({// belongs to the recipe (the PUT route guards recipe-owned Secrets, the POST// route does not), and HCC never creates a Deployment for managed:false, so a// create here would both cross an ownership boundary and never converge.- if (surface === 'recipe-owned') {+ //+ // Two ways in, and both must land here rather than on the create form:+ // - `surface === 'recipe-owned'`, resolved up front from an observed+ // SecretResolved=False/SecretNotFound condition; and+ // - `recipeOwned && secretMissing`, the LATE discovery — status was absent,+ // Unknown or stale, so the surface resolved to 'rotate' and only the+ // rotation PUT's 404 revealed the Secret is gone.+ if (surface === 'recipe-owned' || (recipeOwned && secretMissing)) {return (<FormSection title="Update credentials"><p className="cu-muted">diff --git a/control-ui/components/UpdateConnectorCredentials/types.ts b/control-ui/components/UpdateConnectorCredentials/types.tsindex 34d0ebb74..5c3c4ce3d 100644--- a/control-ui/components/UpdateConnectorCredentials/types.ts+++ b/control-ui/components/UpdateConnectorCredentials/types.ts@@ -19,8 +19,25 @@ export type UpdateConnectorCredentialsProps = {* Which credential surface to render, derived by resolveCredentialSurface()* from the McpServer's SecretResolved condition and spec.managed. Optional* and defaulting to 'rotate' so existing call sites keep today's behavior.+ *+ * OBSERVED state, not ownership: absent, Unknown or stale status yields+ * 'rotate' for recipe-owned connectors too. Never gate the create path on+ * this — use `recipeOwned`.*/surface?: CredentialSurface+ /**+ * Whether the connector is WorkflowRecipe-owned (`spec.managed === false`),+ * threaded from the page via isRecipeOwned().+ *+ * This is the can-create invariant, and it is deliberately independent of+ * `surface`. A recipe-owned connector with no status yet resolves to+ * 'rotate', and the rotation PUT's own 404 is the first evidence its Secret+ * is missing — the exact moment the create form must NOT appear. When this is+ * true, `mode` can never become 'set' by any path, and every "the Secret is+ * missing" transition lands on the explanation that points at the recipe's+ * secrets instead.+ */+ recipeOwned?: boolean}/**diff --git a/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx b/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsxnew file mode 100644index 000000000..0ec76f0b2--- /dev/null+++ b/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx@@ -0,0 +1,278 @@+import React from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import { ToastProvider } from '@components/Toast'+import EditMcpServerPage from '../../app/mcp-servers/[name]/edit/page'+import { createMcpSecret, getMcpServer, getMcpServers, updateMcpSecret } from '../../lib/api'+import type { McpServerCondition, McpServerResource } from '../../lib/api'++// ─── R1-H2: drive the REAL page, not the component in isolation ────────────+//+// The component tests inject `surface`/`recipeOwned` directly and the resolver+// tests call the resolver directly, so NEITHER covers the wiring in between.+// The reviewer reproduced that gap twice: deleting the page's `surface` prop+// left both changed suites 36/36 green, and resolving only the first condition+// left the resolver suite 8/8 green. These tests close it by rendering the edit+// page against a producer-shaped getMcpServer() response and asserting the UI+// an operator would actually see.+//+// Nothing here passes `surface` or `recipeOwned` by hand — the page must derive+// both from the McpServer it loaded.++const SERVER_NAME = 'linear-connector'+const SECRET_NAME = 'linear-credentials'++const navigation = vi.hoisted(() => ({+ params: { name: 'linear-connector' },+ push: vi.fn(),+}))++vi.mock('next/navigation', () => ({+ useParams: () => navigation.params,+ useRouter: () => ({ push: navigation.push }),+}))++vi.mock('@components/AuthGate', () => ({+ AuthGate: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}))++vi.mock('@components/DashboardLayout', () => ({+ DashboardLayout: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}))++vi.mock('../../lib/api', async () => {+ const actual = await vi.importActual<typeof import('../../lib/api')>('../../lib/api')+ return {+ ...actual,+ getMcpServer: vi.fn(),+ getMcpServers: vi.fn(),+ updateMcpServer: vi.fn(),+ updateMcpSecret: vi.fn(),+ createMcpSecret: vi.fn(),+ }+})++const mockGetMcpServer = vi.mocked(getMcpServer)+const mockGetMcpServers = vi.mocked(getMcpServers)+const mockUpdateMcpSecret = vi.mocked(updateMcpSecret)+const mockCreateMcpSecret = vi.mocked(createMcpSecret)++/** A SecretResolved condition in the shape HCC writes it. */+function secretResolved(+ overrides: Partial<McpServerCondition> & { lastTransitionTime: string }+): McpServerCondition {+ return {+ type: 'SecretResolved',+ status: 'False',+ reason: 'SecretNotFound',+ message: `Secret "${SECRET_NAME}" not found in namespace "mcp-server"`,+ ...overrides,+ }+}++/**+ * The producer: an McpServer as `GET /admin/mcp-servers/:name` returns it,+ * including the `spec.envSecret` the page has to narrow and the+ * `status.conditions` array the resolver has to reduce.+ */+function mcpServer(options: {+ managed?: boolean+ conditions?: McpServerCondition[]+}): McpServerResource {+ return {+ metadata: { name: SERVER_NAME, namespace: 'mcp-server' },+ spec: {+ image: 'ghcr.io/acme/linear-mcp:1.4.0',+ contextRef: 'default',+ ...(options.managed === undefined ? {} : { managed: options.managed }),+ envSecret: {+ name: SECRET_NAME,+ keys: [+ { secretKey: 'api-key', envVar: 'LINEAR_API_KEY' },+ { secretKey: 'workspace-id', envVar: 'LINEAR_WORKSPACE' },+ ],+ },+ },+ status: { conditions: options.conditions ?? [] },+ }+}++/** Renders the page and waits for its initial getMcpServer() to settle. */+async function renderPage(server: McpServerResource) {+ mockGetMcpServer.mockResolvedValue(server)+ render(+ <ToastProvider>+ <EditMcpServerPage />+ </ToastProvider>+ )+ // Anchor on the loaded connector's own image: it renders only after+ // getMcpServer() resolves, and it is surface-independent (the credential+ // panel's own title changes between set/rotate/recipe-owned).+ await screen.findByText('ghcr.io/acme/linear-mcp:1.4.0')+}++beforeEach(() => {+ mockGetMcpServers.mockResolvedValue({ items: [] })+})++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++describe('EditMcpServerPage — credential surface wiring', () => {+ it('renders the CREATE form when a managed connector reports SecretNotFound', async () => {+ await renderPage(+ mcpServer({+ managed: true,+ conditions: [secretResolved({ lastTransitionTime: '2026-08-06T04:00:00.000Z' })],+ })+ )++ expect(screen.getByText(/needs credentials before it can start/i)).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Rotate credentials' })).not.toBeInTheDocument()+ })++ // SecretMissingKey means the Secret EXISTS but lacks a declared key, which the+ // PUT merge-patch already adds. Sending it to the create form would POST into+ // an AlreadyExists that control-api collapses to a bare 500.+ it('keeps the ROTATE form when the connector reports SecretMissingKey', async () => {+ await renderPage(+ mcpServer({+ managed: true,+ conditions: [+ secretResolved({+ reason: 'SecretMissingKey',+ message: `Secret "${SECRET_NAME}" is missing key "workspace-id"`,+ lastTransitionTime: '2026-08-06T04:00:00.000Z',+ }),+ ],+ })+ )++ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()+ expect(screen.getByText(/Rotate values stored in Secret/i)).toBeInTheDocument()+ })++ it('renders the recipe explanation, and no form, for an unmanaged connector with a missing Secret', async () => {+ await renderPage(+ mcpServer({+ managed: false,+ conditions: [secretResolved({ lastTransitionTime: '2026-08-06T04:00:00.000Z' })],+ })+ )++ expect(screen.getByText(/managed by its WorkflowRecipe/i)).toBeInTheDocument()+ expect(screen.queryByLabelText('api-key')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Rotate credentials' })).not.toBeInTheDocument()+ })++ // A real status array carries several condition types and no ordering+ // guarantee. Only the newest SecretResolved entry may decide the surface.+ it('ignores unrelated conditions and honors the NEWEST SecretResolved entry', async () => {+ await renderPage(+ mcpServer({+ managed: true,+ conditions: [+ {+ type: 'DeploymentReady',+ status: 'False',+ reason: 'SecretNotFound',+ message: 'unrelated condition reusing the reason',+ lastTransitionTime: '2026-08-06T09:00:00.000Z',+ },+ secretResolved({ lastTransitionTime: '2026-08-06T04:00:00.000Z' }),+ secretResolved({+ status: 'True',+ reason: 'SecretResolved',+ message: `Secret "${SECRET_NAME}" resolved`,+ lastTransitionTime: '2026-08-06T05:00:00.000Z',+ }),+ ],+ })+ )++ // The stale SecretNotFound and the DeploymentReady noise must both lose.+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()+ })++ it('honors a NEWER SecretNotFound over a stale clean resolution', async () => {+ await renderPage(+ mcpServer({+ managed: true,+ conditions: [+ secretResolved({+ status: 'True',+ reason: 'SecretResolved',+ message: `Secret "${SECRET_NAME}" resolved`,+ lastTransitionTime: '2026-08-06T04:00:00.000Z',+ }),+ secretResolved({ lastTransitionTime: '2026-08-06T05:00:00.000Z' }),+ ],+ })+ )++ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()+ })+})++// ─── R1-H1, end to end through the page ────────────────────────────────────+describe('EditMcpServerPage — late 404 on an unmanaged connector', () => {+ it('never exposes the create form when the rotation PUT 404s and status was absent', async () => {+ // The realistic race: the connector was just created, HCC has not written+ // status yet, so NOTHING observable says the Secret is missing and the+ // resolver can only answer 'rotate'. Ownership must come from the spec.+ await renderPage(mcpServer({ managed: false, conditions: [] }))++ // It starts as a normal rotate form — that part is unchanged.+ const rotate = screen.getByRole('button', { name: 'Rotate credentials' })+ mockUpdateMcpSecret.mockRejectedValue(+ Object.assign(new Error(`404 - Secret "${SECRET_NAME}" not found in mcp-server`), {+ status: 404,+ })+ )++ fireEvent.change(screen.getByLabelText('api-key'), { target: { value: 'partial-value' } })+ fireEvent.click(rotate)+ const dialog = await screen.findByRole('alertdialog')+ fireEvent.click(within(dialog).getByRole('button', { name: 'Rotate & restart' }))++ await waitFor(() => {+ expect(screen.getByText(/managed by its WorkflowRecipe/i)).toBeInTheDocument()+ })+ // Explanation-only: no create form, no partial POST, and no copy telling the+ // operator to re-enter every key on a screen that cannot create anything.+ expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()+ expect(screen.queryByLabelText('api-key')).not.toBeInTheDocument()+ expect(screen.queryByText(/Enter every key to recreate it/)).not.toBeInTheDocument()+ expect(mockCreateMcpSecret).not.toHaveBeenCalled()+ })++ // The managed control for the same race: the recovery this screen exists to+ // provide must survive the ownership guard.+ it('does open the create form on the same 404 when the connector is managed', async () => {+ await renderPage(mcpServer({ managed: true, conditions: [] }))++ mockUpdateMcpSecret.mockRejectedValue(+ Object.assign(new Error(`404 - Secret "${SECRET_NAME}" not found in mcp-server`), {+ status: 404,+ })+ )++ fireEvent.change(screen.getByLabelText('api-key'), { target: { value: 'partial-value' } })+ fireEvent.click(screen.getByRole('button', { name: 'Rotate credentials' }))+ const dialog = await screen.findByRole('alertdialog')+ fireEvent.click(within(dialog).getByRole('button', { name: 'Rotate & restart' }))++ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()+ })+ expect(screen.getByText(/This Secret no longer exists\./)).toBeInTheDocument()+ expect(screen.queryByText(/managed by its WorkflowRecipe/i)).not.toBeInTheDocument()+ expect(mockCreateMcpSecret).not.toHaveBeenCalled()+ })+})diff --git a/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx b/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsxindex 2f2c3c24d..954510209 100644--- a/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx+++ b/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx@@ -81,7 +81,8 @@ async function flush(ticks = 4) {// always pass explicitly.async function renderPanel(envSecret: EnvSecret | undefined,- surface: CredentialSurface = 'rotate'+ surface: CredentialSurface = 'rotate',+ recipeOwned = false) {const utils = render(<ToastProvider>@@ -89,6 +90,7 @@ async function renderPanel(serverName={SERVER_NAME}envSecret={envSecret}surface={surface}+ recipeOwned={recipeOwned}/></ToastProvider>)@@ -775,6 +777,70 @@ describe('UpdateConnectorCredentials — recipe-owned', () => {})})+// ─── R1-H1: ownership must not depend on the observed condition ────────────+//+// `surface` is derived from status. A managed:false connector whose status is+// absent, Unknown, or stale carries NO SecretNotFound condition, so it resolves+// to `rotate` — and the PUT's own 404 is then the FIRST evidence the Secret is+// missing. If that 404 were allowed to open the create form, the ownership+// guard would be defeated exactly when it matters: the operator would POST an+// unlabeled Secret outside the WorkflowRecipe flow, collide with the recipe's+// later provisioning, and then wait forever for an HCC rollout that+// managed:false connectors never receive.+//+// `recipeOwned` is therefore threaded from the page as an ownership FACT+// (spec.managed === false), independent of any condition.+describe('UpdateConnectorCredentials — recipe-owned, late 404', () => {+ it('lands on explanation-only when a rotate PUT 404s on a recipe-owned connector', async () => {+ mockUpdateMcpSecret.mockRejectedValue(+ Object.assign(new Error('404 - Secret "linear-credentials" not found in mcp-server'), {+ status: 404,+ })+ )+ // Status has not been written yet, so the resolver can only say 'rotate'.+ await renderPanel(ENV_SECRET, 'rotate', true)+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()++ await submitRotation({ 'api-key': 'only-one' })++ // The 404 must point at the recipe, not at a create form.+ expect(screen.getByText(/managed by its WorkflowRecipe/i)).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Rotate credentials' })).not.toBeInTheDocument()+ expect(screen.queryByLabelText('api-key')).not.toBeInTheDocument()+ expect(screen.queryByText(/Enter every key to recreate it/)).not.toBeInTheDocument()+ expect(mockCreateMcpSecret).not.toHaveBeenCalled()+ })++ // Defense in depth: even if a caller (or a future resolver change) handed+ // this component `surface: 'set'` for a recipe-owned connector, POST must+ // stay unreachable. `mode` may never resolve to 'set' by ANY path.+ it('never renders the create form for a recipe-owned connector handed surface="set"', async () => {+ await renderPanel(ENV_SECRET, 'set', true)++ expect(screen.getByText(/managed by its WorkflowRecipe/i)).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()+ expect(screen.queryByText(/needs credentials before it can start/i)).not.toBeInTheDocument()+ expect(screen.queryByLabelText('api-key')).not.toBeInTheDocument()+ })++ // The managed:TRUE control for the same journey — the recovery this screen+ // exists to provide must keep working, so the guard above cannot be a blanket+ // "never recover from a 404".+ it('still opens the create form on a late 404 for a managed connector', async () => {+ mockUpdateMcpSecret.mockRejectedValue(+ Object.assign(new Error('404 - Secret "linear-credentials" not found in mcp-server'), {+ status: 404,+ })+ )+ await renderPanel(ENV_SECRET, 'rotate', false)+ await submitRotation({ 'api-key': 'only-one' })++ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()+ expect(screen.queryByText(/managed by its WorkflowRecipe/i)).not.toBeInTheDocument()+ })+})+describe('UpdateConnectorCredentials — set mode', () => {it('renders set-mode copy instead of rotation copy', async () => {await renderPanel(ENV_SECRET, 'set')diff --git a/control-ui/next-env.d.ts b/control-ui/next-env.d.tsindex 9edff1c7c..c4b7818fb 100644--- a/control-ui/next-env.d.ts+++ b/control-ui/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/types/routes.d.ts";+import "./.next/dev/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex ba2acd63f..9162cc278 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.396",+ "version": "0.1.397","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.396",+ "version": "0.1.397","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 cd30c73a1..969659ed6 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.396",+ "version": "0.1.397","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",