Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

chore: sync dev into connector credentials

Jose Ramirez78f528093e3e
diff --cc README.md
index 1bb1ac4a5,34f36d5fa..23dec3f5a
--- a/README.md
+++ b/README.md
@@@ -37,8 -37,12 +37,12 @@@
## Quick start
- Stand up the whole platform on a local cluster with one command. It brings up
- every service and a seeded agent named `chatllm`:
-> **This quick start runs the whole platform on a local [minikube](https://minikube.sigs.k8s.io/) cluster** — the fastest way to try Evenfire on your workstation.
++> **This quick start runs the whole platform on a local [minikube](https://minikube.sigs.k8s.io/) cluster** — the fastest way to try Evenfire on your workstation.
+
+ Stand up every service on minikube with one command, including a seeded agent
+ named `chatllm`. On a fresh minimal install, setup consumes the first-run
+ admin bootstrap before any login, creates the matching Desktop identity, and
+ records the governed `initial_setup` GFS operator link atomically:
```bash
git clone https://github.com/evenfire-ai/evenfire.git && cd evenfire
diff --cc control-ui/app/mcp-servers/[name]/edit/page.tsx
index eab363eba,507073b23..40397b1af
--- a/control-ui/app/mcp-servers/[name]/edit/page.tsx
+++ b/control-ui/app/mcp-servers/[name]/edit/page.tsx
@@@ -9,15 -9,37 +9,41 @@@ import { CreatePageHeader } from '@comp
import { DashboardLayout } from '@components/DashboardLayout'
import { EgressEditor } from '@components/EgressEditor'
import { IconCable } from '@components/Sidebar/icons'
+ import { TabBar } from '@components/TabBar'
import { useToast } from '@components/Toast'
import { UpdateConnectorCredentials } from '@components/UpdateConnectorCredentials'
+import {
+ isRecipeOwned,
+ resolveCredentialSurface,
+} from '@components/UpdateConnectorCredentials/resolveCredentialSurface'
+ import {
+ CONNECTOR_EDIT_DEFAULT_TAB,
+ CONNECTOR_EDIT_TABS,
+ CONNECTOR_EDIT_TAB_LABELS,
+ type ConnectorEditTab,
+ } from '@constants/connectorEdit'
import { CONTROL_ROUTES } from '@constants/routes'
- import { getMcpServer, updateMcpServer } from '@lib/api'
- import type { EgressBinding, EnvSecret, EnvSecretKeyMapping, McpServerResource } from '@lib/api'
+ import { getAgentDisplayName } from '@lib/agentName'
+ import {
+ getContextTeams,
+ getContextUsers,
+ getContexts,
+ getHosts,
+ getMcpServer,
+ updateMcpServer,
+ } from '@lib/api'
+ import type {
+ ContextResource,
+ EgressBinding,
+ EnvSecret,
+ EnvSecretKeyMapping,
+ McpServerResource,
+ } from '@lib/api'
+ import {
+ contextNamesForConnector,
+ mergeAccessSummaries,
+ sortAccessPrincipals,
+ } from '@lib/connectorAccess'
import type { EgressEditorStatus } from '@lib/egressModel'
/**
@@@ -128,22 -311,134 +315,140 @@@ export default function EditMcpServerPa
/>
}
>
+ <TabBar<ConnectorEditTab>
+ ariaLabel="Connector edit sections"
+ activeValue={activeTab}
+ className="cu-tabs--compact cu-connector-edit-tabs"
+ onChange={selectTab}
+ options={CONNECTOR_EDIT_TABS.map(tab => ({
+ value: tab,
+ label: CONNECTOR_EDIT_TAB_LABELS[tab],
+ href:
+ tab === CONNECTOR_EDIT_DEFAULT_TAB
+ ? CONTROL_ROUTES.connectors.edit(name)
+ : CONTROL_ROUTES.connectors.editTab(name, tab),
+ }))}
+ />
+
+ {loadError ? <div className="cu-banner cu-banner--error">{loadError}</div> : null}
+
{loading ? (
- <FormSectionsSkeleton
- className="cu-connector-edit-form"
- label="Connector"
- primaryActionLabel="Save egress"
- sections={3}
- />
- ) : loadError ? (
- <div className="cu-connector-edit-form">
- <div className="cu-banner cu-banner--error" role="alert">
- {loadError}
+ activeTab === 'credentials' ? (
+ <div
+ role="status"
+ aria-busy="true"
+ aria-label="Loading connector credentials"
+ className="cu-connector-edit-form cu-body-loading-skeleton"
+ >
+ <section className="cu-body-loading-skeleton__section">
+ <span className="cu-skeleton cu-body-loading-skeleton__heading" />
+ <span className="cu-skeleton cu-body-loading-skeleton__line" />
+ <div className="cu-body-loading-skeleton__fields">
+ <span className="cu-skeleton cu-body-loading-skeleton__field" />
+ <span className="cu-skeleton cu-body-loading-skeleton__field" />
+ </div>
+ </section>
</div>
- </div>
+ ) : (
+ <div className="cu-connector-edit-form">
+ <FormSectionsSkeleton
+ label="Connector"
+ primaryActionLabel="Save egress"
+ sections={2}
+ />
+ </div>
+ )
) : server ? (
- <div className="cu-connector-edit-form">
- <form className="cu-create-content cu-connector-edit-content" onSubmit={handleSave}>
+ activeTab === 'credentials' ? (
+ <div className="cu-connector-edit-form">
+ <UpdateConnectorCredentials
+ serverName={name}
+ envSecret={envSecret}
+ registryCredentialSource={registryCredentialSource}
++ surface={resolveCredentialSurface(
++ server.status?.conditions,
++ server.spec as { managed?: boolean } | undefined
++ )}
++ // Ownership is a spec fact, independent of observed status.
++ recipeOwned={isRecipeOwned(server.spec as { managed?: boolean } | undefined)}
+ />
+ </div>
+ ) : activeTab === 'context' ? (
+ <div className="cu-connector-edit-form cu-connector-edit-content">
+ <section className="cu-form-section" aria-labelledby="connector-context-title">
+ <div className="cu-form-section__header">
+ <h2 id="connector-context-title" className="cu-form-section__title">
+ Context access
+ </h2>
+ <p className="cu-form-section__description">
+ This connector is available in the contexts shown below. Context assignments
+ are derived from the current Context allowlists and cannot be changed here
+ yet.
+ </p>
+ </div>
+
+ {loadingContexts ? (
+ <p className="cu-muted" role="status">
+ Loading contexts…
+ </p>
+ ) : contextListError ? (
+ <div className="cu-banner cu-banner--warn" role="alert">
+ {contextListError}
+ </div>
+ ) : (
+ <p className="cu-connector-edit-context-name" aria-label="Connector contexts">
+ Contexts:{' '}
+ <strong>{contextNames.length > 0 ? contextNames.join(', ') : 'None'}</strong>
+ </p>
+ )}
+
+ {!loadingContexts && !contextListError && contextNames.length > 0 ? (
+ loadingContextAccess ? (
+ <p className="cu-muted">Loading context access…</p>
+ ) : (
+ <>
+ {contextAccessError ? (
+ <p className="cu-banner cu-banner--warn" role="status">
+ {contextAccessError}
+ </p>
+ ) : null}
+ <section className="cu-registry-context-access" aria-label="Context access">
+ {CONTEXT_ACCESS_GROUPS.map(group => (
+ <section
+ className="cu-registry-context-access__group"
+ data-kind={group.key}
+ key={group.key}
+ >
+ <div className="cu-registry-context-access__heading">
+ <h4>{group.title}</h4>
+ <span>{contextAccess[group.key].length}</span>
+ </div>
+ {contextAccess[group.key].length > 0 ? (
+ <ul className="cu-registry-context-access__list">
+ {contextAccess[group.key].map(principal => (
+ <li key={principal.id}>
+ <span>{principal.label}</span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="cu-muted">
+ No {group.title.toLowerCase()} have access.
+ </p>
+ )}
+ </section>
+ ))}
+ </section>
+ </>
+ )
+ ) : null}
+ </section>
+ </div>
+ ) : (
+ <form
+ className="cu-connector-edit-form cu-connector-edit-content"
+ onSubmit={handleSave}
+ >
<div className="cu-connector-edit-meta">
<div>
<strong>Image:</strong>{' '}
diff --cc control-ui/components/UpdateConnectorCredentials/index.tsx
index 94157d68d,9b5a0d032..5ae16d0f9
--- a/control-ui/components/UpdateConnectorCredentials/index.tsx
+++ b/control-ui/components/UpdateConnectorCredentials/index.tsx
@@@ -4,7 -4,7 +4,13 @@@ import React, { useEffect, useRef, useS
import { useConfirmDialog } from '@components/ConfirmDialog'
import { useToast } from '@components/Toast'
import { Button, Field, FormSection, TextInput } from '@components/ui'
- import { createMcpSecret, getMcpServer, getMcpServers, updateMcpSecret } from '@lib/api'
-import { getMcpServer, getMcpServers, getRegistryCredentialSchema, updateMcpSecret } from '@lib/api'
++import {
++ createMcpSecret,
++ getMcpServer,
++ getMcpServers,
++ getRegistryCredentialSchema,
++ updateMcpSecret,
++} from '@lib/api'
import type { McpServerCondition } from '@lib/api'
import type { RotationPhase, UpdateConnectorCredentialsProps } from './types'
@@@ -121,8 -82,7 +127,9 @@@ function findFreshDeploymentReady
export function UpdateConnectorCredentials({
serverName,
envSecret,
+ surface = 'rotate',
+ recipeOwned = false,
+ registryCredentialSource,
}: UpdateConnectorCredentialsProps) {
const { showToast } = useToast()
const { confirm, confirmDialog } = useConfirmDialog()
@@@ -145,20 -100,7 +152,24 @@@
const [phaseMessage, setPhaseMessage] = useState('')
const [rotationCutoff, setRotationCutoff] = useState<string | null>(null)
const [rotationAffected, setRotationAffected] = useState<string[]>([])
- const [credentialLabels, setCredentialLabels] = useState<Record<string, string>>({})
++ // Labels use the same Kubernetes-valid key namespace as drafts. Keep this
++ // map prototype-safe as well, because Marketplace schemas may contain keys
++ // such as `constructor` or `__proto__`.
++ const [credentialLabels, setCredentialLabels] = useState<CredentialMap>(emptyCredentialMap)
+ // Latches the form onto rotate semantics after a successful create, so a
+ // stale `surface` prop cannot leave "set" copy on a Secret that now exists.
+ const [secretCreated, setSecretCreated] = useState(false)
+ // Latches the form onto set semantics when a rotate PUT 404s (Task 5).
+ const [recreateRequired, setRecreateRequired] = useState(false)
+ // Which operation is actually in flight / just completed. Captured at submit
+ // time and used for the in-flight and success banners.
+ //
+ // This CANNOT be derived from `mode`: setSecretCreated(true) flips `mode` to
+ // 'rotate' the instant a create succeeds, so a banner reading `mode` would
+ // announce "Credentials rotated" immediately after a create. The latch and
+ // the banner answer different questions — "what should the form do next?"
+ // versus "what did we just do?" — so they need separate state.
+ const [submittedMode, setSubmittedMode] = useState<'set' | 'rotate'>('rotate')
// The HCC's most recent RolloutIncomplete diagnostic, kept across polls (a
// ref, not state: it only matters at the timeout boundary, so it must not
// re-render or re-fire the poll effect). Seeing RolloutIncomplete never
@@@ -195,6 -137,32 +206,32 @@@
}
}, [envSecret])
+ useEffect(() => {
+ if (!registryCredentialSource) {
- setCredentialLabels({})
++ setCredentialLabels(emptyCredentialMap())
+ return
+ }
+
+ let cancelled = false
+ void getRegistryCredentialSchema(
+ registryCredentialSource.name,
+ registryCredentialSource.version
+ )
+ .then(schema => {
+ if (cancelled) return
- setCredentialLabels(
- Object.fromEntries(schema.keys.map(key => [key.name, key.label || key.name]))
- )
++ const labels = emptyCredentialMap()
++ for (const key of schema.keys) labels[key.name] = key.label || key.name
++ setCredentialLabels(labels)
+ })
+ .catch(() => {
- if (!cancelled) setCredentialLabels({})
++ if (!cancelled) setCredentialLabels(emptyCredentialMap())
+ })
+
+ return () => {
+ cancelled = true
+ }
+ }, [registryCredentialSource])
+
// 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).
@@@ -547,107 -357,81 +584,111 @@@
>
{confirmDialog}
- <form className="cu-connector-credentials-form" onSubmit={handleSubmit}>
- <div className="cu-form-stack">
- <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>
-
- {envSecret.keys.map(k => (
+ <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>
+
+ {/* `noValidate`: the browser's own required-field bubble would fire
+ before handleSubmit and replace the aggregate message that actually
+ NAMES the missing keys. The `required` attributes below are kept for
+ their programmatic semantics (assistive technology reads the required
+ state regardless of novalidate); the enforcement stays ours. */}
- <form className="cu-form-stack" onSubmit={handleSubmit} noValidate>
++ <form
++ className="cu-connector-credentials-form cu-form-stack"
++ onSubmit={handleSubmit}
++ noValidate
++ >
+ {envSecret.keys.map(k => {
+ const isInvalid = invalidKeys.includes(k.secretKey)
+ return (
<Field
key={k.secretKey}
- htmlFor={`mcp-cred-${k.secretKey}`}
- label={credentialLabels[k.secretKey] || k.secretKey}
+ htmlFor={inputId(k.secretKey)}
- label={k.secretKey}
++ label={ownCredentialValue(credentialLabels, k.secretKey) ?? k.secretKey}
+ required={mode === 'set'}
>
<TextInput
- id={`mcp-cred-${k.secretKey}`}
+ id={inputId(k.secretKey)}
type="password"
autoComplete="new-password"
- placeholder="Leave blank to keep current value"
- value={draft[k.secretKey] || ''}
+ placeholder={mode === 'set' ? 'Required' : 'Leave blank to keep current value'}
+ value={ownCredentialValue(draft, k.secretKey) ?? ''}
onChange={e => updateField(k.secretKey, e.target.value)}
disabled={busy}
+ // Set mode creates the Secret in one shot: HCC answers
+ // SecretMissingKey for any key left out, so every declared key
+ // really is mandatory. In rotate mode a blank field means
+ // "keep the current value", and marking it required would be a
+ // lie the screen reader would repeat on every field.
+ required={mode === 'set'}
+ aria-required={mode === 'set' || undefined}
+ invalid={isInvalid}
+ aria-invalid={isInvalid || undefined}
+ aria-describedby={isInvalid ? VALIDATION_ERROR_ID : undefined}
/>
</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 {serverName} to restart with the new value.
- {phaseMessage ? ` ${phaseMessage}` : ''}
- </div>
- ) : null}
-
- {phase === 'success' ? (
- <div className="cu-banner cu-banner--ok" role="status">
- Credentials rotated. {serverName} restarted and is serving the new credential.
- {otherAffectedNote}
- </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>
+ )
+ })}
+
+ {validationError ? (
+ <div className="cu-banner cu-banner--error" role="alert" id={VALIDATION_ERROR_ID}>
+ {validationError}
+ </div>
+ ) : null}
+
+ {phase === 'rotating' ? (
+ <div className="cu-banner cu-banner--info" role="status">
+ {submittedMode === 'set'
+ ? `Setting credentials — waiting for ${serverName} to start.`
+ : `Rotating credentials — waiting for ${serverName} to restart with the new value.`}
+ {phaseMessage ? ` ${phaseMessage}` : ''}
+ </div>
+ ) : null}
+
+ {phase === 'success' ? (
+ <div className="cu-banner cu-banner--ok" role="status">
+ {submittedMode === 'set'
+ ? `Credentials set. ${serverName} started and is serving the new credential.`
+ : `Credentials rotated. ${serverName} restarted and is serving the new credential.`}
+ {otherAffectedNote}
+ </div>
+ ) : null}
+
+ {phase === 'failed' ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ {submittedMode === 'set'
+ ? `Could not set credentials: ${phaseMessage}`
+ : `Rotation failed: ${phaseMessage}`}
+ </div>
+ ) : null}
+
+ {phase === 'timeout' ? (
+ <div className="cu-banner cu-banner--warning" role="alert">
+ {phaseMessage}{' '}
+ {submittedMode === 'set'
+ ? 'You can also try setting the credentials again.'
+ : 'You can also try the rotation again.'}
+ </div>
+ ) : null}
<div className="cu-create-actions">
{phase === 'success' || phase === 'failed' || phase === 'timeout' ? (
diff --cc control-ui/components/UpdateConnectorCredentials/types.ts
index 5c3c4ce3d,e85854edb..e5a2f9933
--- a/control-ui/components/UpdateConnectorCredentials/types.ts
+++ b/control-ui/components/UpdateConnectorCredentials/types.ts
@@@ -1,6 -1,10 +1,11 @@@
import type { EnvSecret } from '../../lib/api'
+import type { CredentialSurface } from './resolveCredentialSurface'
+ export type RegistryCredentialSource = {
+ name: string
+ version: string
+ }
+
export type UpdateConnectorCredentialsProps = {
/**
* McpServer CRD name — the connector currently being edited. Also the
@@@ -16,28 -20,11 +21,30 @@@
*/
envSecret: EnvSecret | undefined
/**
- * Marketplace source retained on the connector CRD. When present, its
- * credential schema supplies operator-friendly field names while secret
- * keys remain the stable write-only data identifiers.
+ * 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
++ /** Marketplace source used to resolve operator-friendly credential labels. */
+ registryCredentialSource?: RegistryCredentialSource
}
/**
diff --cc control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
index 46c7bfb79,000000000..58ea7cb59
mode 100644,000000..100644
--- a/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
+++ b/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
@@@ -1,418 -1,0 +1,428 @@@
+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 {
++ createMcpSecret,
++ getContexts,
++ getMcpServer,
++ getMcpServers,
++ updateMcpSecret,
++} from '../../lib/api'
+import type { McpServerCondition, McpServerResource } from '../../lib/api'
+import {
+ secretFound,
+ secretMissingKey,
+ secretNotFound,
+ syntheticCondition,
+} from './fixtures/secretResolvedConditions'
+
+// ─── 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 three times: deleting the page's `surface`
+// prop left both changed suites green, resolving only the first condition left
+// the resolver suite green, and — round 2 — coupling the page's `recipeOwned`
+// to `status.conditions.length === 0` left all 69 changed tests green.
+//
+// These tests close it by rendering the edit page against producer-shaped
+// getMcpServer() responses 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 — and every condition comes from the shared
+// producer builder (./fixtures/secretResolvedConditions), so a drift in the HCC
+// is a one-place fix rather than a hunt through hand-written literals.
+
+const SERVER_NAME = 'linear-connector'
+const SECRET_NAME = 'linear-credentials'
+const NAMESPACE = 'mcp-server'
+
+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,
++ getContexts: vi.fn(),
+ 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 mockGetContexts = vi.mocked(getContexts)
+const mockUpdateMcpSecret = vi.mocked(updateMcpSecret)
+const mockCreateMcpSecret = vi.mocked(createMcpSecret)
+
+const CONNECTOR_IMAGE = 'ghcr.io/acme/linear-mcp:1.4.0'
+
+/**
+ * An McpServer as `GET /admin/mcp-servers/:name` returns it, including the
+ * `spec.envSecret` the page has to narrow and the `status` the resolver has to
+ * reduce.
+ *
+ * `status` is passed through EXACTLY as given, including `undefined`: the
+ * connector-just-created race leaves the subresource absent altogether, which
+ * is a different shape from `{ conditions: [] }` and has to be testable as one.
+ */
+function mcpServer(options: {
+ managed?: boolean
+ status?: { conditions?: McpServerCondition[] }
+}): McpServerResource {
+ return {
+ metadata: { name: SERVER_NAME, namespace: NAMESPACE },
+ spec: {
+ image: CONNECTOR_IMAGE,
+ 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' },
+ ],
+ },
+ },
+ ...(options.status === undefined ? {} : { status: options.status }),
+ }
+}
+
+/** 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(CONNECTOR_IMAGE)
++ // The credentials tab owns this heading and renders only after
++ // getMcpServer() resolves. The current edit-page layout no longer repeats
++ // the image in this tab, so use the credential section itself as the loaded
++ // anchor rather than a detail rendered by the egress tab.
++ await screen.findByRole('heading', { name: /^(Update|Set) credentials$/ })
+}
+
+/** The credential panel, scoped so "no submit control" means no control in
+ * THIS section rather than none on a page that also has Save egress/Cancel. */
+function credentialPanel(): HTMLElement {
+ const heading = screen.getByRole('heading', { name: /^(Update|Set) credentials$/ })
+ const section = heading.closest('section')
+ if (!section) throw new Error('credential FormSection not found')
+ return section
+}
+
+/**
+ * Drives the LATE-DISCOVERY journey: fill PARTIAL rotate data (one of the two
+ * declared keys), submit, confirm, and have the real PUT answer a
+ * status-bearing 404 — the only way a connector whose status never said
+ * "missing" can learn its Secret is gone.
+ */
+async function submitPartialRotateAndGet404() {
+ mockUpdateMcpSecret.mockRejectedValue(
+ Object.assign(new Error(`404 - Secret "${SECRET_NAME}" not found in ${NAMESPACE}`), {
+ 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' }))
+}
+
+/** Invariant O2 at the page level: explanation only. */
+function expectExplanationOnly() {
+ const panel = credentialPanel()
+ expect(within(panel).getByText(/managed by its WorkflowRecipe/i)).toBeInTheDocument()
+ // No credential form at all…
+ expect(panel.querySelectorAll('form')).toHaveLength(0)
+ // …no password inputs (the only kind this screen renders for credentials)…
+ expect(panel.querySelectorAll('input[type="password"]')).toHaveLength(0)
+ // Regex, not the bare key: set mode's label carries the required marker
+ // ("api-key *"), so an exact-string query would pass even if the create form
+ // HAD rendered.
+ expect(screen.queryByLabelText(/^api-key/)).not.toBeInTheDocument()
+ expect(screen.queryByLabelText(/^workspace-id/)).not.toBeInTheDocument()
+ // …no submit control…
+ expect(within(panel).queryAllByRole('button')).toHaveLength(0)
+ expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Rotate credentials' })).not.toBeInTheDocument()
+ // …and no copy telling the operator to re-enter every key on a screen that
+ // cannot create anything.
+ expect(screen.queryByText(/Enter every key to recreate it/)).not.toBeInTheDocument()
+ // The load-bearing one: the POST is never reached.
+ expect(mockCreateMcpSecret).not.toHaveBeenCalled()
+}
+
+/** The managed control: the recovery this screen exists to provide. */
+function expectRecoveredIntoCreateForm() {
+ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()
+ expect(screen.getByText(/This Secret no longer exists\./)).toBeInTheDocument()
+ // "api-key *" in set mode — every declared key is required there.
+ expect(screen.getByLabelText('api-key *')).toBeInTheDocument()
+ expect(screen.getByLabelText('workspace-id *')).toBeInTheDocument()
+ expect(screen.queryByText(/managed by its WorkflowRecipe/i)).not.toBeInTheDocument()
+ // Still no POST: recovering into the form is not submitting it.
+ expect(mockCreateMcpSecret).not.toHaveBeenCalled()
+}
+
+beforeEach(() => {
+ mockGetMcpServers.mockResolvedValue({ items: [] })
++ mockGetContexts.mockResolvedValue({ items: [] })
+})
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+
+// ─── R1-H2 / mini-spec §1: ownership is a function of `spec` alone ─────────
+//
+// Invariant O1: `recipeOwned === (spec.managed === false)`, never a function of
+// status. Every shape below resolves the SURFACE to 'rotate' — none of them
+// carries the SecretNotFound condition that would let the resolver spot the
+// missing Secret up front — so ownership is the ONLY thing standing between a
+// managed:false connector and the create form once the PUT 404s.
+//
+// That is what makes the round-2 mutation
+//
+// recipeOwned = (status?.conditions ?? []).length === 0 && managed === false
+//
+// so dangerous: for shapes 3-5 it silently returns false and the late 404
+// re-opens POST on a Secret that belongs to a WorkflowRecipe. Shapes 1-2 are
+// the other half of the pair — they keep the mutant honest about the states it
+// does still get right, so a "fix" that simply hard-codes recipeOwned=false
+// cannot pass either.
+const STATUS_SHAPES: Array<{
+ name: string
+ status?: { conditions?: McpServerCondition[] }
+}> = [
+ // 1. The connector was just created and HCC has not written the status
+ // subresource at all. Nothing observable says anything.
+ { name: 'status absent entirely', status: undefined },
+ // 2. Status exists but is empty — the same information, a different shape.
+ { name: 'empty conditions array', status: { conditions: [] } },
+ // 3. SYNTHETIC ADVERSARY: HCC writes SecretResolved at 'True' or 'False'
+ // only, never 'Unknown'. Included because a partially-reconciled or
+ // hand-edited resource can still present it, and because it is the
+ // cheapest way to have a NON-EMPTY conditions array that proves nothing —
+ // exactly where the length-based mutant goes wrong.
+ {
+ name: 'SecretResolved / Unknown / Reconciling (synthetic)',
+ status: {
+ conditions: [
+ syntheticCondition({
+ status: 'Unknown',
+ reason: 'Reconciling',
+ message: 'Secret resolution in progress',
+ lastTransitionTime: '2026-08-06T03:00:00.000Z',
+ }),
+ ],
+ },
+ },
+ // 4. Producer output, but STALE: the Secret resolved cleanly an hour ago and
+ // has been deleted since. The UI cannot know that until the PUT 404s.
+ {
+ name: 'stale SecretResolved / True / SecretFound',
+ status: { conditions: [secretFound({ at: '2026-08-06T03:00:00.000Z' })] },
+ },
+ // 5. Producer output: the Secret EXISTS but lacks a key — so this one says
+ // the opposite of "missing", and still resolves to rotate.
+ {
+ name: 'SecretResolved / False / SecretMissingKey',
+ status: {
+ conditions: [
+ secretMissingKey({
+ at: '2026-08-06T03:00:00.000Z',
+ secretName: SECRET_NAME,
+ secretKey: 'workspace-id',
+ envVar: 'LINEAR_WORKSPACE',
+ }),
+ ],
+ },
+ },
+]
+
+describe('EditMcpServerPage — ownership survives a late 404 for every status shape', () => {
+ for (const shape of STATUS_SHAPES) {
+ it(`keeps a managed:false connector on explanation-only — ${shape.name}`, async () => {
+ await renderPage(mcpServer({ managed: false, status: shape.status }))
+
+ // It starts as an ordinary rotate form: nothing observable says the
+ // Secret is missing, so the resolver can only answer 'rotate'.
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()
+
+ await submitPartialRotateAndGet404()
+
+ await waitFor(() => {
+ expect(screen.getByText(/managed by its WorkflowRecipe/i)).toBeInTheDocument()
+ })
+ expectExplanationOnly()
+ // The partial draft really was submitted — one key of two — so this is
+ // the journey that used to leak into a partial POST, not a no-op.
+ expect(mockUpdateMcpSecret).toHaveBeenCalledWith(SECRET_NAME, { 'api-key': 'partial-value' })
+ })
+
+ it(`still recovers a managed:true connector into the create form — ${shape.name}`, async () => {
+ await renderPage(mcpServer({ managed: true, status: shape.status }))
+
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()
+
+ await submitPartialRotateAndGet404()
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()
+ })
+ expectRecoveredIntoCreateForm()
+ })
+ }
+
+ // `managed` absent means managed:true (the CRD defaults it, so the API server
+ // always persists it — but a fixture or an older resource may still omit it).
+ // Absence must never be read as recipe-owned.
+ it('treats an ABSENT spec.managed as managed, not as recipe-owned', async () => {
+ await renderPage(mcpServer({ status: { conditions: [] } }))
+ await submitPartialRotateAndGet404()
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()
+ })
+ expectRecoveredIntoCreateForm()
+ })
+})
+
+describe('EditMcpServerPage — credential surface wiring', () => {
+ it('renders the CREATE form when a managed connector reports SecretNotFound', async () => {
+ await renderPage(
+ mcpServer({
+ managed: true,
+ status: {
+ conditions: [secretNotFound({ at: '2026-08-06T04:00:00.000Z', secretName: SECRET_NAME })],
+ },
+ })
+ )
+
+ 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,
+ status: {
+ conditions: [
+ secretMissingKey({ at: '2026-08-06T04:00:00.000Z', secretName: SECRET_NAME }),
+ ],
+ },
+ })
+ )
+
+ 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,
+ status: {
+ conditions: [secretNotFound({ at: '2026-08-06T04:00:00.000Z', secretName: SECRET_NAME })],
+ },
+ })
+ )
+
+ expectExplanationOnly()
+ })
+
+ // A real status array carries several condition types and no ordering
+ // guarantee. Only the newest SecretResolved entry may decide the surface.
+ //
+ // The DeploymentReady entry is a SYNTHETIC ADVERSARY: it reuses the
+ // SecretNotFound reason on a type the HCC never writes it on, and carries the
+ // newest timestamp in the array.
+ it('ignores unrelated conditions and honors the NEWEST SecretResolved entry', async () => {
+ await renderPage(
+ mcpServer({
+ managed: true,
+ status: {
+ conditions: [
+ syntheticCondition({
+ type: 'DeploymentReady',
+ message: 'unrelated condition reusing the reason',
+ lastTransitionTime: '2026-08-06T09:00:00.000Z',
+ }),
+ secretNotFound({ at: '2026-08-06T04:00:00.000Z', secretName: SECRET_NAME }),
+ secretFound({ at: '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,
+ status: {
+ conditions: [
+ secretFound({ at: '2026-08-06T04:00:00.000Z' }),
+ secretNotFound({ at: '2026-08-06T05:00:00.000Z', secretName: SECRET_NAME }),
+ ],
+ },
+ })
+ )
+
+ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()
+ })
+
+ // The R1-M2 defect, end to end through the page: a malformed calendar date
+ // (February 30, which JavaScript silently normalizes into March 2) must NOT
+ // outrank the valid — and genuinely newer — clean resolution.
+ //
+ // SYNTHETIC ADVERSARY: HCC always stamps a real instant.
+ it('does not let a February-30 duplicate reopen the create form', async () => {
+ await renderPage(
+ mcpServer({
+ managed: true,
+ status: {
+ conditions: [
+ syntheticCondition({ lastTransitionTime: '2026-02-30T00:00:00.000Z' }),
+ secretFound({ at: '2026-02-28T23:59:59.000Z' }),
+ ],
+ },
+ })
+ )
+
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()
+ })
+})
diff --cc control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx
index 42912d81d,1608a8e4c..394dbfd2b
--- a/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx
+++ b/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx
@@@ -6,21 -6,21 +6,29 @@@ import
POLL_TIMEOUT_MS,
UpdateConnectorCredentials,
} from '@components/UpdateConnectorCredentials'
-import { getMcpServer, getMcpServers, getRegistryCredentialSchema, updateMcpSecret } from '@lib/api'
+import type { CredentialSurface } from '@components/UpdateConnectorCredentials/resolveCredentialSurface'
- import { createMcpSecret, getMcpServer, getMcpServers, updateMcpSecret } from '@lib/api'
++import {
++ createMcpSecret,
++ getMcpServer,
++ getMcpServers,
++ getRegistryCredentialSchema,
++ updateMcpSecret,
++} from '@lib/api'
import type { EnvSecret, McpServerResource } from '@lib/api'
-import { buildSecretSummary } from '../../test/fixtures/secretSummary'
vi.mock('@lib/api', () => ({
getMcpServer: vi.fn(),
getMcpServers: vi.fn(),
+ getRegistryCredentialSchema: vi.fn(),
updateMcpSecret: vi.fn(),
+ createMcpSecret: vi.fn(),
}))
const mockGetMcpServer = vi.mocked(getMcpServer)
const mockGetMcpServers = vi.mocked(getMcpServers)
+ const mockGetRegistryCredentialSchema = vi.mocked(getRegistryCredentialSchema)
const mockUpdateMcpSecret = vi.mocked(updateMcpSecret)
+const mockCreateMcpSecret = vi.mocked(createMcpSecret)
const SERVER_NAME = 'my-connector'
// secretKey and envVar are deliberately different strings so table/label
@@@ -197,15 -151,42 +205,38 @@@ describe('UpdateConnectorCredentials �
expect(input).toHaveAttribute('autocomplete', 'new-password')
expect(input.value).toBe('')
}
- expect(
- rotateButton.compareDocumentPosition(screen.getByLabelText(ENV_SECRET.keys[0].secretKey))
- ).toBe(Node.DOCUMENT_POSITION_PRECEDING)
})
- it('uses the Marketplace credential label when the connector retains its catalog source', async () => {
++ it('uses a Marketplace credential label while preserving the Secret key identifier', async () => {
+ mockGetRegistryCredentialSchema.mockResolvedValueOnce({
+ required: true,
+ authType: 'api-key',
- keys: [
- {
- name: 'api-key',
- label: 'Linear API key',
- kind: 'api-key',
- },
- ],
++ keys: [{ name: 'api-key', label: 'Linear API key', kind: 'api-key' }],
+ })
+ render(
+ <ToastProvider>
+ <UpdateConnectorCredentials
+ serverName={SERVER_NAME}
+ envSecret={ENV_SECRET}
+ registryCredentialSource={{ name: '@evenfire/linear', version: '1.0.0' }}
+ />
+ </ToastProvider>
+ )
+
+ await flush(3)
+
+ expect(mockGetRegistryCredentialSchema).toHaveBeenCalledWith('@evenfire/linear', '1.0.0')
+ expect(screen.getByLabelText('Linear API key')).toBeInTheDocument()
+ expect(screen.getByLabelText('workspace-id')).toBeInTheDocument()
+ })
+
it('never renders a stored credential value — inputs stay empty through a full rotation cycle', async () => {
- mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key']))
+ mockUpdateMcpSecret.mockResolvedValue({
+ name: ENV_SECRET.name,
+ namespace: 'mcp-server',
+ keys: ['api-key'],
+ affectedConnectors: [SERVER_NAME],
+ })
mockGetMcpServer.mockResolvedValue(
serverWithCondition({
status: 'True',
diff --cc control-ui/components/__tests__/fixtures/producerContract.ts
index 3da004474,000000000..a4556f3f8
mode 100644,000000..100644
--- a/control-ui/components/__tests__/fixtures/producerContract.ts
+++ b/control-ui/components/__tests__/fixtures/producerContract.ts
@@@ -1,655 -1,0 +1,678 @@@
+import { readFileSync } from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import type { McpServerCondition } from '@lib/api'
+
+/**
+ * The `SecretResolved` contract, READ OFF THE PRODUCER (R1-H2).
+ *
+ * Every `SecretResolved` condition the credential screen can ever observe is
+ * written by `host-context-controller/src/reconciler.ts`, and by nothing else.
+ * This module extracts that contract — the condition type, the success triple,
+ * the failure status, and each failure reason with its message template — from
+ * the producer's own source text, so the fixture builders in
+ * `./secretResolvedConditions.ts` can DERIVE their values instead of restating
+ * them.
+ *
+ * That derivation is the whole point. A handwritten mirror of the producer is
+ * exactly as stale as the author who wrote it, and a UI suite cannot tell the
+ * difference: if HCC renamed a reason, both the mocked producer output and the
+ * assertion would keep encoding the old triple and stay green. With the
+ * fixtures derived, the rename travels into every suite that renders a
+ * connector — `getMcpServer` → page → resolver → component — and the ones whose
+ * expectations no longer hold go red.
+ *
+ * ── Nothing here may fail SILENTLY ────────────────────────────────────────
+ *
+ * A silently-empty extraction would let every consuming suite pass while
+ * proving nothing, which is strictly worse than the handwritten mirror it
+ * replaces. So every step throws — at IMPORT time, before a single test body
+ * runs — when it cannot find what it is looking for: a missing or implausibly
+ * small producer file, a condition write it cannot parse, a failure branch it
+ * cannot classify, a declared reason with no matching return, a message
+ * placeholder no builder argument feeds. There is no code path that returns an
+ * empty or partial contract.
+ *
+ * ── Independence from `../secretResolvedProducerContract.test.ts` ──────────
+ *
+ * That suite reads the same producer and asserts the fixture builders reproduce
+ * what IT extracted. It deliberately does not import this module: the two
+ * extractions are written differently on purpose — this one anchors on the
+ * `writeStatusCondition` CALL and classifies failures by the BRANCH GUARD they
+ * sit under, that one anchors on the `type: 'SecretResolved',` literal and keys
+ * failures by their reason string. Neither can vacuously agree with itself, and
+ * a disagreement between them is a red test rather than a shared blind spot.
+ *
+ * This module reads source TEXT only. It does not import the controller:
+ * making control-ui depend on an HCC package at runtime would be heavier
+ * coupling than the drift it prevents.
+ */
+
+const RECONCILER_PATH = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../../../../host-context-controller/src/reconciler.ts'
+)
+
+/** Smallest size the real reconciler has ever been, by a wide margin. A stub, a
+ * truncated read or an empty file must not be mistaken for "no producer". */
+const MIN_PRODUCER_BYTES = 20_000
+
+function fail(detail: string): never {
+ throw new Error(
+ `SecretResolved producer contract [${path.basename(RECONCILER_PATH)}]: ${detail} ` +
+ `This module is the only thing tying the control-ui credential fixtures to the real ` +
+ `host-context-controller conditions — repair the extraction, do not delete it.`
+ )
+}
+
+function readProducerSource(): string {
+ let text: string
+ try {
+ text = readFileSync(RECONCILER_PATH, 'utf8')
+ } catch (error) {
+ fail(
+ `cannot read the producer at ${RECONCILER_PATH}. If the host-context-controller moved, ` +
+ `update RECONCILER_PATH. (${error instanceof Error ? error.message : String(error)})`
+ )
+ }
+ if (text.length < MIN_PRODUCER_BYTES) {
+ fail(
+ `${RECONCILER_PATH} is only ${text.length} bytes, below the ${MIN_PRODUCER_BYTES}-byte ` +
+ `floor. Refusing to derive a contract from what is almost certainly not the real reconciler.`
+ )
+ }
+ return text
+}
+
+const source = readProducerSource()
+const lines = source.split('\n')
+
+// ─── Small source-text helpers ─────────────────────────────────────────────
+
+const indentOf = (line: string): number => line.length - line.trimStart().length
+const isBlank = (line: string): boolean => line.trim() === ''
+const isStringLiteral = (expression: string): boolean => /^'[^']*'$/.test(expression)
+const unquote = (expression: string): string => expression.slice(1, -1)
+const stripTrailingComma = (text: string): string => text.replace(/,$/, '')
+
+/** Index of the line closing the brace opened on `startIndex`. */
+function blockEnd(startIndex: number, what: string): number {
+ let depth = 0
+ for (let index = startIndex; index < lines.length; index++) {
+ for (const character of lines[index]) {
+ if (character === '{') depth += 1
+ else if (character === '}') {
+ depth -= 1
+ if (depth === 0) return index
+ }
+ }
+ }
+ return fail(`the ${what} opened at line ${startIndex + 1} is never closed.`)
+}
+
+/**
+ * Properties of an object literal whose opening brace is on `startIndex`,
+ * keyed by name with the RAW value expression (whitespace collapsed, trailing
+ * comma removed). Multi-line values — ternaries, concatenated templates — are
+ * joined; ES shorthand (`message,`) yields the identifier as its own value.
+ */
+function propertiesOf(startIndex: number, endIndex: number): Map<string, string> {
+ const propertyIndent = indentOf(lines[startIndex]) + 2
+ const properties = new Map<string, string>()
+ let name: string | null = null
+ let parts: string[] = []
+
+ const flush = (): void => {
+ // Lines are joined with a single space and NOT whitespace-collapsed: a
+ // producer message is compared byte for byte, so squeezing runs of spaces
+ // inside one would invent a message no controller ever wrote.
+ if (name !== null) {
+ properties.set(name, stripTrailingComma(parts.join(' ').trim()))
+ }
+ name = null
+ parts = []
+ }
+
+ for (let index = startIndex + 1; index < endIndex; index++) {
+ const line = lines[index]
+ if (isBlank(line)) continue
+ const declaration =
+ indentOf(line) === propertyIndent
+ ? /^([A-Za-z_$][\w$]*)(?::\s*(.*))?$/.exec(stripTrailingComma(line.trim()))
+ : null
+ if (declaration) {
+ flush()
+ name = declaration[1]
+ // `message,` shorthand: the value IS the identifier.
+ parts = [declaration[2] === undefined ? declaration[1] : declaration[2]]
+ continue
+ }
+ if (name === null) continue // leading comment, before the first property
+ parts.push(line.trim())
+ }
+ flush()
+ return properties
+}
+
+function requiredProperty(properties: Map<string, string>, name: string, what: string): string {
+ const value = properties.get(name)
+ if (value === undefined) {
+ fail(`the ${what} has no \`${name}\` property. Its literal changed shape; re-derive this.`)
+ }
+ return value
+}
+
+// ─── Extraction 1: the condition writes ────────────────────────────────────
+//
- // Anchored on the CALL — `await this.writeStatusCondition(server, {` — not on
- // any condition type literal, so the condition type itself is derived rather
- // than assumed.
++// Anchored on the CALL — not on any condition type literal, so the condition
++// type itself is derived rather than assumed. The HCC writes are deliberately
++// formatted across arguments (`writeStatusCondition(\n server,\n { ... })`) to
++// make the cancellation callback explicit, while older producer revisions
++// used `writeStatusCondition(server, { ... })`; both are accepted here.
+
+type ConditionWrite = {
+ /** 1-based line of the call, for failure messages. */
+ line: number
+ /** The condition type, unquoted. Always a literal (enforced below). */
+ type: string
+ /** RAW source expressions, e.g. `'True'` or `secretResult.reason`. */
+ status: string
+ reason: string
+ message: string
+}
+
- const WRITE_CALL = /^\s*await this\.writeStatusCondition\(server, \{$/
++const WRITE_CALL = /^\s*await this\.writeStatusCondition\($/
++const LEGACY_WRITE_CALL = /^\s*await this\.writeStatusCondition\(server, \{$/
++
++function conditionObjectStart(callIndex: number): number | null {
++ if (LEGACY_WRITE_CALL.test(lines[callIndex])) return callIndex
++ const serverArgument = lines[callIndex + 1]?.trim()
++ // This contract models reconcile's McpServer SecretResolved writes. Other
++ // controller paths write conditions for `state.server`; they are not part of
++ // the validateSecret producer contract and must not make this extractor
++ // reject a source file that legitimately contains them.
++ if (serverArgument !== 'server,') return null
++ const conditionObject = lines[callIndex + 2]?.trim()
++ if (conditionObject !== '{') {
++ fail(
++ `the writeStatusCondition call at line ${callIndex + 1} no longer passes ` +
++ '`server` followed by a condition object. Re-derive the producer contract.'
++ )
++ }
++ return callIndex + 2
++}
+
+function extractConditionWrites(): ConditionWrite[] {
+ const writes: ConditionWrite[] = []
+ lines.forEach((line, index) => {
- if (!WRITE_CALL.test(line)) return
++ if (!WRITE_CALL.test(line) && !LEGACY_WRITE_CALL.test(line)) return
++ const objectStart = conditionObjectStart(index)
++ if (objectStart === null) return
+ const what = `condition write at line ${index + 1}`
- const properties = propertiesOf(index, blockEnd(index, what))
++ const properties = propertiesOf(objectStart, blockEnd(objectStart, what))
+ const typeExpression = requiredProperty(properties, 'type', what)
+ if (!isStringLiteral(typeExpression)) {
+ fail(
+ `the ${what} names its type with the expression \`${typeExpression}\` rather than a ` +
+ `string literal. A computed condition type is invisible to this contract, which would ` +
+ `let a SecretResolved write go unmodelled.`
+ )
+ }
+ writes.push({
+ line: index + 1,
+ type: unquote(typeExpression),
+ status: requiredProperty(properties, 'status', what),
+ reason: requiredProperty(properties, 'reason', what),
+ message: requiredProperty(properties, 'message', what),
+ })
+ })
+ if (writes.length === 0) {
+ fail(
- `found NO \`await this.writeStatusCondition(server, {\` calls. Either the producer stopped ` +
++ 'found NO writeStatusCondition calls with a server and condition object. Either the producer stopped ' +
+ `writing status conditions altogether, or this extractor no longer matches the call.`
+ )
+ }
+ return writes
+}
+
+const conditionWrites = extractConditionWrites()
+
+/**
+ * The FORWARDING writes: the ones whose reason and message come straight from a
+ * `validateSecret` failure result. They are what identifies the SecretResolved
+ * condition type and its failure status without either being restated here.
+ */
+const forwardingWrites = conditionWrites.filter(write => write.reason === 'secretResult.reason')
+
+if (forwardingWrites.length === 0) {
+ fail(
+ `no condition write forwards \`secretResult.reason\`. Every False SecretResolved condition ` +
+ `the credential screen reads is one of those forwards, so an empty set means the extractor ` +
+ `is broken or the producer stopped surfacing secret validation failures as conditions.`
+ )
+}
+
+function onlyValue(values: string[], what: string): string {
+ const distinct = new Set(values)
+ if (distinct.size !== 1) {
+ fail(`expected ONE ${what} across the producer's forwarding writes, found ${[...distinct]}.`)
+ }
+ return [...distinct][0]
+}
+
+for (const write of forwardingWrites) {
+ if (write.message !== 'secretResult.message') {
+ fail(
+ `the condition write at line ${write.line} forwards \`secretResult.reason\` but writes ` +
+ `\`${write.message}\` as its message. The fixtures derive the condition message from the ` +
+ `validateSecret result, which that write no longer does.`
+ )
+ }
+}
+
+/**
+ * The condition type the credential screen resolves on, taken from the
+ * producer's own forwarding writes.
+ */
+export const PRODUCER_CONDITION_TYPE: string = onlyValue(
+ forwardingWrites.map(write => write.type),
+ 'condition type'
+)
+
+/**
+ * The K8s tri-state the UI's own `McpServerCondition` admits. This is a
+ * CONSUMER-side constraint, not a copy of the producer: a producer value
+ * outside it could not be typed as a condition at all, and silently widening
+ * the UI type is exactly the drift this module exists to refuse.
+ */
+const CONDITION_STATUSES: McpServerCondition['status'][] = ['True', 'False', 'Unknown']
+
+function asConditionStatus(expression: string, what: string): McpServerCondition['status'] {
+ if (!isStringLiteral(expression)) {
+ fail(`the ${what} is the expression \`${expression}\`, not a string literal status.`)
+ }
+ const value = unquote(expression) as McpServerCondition['status']
+ if (!CONDITION_STATUSES.includes(value)) {
+ fail(
+ `the ${what} is '${value}', which is not one of the tri-state values the UI's ` +
+ `McpServerCondition admits (${CONDITION_STATUSES.join(', ')}).`
+ )
+ }
+ return value
+}
+
+/** The status every forwarded `validateSecret` failure is written at. */
+export const PRODUCER_FAILURE_STATUS: McpServerCondition['status'] = asConditionStatus(
+ onlyValue(
+ forwardingWrites.map(write => write.status),
+ 'failure status'
+ ),
+ 'forwarded failure status'
+)
+
+/**
+ * The success triple. Derived as "every fully-literal write on the
+ * SecretResolved type", which is the complement of the forwarding writes — so a
+ * THIRD write shape on that type is a hard error rather than something this
+ * contract quietly ignores.
+ */
+function extractSuccess(): {
+ status: McpServerCondition['status']
+ reason: string
+ message: string
+} {
+ const onType = conditionWrites.filter(write => write.type === PRODUCER_CONDITION_TYPE)
+ const literal = onType.filter(
+ write =>
+ isStringLiteral(write.status) &&
+ isStringLiteral(write.reason) &&
+ isStringLiteral(write.message)
+ )
+ if (literal.length + forwardingWrites.length !== onType.length) {
+ fail(
+ `the producer writes '${PRODUCER_CONDITION_TYPE}' in a shape that is neither a forwarded ` +
+ `validateSecret failure nor a fully-literal triple (lines ` +
+ `${onType.map(write => write.line).join(', ')}). The UI can observe a condition this ` +
+ `contract says nothing about.`
+ )
+ }
+ if (literal.length === 0) {
+ fail(`the producer never writes a literal '${PRODUCER_CONDITION_TYPE}' triple any more.`)
+ }
+ const distinct = new Set(literal.map(write => `${write.status}|${write.reason}|${write.message}`))
+ if (distinct.size !== 1) {
+ fail(
+ `the producer's literal '${PRODUCER_CONDITION_TYPE}' writes no longer agree: ${[...distinct]}. ` +
+ `One fixture builder cannot stand for all of them; it needs a discriminator.`
+ )
+ }
+ const success = literal[0]
+ const status = asConditionStatus(success.status, `literal write at line ${success.line}`)
+ if (status === PRODUCER_FAILURE_STATUS) {
+ fail(
+ `the producer's literal '${PRODUCER_CONDITION_TYPE}' write at line ${success.line} carries ` +
+ `the FAILURE status '${status}', so there is no success triple to derive.`
+ )
+ }
+ return { status, reason: unquote(success.reason), message: unquote(success.message) }
+}
+
+/** The triple both success sites — managed and WRC-owned — write. */
+export const PRODUCER_SUCCESS: {
+ status: McpServerCondition['status']
+ reason: string
+ message: string
+} = extractSuccess()
+
+// ─── Extraction 2: validateSecret's failure results ────────────────────────
+//
+// Scoped to the `validateSecret` method body, and each result is classified by
+// the BRANCH GUARD it sits under — the k8s 404, the 401/403, the missing-key
+// check — never by the reason string it returns. That is what makes a reason
+// RENAME propagate instead of throwing: the role survives, the value moves.
+
+function findMethodBody(name: string): { start: number; end: number } {
+ const start = lines.findIndex(line => new RegExp(`^\\s*async ${name}\\(`).test(line))
+ if (start < 0) {
+ fail(`could not find the \`async ${name}(\` method. Every False condition forwards its result.`)
+ }
+ const methodIndent = indentOf(lines[start])
+ for (let index = start + 1; index < lines.length; index++) {
+ if (indentOf(lines[index]) === methodIndent && lines[index].trim() === '}') {
+ return { start, end: index }
+ }
+ }
+ return fail(`the \`async ${name}(\` method starting at line ${start + 1} is never closed.`)
+}
+
+const validateSecret = findMethodBody('validateSecret')
+
+/**
+ * The block openers enclosing a statement, innermost first, up to the method
+ * signature. Derived from indentation: the first PRECEDING line indented less
+ * than the statement is the opener of the block containing it, and the walk
+ * repeats from there.
+ */
+function enclosingBlockOpeners(statementIndex: number): string[] {
+ const openers: string[] = []
+ let indent = indentOf(lines[statementIndex])
+ for (let index = statementIndex - 1; index >= validateSecret.start; index--) {
+ if (isBlank(lines[index])) continue
+ const candidate = indentOf(lines[index])
+ if (candidate < indent) {
+ openers.push(lines[index].trim())
+ indent = candidate
+ }
+ }
+ if (openers.length === 0) {
+ fail(
+ `the failure return at line ${statementIndex + 1} has no enclosing block, which is not a ` +
+ `shape TypeScript can produce. The indentation this extractor reads nesting from changed.`
+ )
+ }
+ return openers
+}
+
+/**
+ * Collapses a possibly multi-line, possibly `+`-concatenated template literal
+ * into the single template it evaluates to. A plain quoted string is accepted
+ * as a template with no placeholders.
+ */
+function normalizeTemplate(raw: string, what: string): string {
+ const joined = raw.trim().replace(/`\s*\+\s*`/g, '')
+ if (isStringLiteral(joined)) return unquote(joined)
+ if (!joined.startsWith('`') || !joined.endsWith('`') || joined.length < 2) {
+ fail(
+ `could not read the message template for ${what}. Expected one or more concatenated ` +
+ `template literals, got ${JSON.stringify(raw)}.`
+ )
+ }
+ return joined.slice(1, -1)
+}
+
+/** Walks BACK from a failure return to the `const message =` that fed it. */
+function templateFromPrecedingAssignment(returnIndex: number, what: string): string {
+ for (let index = returnIndex; index >= validateSecret.start; index--) {
+ const assignment = /^\s*const message =(.*)$/.exec(lines[index])
+ if (!assignment) continue
+ const baseIndent = indentOf(lines[index])
+ const parts = [assignment[1].trim()]
+ for (let cursor = index + 1; cursor < validateSecret.end; cursor++) {
+ if (isBlank(lines[cursor]) || indentOf(lines[cursor]) <= baseIndent) break
+ parts.push(lines[cursor].trim())
+ }
+ return normalizeTemplate(parts.join(' '), what)
+ }
+ return fail(
+ `the ${what} references a \`message\` with no preceding \`const message =\` assignment. ` +
+ `The producer's failure construction changed.`
+ )
+}
+
+type FailureReturn = { line: number; reason: string; template: string }
+
+const INLINE_FAILURE = /^return \{ ok: false, reason: ('[A-Za-z]+'), message \},?$/
+
+function extractFailureReturns(): FailureReturn[] {
+ const results: FailureReturn[] = []
+ for (let index = validateSecret.start + 1; index < validateSecret.end; index++) {
+ const trimmed = lines[index].trim()
+ if (!trimmed.startsWith('return {')) continue
+ const what = `validateSecret failure return at line ${index + 1}`
+
+ // Single-line form: `return { ok: false, reason: 'X', message }`.
+ if (trimmed.includes('ok: false') && !trimmed.endsWith('{')) {
+ const inline = INLINE_FAILURE.exec(trimmed)
+ if (!inline) {
+ fail(`the ${what} is an \`ok: false\` result this extractor cannot parse: ${trimmed}`)
+ }
+ results.push({
+ line: index + 1,
+ reason: unquote(inline[1]),
+ template: templateFromPrecedingAssignment(index, what),
+ })
+ continue
+ }
+ if (!trimmed.endsWith('{')) continue
+
+ // Multi-line object form.
+ const properties = propertiesOf(index, blockEnd(index, what))
+ if (properties.get('ok') !== 'false') continue
+ const reason = requiredProperty(properties, 'reason', what)
+ if (!isStringLiteral(reason)) {
+ fail(`the ${what} names its reason with \`${reason}\` rather than a string literal.`)
+ }
+ const message = requiredProperty(properties, 'message', what)
+ results.push({
+ line: index + 1,
+ reason: unquote(reason),
+ template:
+ message === 'message'
+ ? templateFromPrecedingAssignment(index, what)
+ : normalizeTemplate(message, what),
+ })
+ }
+ if (results.length === 0) {
+ fail(
+ `found NO \`ok: false\` results inside validateSecret. Every False ${PRODUCER_CONDITION_TYPE} ` +
+ `condition forwards one of them, so an empty set means the extractor is broken, not that ` +
+ `the failures are gone.`
+ )
+ }
+ return results
+}
+
+const failureReturns = extractFailureReturns()
+
+/**
+ * What each failure MEANS, keyed by the branch the producer takes to reach it.
+ *
+ * - `absent` the API server said the Secret is not there (k8s 404). The
+ * ONLY failure that may send a managed connector to the
+ * create form.
+ * - `missingKey` the Secret EXISTS and lacks a declared key. The rotate
+ * merge-patch adds it.
+ * - `accessDenied` HCC was not allowed to look (k8s 401/403), so this is no
+ * evidence about the Secret at all.
+ * - `readError` any other read failure — the branch with no guard.
+ */
+export type ProducerFailureRole = 'absent' | 'missingKey' | 'accessDenied' | 'readError'
+
+/** Branch guards, NOT reason strings: a reason RENAME must move the value this
+ * role carries, not make the role unfindable. */
+const ROLE_GUARDS: { role: Exclude<ProducerFailureRole, 'readError'>; guard: RegExp }[] = [
+ { role: 'absent', guard: /\bcode === 404\b/ },
+ { role: 'accessDenied', guard: /\bcode === 401\b|\bcode === 403\b/ },
+ { role: 'missingKey', guard: /keyMapping\.secretKey in data/ },
+]
+
+function classifyFailureReturns(): Record<ProducerFailureRole, FailureReturn> {
+ const byRole = new Map<ProducerFailureRole, FailureReturn[]>()
+ const record = (role: ProducerFailureRole, result: FailureReturn): void => {
+ byRole.set(role, [...(byRole.get(role) ?? []), result])
+ }
+
+ for (const result of failureReturns) {
+ const openers = enclosingBlockOpeners(result.line - 1)
+ const matched = ROLE_GUARDS.filter(({ guard }) => openers.some(opener => guard.test(opener)))
+ if (matched.length > 1) {
+ fail(
+ `the failure return at line ${result.line} sits under more than one branch guard ` +
+ `(${matched.map(entry => entry.role).join(', ')}), so its meaning is ambiguous.`
+ )
+ }
+ record(matched.length === 1 ? matched[0].role : 'readError', result)
+ }
+
+ const roles: ProducerFailureRole[] = [...ROLE_GUARDS.map(entry => entry.role), 'readError']
+ const classified = {} as Record<ProducerFailureRole, FailureReturn>
+ for (const role of roles) {
+ const found = byRole.get(role) ?? []
+ if (found.length !== 1) {
+ fail(
+ `expected EXACTLY ONE validateSecret failure for the '${role}' branch, found ` +
+ `${found.length}${found.length ? ` (lines ${found.map(r => r.line).join(', ')})` : ''}. ` +
+ `${
+ role === 'readError'
+ ? 'The unguarded branch is how a NEW failure mode shows up; triage it against the ' +
+ 'create path before re-deriving this.'
+ : 'The branch that decides which credential surface an operator gets moved or forked.'
+ }`
+ )
+ }
+ classified[role] = found[0]
+ }
+ return classified
+}
+
+const failureByRole = classifyFailureReturns()
+
+// ─── Extraction 3: the producer's own enumeration of its failure reasons ───
+//
+// A cross-check on the two above: the reasons the branches return must be
+// exactly the reasons the type declares. A fifth reason, or a declared reason
+// no branch returns, means the classification above is incomplete.
+
+function extractFailureReasonUnion(): string[] {
+ const start = lines.findIndex(line => /^export type SecretValidationResult\b/.test(line))
+ if (start < 0) {
+ fail(
+ `could not find \`export type SecretValidationResult\`. It is the producer's own ` +
+ `enumeration of what a False ${PRODUCER_CONDITION_TYPE} can say.`
+ )
+ }
+ for (let index = start + 1; index < lines.length; index++) {
+ // The declaration ends at the next top-level statement.
+ if (/^\S/.test(lines[index]) && !isBlank(lines[index])) break
+ const declaration = /^\s*reason: ((?:'[A-Za-z]+'(?:\s*\|\s*)?)+)$/.exec(lines[index])
+ if (!declaration) continue
+ const reasons = (declaration[1].match(/'([A-Za-z]+)'/g) ?? []).map(unquote)
+ if (reasons.length === 0) {
+ fail(`the SecretValidationResult failure-reason union at line ${index + 1} is empty.`)
+ }
+ return reasons
+ }
+ return fail(
+ `SecretValidationResult declares no failure-reason union. Without it this contract cannot ` +
+ `detect a new reason appearing.`
+ )
+}
+
+/** Every failure reason the producer declares it can return. */
+export const PRODUCER_FAILURE_REASONS: string[] = extractFailureReasonUnion()
+
+{
+ const declared = new Set(PRODUCER_FAILURE_REASONS)
+ const returned = new Set(failureReturns.map(result => result.reason))
+ const missing = [...declared].filter(reason => !returned.has(reason))
+ const extra = [...returned].filter(reason => !declared.has(reason))
+ if (missing.length > 0 || extra.length > 0) {
+ fail(
+ `the declared failure reasons and the ones validateSecret actually returns disagree — ` +
+ `declared-but-never-returned: [${missing}], returned-but-undeclared: [${extra}]. ` +
+ `One of the two extractions is incomplete, so the role classification cannot be trusted.`
+ )
+ }
+}
+
+// ─── Rendering a producer message template ─────────────────────────────────
+
+/** The values a fixture feeds into the producer's message templates. */
+export type ProducerMessageValues = {
+ secretName?: string
+ namespace?: string
+ secretKey?: string
+ envVar?: string
+ code?: number | string
+ readErrorMessage?: string
+}
+
+/**
+ * Producer interpolation expression -> the fixture argument that fills it.
+ *
+ * An unmapped expression throws: a NEW interpolation in a producer message is
+ * exactly the drift this module exists to catch, and rendering it as the empty
+ * string would quietly produce a message no controller ever writes.
+ */
+const PLACEHOLDER_ARGUMENTS: Record<string, keyof ProducerMessageValues> = {
+ secretName: 'secretName',
+ 'server.namespace': 'namespace',
+ 'keyMapping.secretKey': 'secretKey',
+ 'keyMapping.envVar': 'envVar',
+ code: 'code',
+ errMsg: 'readErrorMessage',
+}
+
+/**
+ * The reason and message the producer emits for one failure ROLE, with the
+ * caller's values interpolated into the producer's own template.
+ */
+export function producerFailure(
+ role: ProducerFailureRole,
+ values: ProducerMessageValues = {}
+): { reason: string; message: string } {
+ const result = failureByRole[role]
+ const message = result.template.replace(/\$\{([^}]+)\}/g, (_whole, expression: string) => {
+ const argument = PLACEHOLDER_ARGUMENTS[expression]
+ if (argument === undefined) {
+ fail(
+ `the message for the '${role}' branch (line ${result.line}) interpolates ` +
+ `\${${expression}}, which no fixture argument maps to. Add it to PLACEHOLDER_ARGUMENTS ` +
+ `and thread the value through the matching builder in ./secretResolvedConditions.ts.`
+ )
+ }
+ const value = values[argument]
+ if (value === undefined) {
+ fail(
+ `the message for the '${role}' branch (line ${result.line}) interpolates ` +
+ `\${${expression}}, but the fixture passed no \`${argument}\`. A producer message must ` +
+ `never be built with a hole in it.`
+ )
+ }
+ return String(value)
+ })
+ if (message.includes('${')) {
+ fail(`the rendered '${role}' message still contains an interpolation: ${message}`)
+ }
+ return { reason: result.reason, message }
+}
diff --cc mcp-host/src/core/guardrails/hooks/hookFetcher.ts
index 000000000,0100d2132..215bf49ec
mode 000000,100644..100644
--- a/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
+++ b/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
@@@ -1,0 -1,190 +1,192 @@@
+ /**
+ * Concrete `/v1` HTTP transport for installed hooks (spec §8.1 wire contract).
+ *
+ * POSTs JSON to `{endpoint}{path}/v1/{point}` with a short-lived bearer token
+ * (mcp-host's env-injected token via a `getAuthToken` closure — the same pattern
+ * as `credentialBrokerClient.ts`; no in-process signing). Enforces the timeout
+ * and body cap, and classifies the outcome per §8.1: `5xx` / timeout /
+ * connection error / malformed or oversized body → `unavailable` (→ the hook's
+ * fail-mode, §8.6). `4xx`/`2xx` are returned for the per-point mapping to judge.
+ *
+ * In-cluster (`image`/`service`) targets resolve to cluster-private IPs and are
+ * dialed directly. A `remote` (external) target — `descriptor.external` — is
+ * dialed through the SSRF-guarded transport (`../../net/ssrf`: reject
+ * private/loopback/link-local/metadata ranges, DNS-pin the connection), so a
+ * hosted provider (e.g. guardrails.aporia.com) works while an internal/metadata
+ * URL is refused (spec §8.3). An SSRF refusal maps to `unavailable` → the hook's
+ * fail-mode.
+ */
+ import { SsrfBlockedError, requestPinned, resolvePinnedPublicIp } from '../../net/ssrf'
+ import type { HookFetcher, LifecyclePoint } from './types'
+
+ /** Minimal fetch surface (injectable for tests + the in-cluster path). */
+ export type FetchLike = (
+ url: string,
+ init: { method: string; headers: Record<string, string>; body: string; signal: AbortSignal }
+ ) => Promise<{ status: number; text: () => Promise<string> }>
+
+ export interface HookFetcherDeps {
+ getAuthToken: () => string
+ timeoutMs?: number
+ /** Tight cap for non-rewrite responses (moderate/post_call/on_error/tool). Default 1 MiB. */
+ maxOutputBytes?: number
+ /** Generous cap for `pre_call` rewrite output (the whole conversation). Default 5 MiB (~1M tokens). */
+ maxRewriteBytes?: number
+ /** In-cluster transport. Defaults to the global `fetch`. */
+ fetchImpl?: FetchLike
+ /** External (remote) transport. Defaults to the SSRF-guarded impl. Injectable for tests. */
+ externalFetchImpl?: FetchLike
+ }
+
+ const POINT_PATH: Record<LifecyclePoint, string> = {
+ pre_call: 'pre_call',
+ moderate: 'moderate',
+ post_call: 'post_call',
+ on_error: 'on_error',
+ pre_tool_use: 'pre_tool_use',
+ post_tool_use: 'post_tool_use',
+ }
+
+ function sanitizeForLog(value: unknown): string {
- return String(value).replace(/[\r\n]+/g, ' ').replace(/[\u0000-\u001F\u007F]/g, '')
++ return String(value)
++ .replace(/[\r\n]+/g, ' ')
++ .replace(/[\u0000-\u001F\u007F]/g, '')
+ }
+
+ /** Build `{endpoint}{path}/v1/{point}`, normalizing slashes (spec §8.1). */
+ export function buildHookUrl(endpoint: string, path: string, point: LifecyclePoint): string {
+ const base = endpoint.replace(/\/+$/, '')
+ const mid = !path || path === '/' ? '' : '/' + path.replace(/^\/+|\/+$/g, '')
+ return `${base}${mid}/v1/${POINT_PATH[point]}`
+ }
+
+ /**
+ * SSRF-guarded transport for `remote` hook targets: requires https, validates
+ * the host resolves only to public IPs, and connects to a pinned IP. Adapts to
+ * the `FetchLike` shape so the outcome classification is shared with the
+ * in-cluster path. Throws `SsrfBlockedError` on a blocked/unverifiable host.
+ */
+ function makeSsrfGuardedFetch(timeoutMs: number, maxBytes: number): FetchLike {
+ return async (urlStr, init) => {
+ const url = new URL(urlStr)
+ if (url.protocol !== 'https:') {
+ throw new SsrfBlockedError(`remote hook URL must be https (got ${url.protocol})`)
+ }
+ const pinnedIp = await resolvePinnedPublicIp(url) // throws SsrfBlockedError on private/unresolvable
+ const { statusCode, body } = await requestPinned({
+ url,
+ method: init.method,
+ headers: init.headers,
+ body: init.body,
+ pinnedIp,
+ timeoutMs,
+ // Absolute deadline (idle-independent) + streaming byte cap: a trickling or
+ // flooding remote hook can no longer hang or OOM the pod (settles → §8.6).
+ signal: init.signal,
+ maxBytes,
+ })
+ return { status: statusCode, text: async () => body }
+ }
+ }
+
+ /**
+ * In-cluster transport (default): the global `fetch` honors the abort `signal`
+ * (absolute deadline) and the body is read WITH a streaming byte cap, so an
+ * oversized in-cluster response is never fully buffered either.
+ */
+ function makeInClusterFetch(maxBytes: number): FetchLike {
+ return async (urlStr, init) => {
+ const res = await (globalThis.fetch as unknown as (u: string, i: unknown) => Promise<Response>)(
+ urlStr,
+ init
+ )
+ return {
+ status: res.status,
+ text: async () => {
+ const stream = res.body as ReadableStream<Uint8Array> | null
+ if (!stream) return res.text()
+ const reader = stream.getReader()
+ const chunks: Buffer[] = []
+ let total = 0
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ if (value) {
+ total += value.length
+ if (total > maxBytes) {
+ await reader.cancel()
+ throw new Error('response exceeded maxBytes') // → caught → unavailable
+ }
+ chunks.push(Buffer.from(value))
+ }
+ }
+ return Buffer.concat(chunks).toString('utf-8')
+ },
+ }
+ }
+ }
+
+ export function createHookFetcher(deps: HookFetcherDeps): HookFetcher {
+ const timeoutMs = deps.timeoutMs ?? 5000
+ // Point-aware response caps (§8.1). A `pre_call` `may_rewrite` output IS the whole
+ // (possibly compressed) conversation — legitimately large — whereas a `moderate`
+ // verdict, a `post_call` redaction, or an `on_error` recovery is small. A single
+ // tight cap for all silently discards rewrites (they blow past 64 KiB) and no-ops
+ // the hook. So: a generous cap for pre_call, a tight cap for everything else.
+ const rewriteCap = deps.maxRewriteBytes ?? 5 * 1024 * 1024 // pre_call: ~1M tokens
+ const responseCap = deps.maxOutputBytes ?? 1 * 1024 * 1024 // moderate / post_call / on_error / tool
+ // The streaming transports enforce only the LARGER ceiling — purely for memory
+ // safety (OOM/flood, §8.6). The per-point APPLICATION cap is checked after parse.
+ const memoryCeiling = Math.max(rewriteCap, responseCap)
+ const inClusterFetch: FetchLike = deps.fetchImpl ?? makeInClusterFetch(memoryCeiling)
+ const externalFetch: FetchLike =
+ deps.externalFetchImpl ?? makeSsrfGuardedFetch(timeoutMs, memoryCeiling)
+
+ return async ({ point, descriptor, body }) => {
+ const url = buildHookUrl(descriptor.endpoint, descriptor.path, point)
+ const doFetch = descriptor.external ? externalFetch : inClusterFetch
+ const applyCap = point === 'pre_call' ? rewriteCap : responseCap
+ try {
+ const res = await doFetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${deps.getAuthToken()}`,
+ },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(timeoutMs),
+ })
+ const text = await res.text()
+ if (text.length > applyCap) {
+ // Over the per-point cap → cannot be applied. NEVER silent (this used to
+ // no-op a rewrite invisibly), and flagged `oversized` so the §8.6 breaker
+ // does NOT count "response too big" as a hook-down failure (§12.4).
+ console.warn(
+ `[Guardrails] hook ${descriptor.id} ${point} response ${text.length}B exceeds the ` +
+ `${point === 'pre_call' ? 'rewrite' : 'response'} cap (${applyCap}B) — discarding as unavailable`
+ )
+ return { status: res.status, body: undefined, unavailable: true, oversized: true }
+ }
+ let parsed: unknown = {}
+ if (text) {
+ try {
+ parsed = JSON.parse(text)
+ } catch {
+ return { status: res.status, body: undefined, unavailable: true } // malformed → unavailable
+ }
+ }
+ // 5xx → unavailable; 2xx/4xx are returned for the mapping to classify.
+ return { status: res.status, body: parsed, unavailable: res.status >= 500 }
+ } catch (err) {
+ // timeout / connection error / SSRF refusal → unavailable (→ fail-mode, §8.6).
+ if (err instanceof SsrfBlockedError) {
+ const safeErrMessage = sanitizeForLog(err.message)
+ const safeDescriptorId = sanitizeForLog(descriptor.id)
+ console.warn(
+ `[Guardrails] remote hook ${safeDescriptorId} blocked by SSRF guard: ${safeErrMessage}`
+ )
+ }
+ return { status: 0, body: undefined, unavailable: true }
+ }
+ }
+ }