Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
Merge origin/dev into feat/oauth-19-integration
Diego Zacarias3d9a3748ed9e
diff --cc control-api/src/db.tsindex 396bbdaf9,bdcdb8227..301cca7d8--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@@ -6104,13 -6192,22 +6192,45 @@@ export const CONTROL_API_MIGRATIONS: Db},},{- version: '0116_dynamic_clients_table',+ version: '0116_mcp_secret_rollback_permits',+ // Renumbered twice while syncing onto dev: 0101 -> 0109 -> 0116. This branch+ // introduced the migration as 0101; the first sync brought dev's 0101–0108+ // (codex multi-connection through the SDK-link FK) and pushed it to 0109;+ // this sync brought dev's 0109–0115 (grok subscriptions through the+ // allowed-models image-input column), so 0109 is now taken by+ // 0109_grok_subscription_connections and the migration moves to the end of+ // the list rather than claiming a version another migration already uses.+ // Environments where this feature branch was already deployed recorded it+ // under one of the earlier names. legacyVersions lets the runner mark 0116+ // applied from that prior row instead of re-running the DDL and leaving an+ // orphan schema_migrations entry. Both prior names are unique to this+ // migration, so there is no false-skip.+ legacyVersions: ['0101_mcp_secret_rollback_permits', '0109_mcp_secret_rollback_permits'],+ apply: applyMcpSecretRollbackPermitSchema,+ },++ {++ // Renumbered from 0116 while syncing onto dev: dev shipped++ // 0116_mcp_secret_rollback_permits, so the oauth-19 dynamic-clients pair++ // moves past it rather than claiming a version another migration already++ // uses. Environments where this feature branch was already deployed (the++ // oauth-19 dev cluster) recorded it as 0116_dynamic_clients_table;++ // legacyVersions lets the runner mark 0117 applied from that prior row++ // instead of re-running the DDL and leaving an orphan schema_migrations++ // entry. The legacy name is unique to this migration, so there is no++ // false-skip.++ version: '0117_dynamic_clients_table',++ legacyVersions: ['0116_dynamic_clients_table'],+ apply: applyDynamicClientsTable,+ },+ {- version: '0117_dynamic_clients_runtime_access',++ // Renumbered from 0117 while syncing onto dev (see 0117_dynamic_clients_table++ // above); dev's 0116 pushed the whole dynamic-clients pair down by one. Same++ // legacyVersions rationale: the prior deploy recorded it as++ // 0117_dynamic_clients_runtime_access, a name unique to this migration.++ version: '0118_dynamic_clients_runtime_access',++ legacyVersions: ['0117_dynamic_clients_runtime_access'],+ apply: applyDynamicClientsRuntimeAccess,+ },]async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {diff --cc control-api/src/routes/admin/registry.tsindex 9fbb7b62e,2cedcef68..fd1e40d6a--- a/control-api/src/routes/admin/registry.ts+++ b/control-api/src/routes/admin/registry.ts@@@ -54,14 -66,7 +69,14 @@@ importvalidateWorkflowRecipeEgressPreflight,validateWorkflowRecipeLimits,} from '../../services/workflowRecipeLimits.js'- import { SecretUpsertRequest } from '../../types.js'+ import type { SecretPreconditions, SecretUpsertRequest } from '../../types.js'+import {+ type GenericOAuthSpecRefs,+ InstallGenericOAuthInputSchema,+ InstallOAuthSecretSchema,+ buildGenericOAuthSpec,+ validateGenericEndpoints,+} from './registryGenericOauth.js'import {EVENFIRE_REGISTRY_PULL_SECRET_NAME,shouldAttachEvenfirePullSecret,@@@ -560,15 -664,11 +674,18 @@@ async function loadRegistryCredentialSc}}+const log = rootLogger.child({ module: 'admin-registry' })+/** Audit log for security-sensitive operations (finding #10). */function auditLog(action: string, details: Record<string, unknown>): void {- const safe: Record<string, unknown> = { timestamp: new Date().toISOString(), action, ...details }+ const safe: Record<string, unknown> = { ...details }+ // Drop value-bearing fields defensively; only key NAMES are ever passed in.+ // pino's redact layer strips token/secret keys on top of this.for (const k of ['credentials', 'clientSecret', 'stringData', 'password']) delete safe[k]- log.info({ event: 'audit', action, ...safe }, `audit: ${action}`)- log.info(safe, 'registry-audit')++ // Keep `action` as a structured field (dev's `registry-audit` message dropped++ // it, which erases which operation the audit line describes); merge the safe++ // details on top. pino's redact layer strips token/secret keys on top of this.++ log.info({ action, ...safe }, 'registry-audit')}/**@@@ -1131,6 -1534,36 +1697,34 @@@ export async function getInstalledRegis}}-const log = rootLogger.child({ module: 'admin-registry' })-+ type RegistryFenceFailure = 'identity-mismatch' | 'identity-unavailable' | 'rejected' | 'unresolved'++ function registryFenceFailure(+ error: unknown+ ): Extract<RegistryFenceFailure, 'rejected' | 'unresolved'> {+ const status = extractK8sError(error)?.status+ return status === 409 || isDeterministicRegistryNoCommit(error) ? 'rejected' : 'unresolved'+ }++ function logRegistryFenceFailure(input: {+ resourceKind: string+ resourceName: string+ namespace: string+ failure: RegistryFenceFailure+ error?: unknown+ }): void {+ log.warn(+ {+ resourceKind: input.resourceKind,+ resourceName: input.resourceName,+ namespace: input.namespace,+ fenceFailure: input.failure,+ ...(input.error === undefined ? {} : { error: registryErrorLogFields(input.error) }),+ },+ 'Registry mutation identity fence did not establish no-commit'+ )+ }+export function createAdminRegistryRouter(gateway?: K8sGateway): Router {const router = Router()@@@ -1591,283 -2024,6 +2185,286 @@@return}+ // ── OAuth wiring (S1-U2/U3 baked · S3-B4 generic): generate spec.oauth from+ // the catalog block + operator input. Only runs when the entry declares OAuth.+ // The catalog `genericConfig` SUGGESTION is validated but NEVER read here to+ // build the spec (S-4): only the wizard-confirmed body.oauth reaches the CR.+ let managedOAuthSecret: { name: string; data: Record<string, string> } | undefined- let oauthClientSecretCreated = false++ // Snapshot of the managed OAuth client Secret created in Step 3b, captured++ // for the same UID/RV-fenced rollback dev applies to the envSecret++ // (createdSecretSnapshot). Null until Step 3b creates it.++ let createdOAuthClientSecretSnapshot: SecretSnapshot | null = null+ const catalogOAuthRaw = (meta as { oauth?: unknown } | null)?.oauth+ if (catalogOAuthRaw !== undefined && catalogOAuthRaw !== null) {+ const parsedCatalog = CatalogOAuthBlockSchema.safeParse(catalogOAuthRaw)+ if (!parsedCatalog.success) {+ res.status(400).json({ error: 'Invalid catalog oauth block', pendingAllowed: false })+ return+ }+ const catalogOAuth = parsedCatalog.data++ if (catalogOAuth.provider === 'generic') {+ // ── Generic self-hosted lane (S3-B4 / DEC-28) ────────────────────────+ // Opened BEFORE the isKnownOAuthProvider gate so 'generic' never enters+ // ADAPTERS/KNOWN_OAUTH_PROVIDERS; the baked path stays byte-identical.+ if (!config.oauthCallbackBaseUrl || config.oauthCallbackBaseUrl.trim().length === 0) {+ res.status(400).json({+ error:+ 'oauth: CONTROL_API_OAUTH_CALLBACK_BASE_URL is not configured; cannot install an OAuth server',+ })+ return+ }+ if (body.oauth === undefined || body.oauth === null) {+ res.status(400).json({+ error: 'oauth: generic client configuration is required (endpoints + wire knobs)',+ })+ return+ }+ const parsedGeneric = InstallGenericOAuthInputSchema.safeParse(body.oauth)+ if (!parsedGeneric.success) {+ // Zod issue paths/messages are field names + type descriptions, never+ // submitted values — cannot leak a client secret or endpoint.+ const detail = parsedGeneric.error.issues+ .map(issue => {+ const path = issue.path.join('.')+ return path ? `${path}: ${issue.message}` : issue.message+ })+ .join('; ')+ res.status(400).json({ error: `oauth: invalid generic oauth input: ${detail}` })+ return+ }+ const genericInput = parsedGeneric.data+ const knobs = genericInput.generic++ // grantScope: operator → catalog → 'user' (same order as baked).+ const grantScope = genericInput.grantScope ?? catalogOAuth.grantScope ?? 'user'++ // Scopes: operator → catalog → [] (generic has no baked adapter). GAP-6+ // (DA-4): with sendScope:true an empty scope set is rejected, exactly as+ // baked; with sendScope:false an authorize without `scope` is legal.+ const scopes = computeInstallOAuthScopes({+ operatorScopes: genericInput.scopes,+ catalogScopes: catalogOAuth.scopes,+ defaultScopes: [],+ })+ if (scopes.length === 0 && knobs.sendScope) {+ res.status(400).json({+ error: 'oauth_scopes_required',+ message:+ 'oauth: generic client with sendScope:true requires explicit scopes; none supplied',+ })+ return+ }++ // Coherence (fail-closed, not a decision): Basic client auth needs a+ // secret. The composer throws at runtime without one (providers.ts); reject+ // at admission instead of creating an unusable public+basic client.+ if (knobs.tokenAuthMethod === 'basic' && genericInput.secret === undefined) {+ res.status(400).json({+ error:+ 'oauth: generic tokenAuthMethod=basic requires a client secret (confidential)',+ })+ return+ }++ // D-B5: control-api derives the immutable id and pre-checks uniqueness. The+ // slug narrow (CEL) applies to generic too — client_id IS oauth.id (public).+ const oauthId = deriveOAuthClientId(serverName)+ if (!oauthId) {+ res+ .status(400)+ .json({ error: 'oauth: could not derive a valid oauth.id from serverName' })+ return+ }+ if (await oauthClientIdInUse(gateway, targetNs, oauthId)) {+ res.status(409).json({+ error: `oauth.id "${oauthId}" is already in use by another server; choose a different serverName`,+ })+ return+ }++ // Kernel §4 (spec 19 §4) over every operator-typed endpoint, BEFORE any+ // Secret or CR is written (0 Secrets, 0 CR on rejection). These endpoints+ // are immutable by CEL and authorize is never re-validated at runtime.+ const endpointErrors = await validateGenericEndpoints(knobs)+ if (endpointErrors.length > 0) {+ res.status(422).json({ error: 'oauth_endpoint_rejected', errors: endpointErrors })+ return+ }++ // Secret refs by mode (D-B3) — confidential only. A public client (no+ // secret) carries NO refs; its client_id IS oauth.id (DA-1).+ let refs: GenericOAuthSpecRefs | undefined+ if (genericInput.secret) {+ if (genericInput.secret.mode === 'reference') {+ const verify = await verifyReferencedOAuthSecret(+ gateway,+ targetNs,+ genericInput.secret+ )+ if (!verify.ok) {+ res.status(verify.status).json({ error: verify.error })+ return+ }+ refs = {+ clientIdRef: {+ name: genericInput.secret.secretName,+ key: genericInput.secret.clientIdKey,+ },+ clientSecretRef: {+ name: genericInput.secret.secretName,+ key: genericInput.secret.clientSecretKey,+ },+ }+ } else {+ const oauthSecretName = `${serverName}-oauth-client`+ refs = {+ clientIdRef: { name: oauthSecretName, key: OAUTH_CLIENT_ID_KEY },+ clientSecretRef: { name: oauthSecretName, key: OAUTH_CLIENT_SECRET_KEY },+ }+ managedOAuthSecret = {+ name: oauthSecretName,+ data: {+ [OAUTH_CLIENT_ID_KEY]: genericInput.secret.clientId,+ [OAUTH_CLIENT_SECRET_KEY]: genericInput.secret.clientSecret,+ },+ }+ }+ }++ mcpServerSpec.auth = { type: 'oauth' }+ mcpServerSpec.oauth = buildGenericOAuthSpec({+ id: oauthId,+ knobs,+ scopes,+ grantScope,+ refs,+ })+ } else {+ // Baked lane (S1) — byte-identical to before, now guarded by the generic+ // branch above so 'generic' never reaches the isKnownOAuthProvider gate.+ if (!isKnownOAuthProvider(catalogOAuth.provider)) {+ res.status(400).json({+ error: `oauth.provider "${catalogOAuth.provider}" is not a supported baked provider`,+ })+ return+ }+ const provider = catalogOAuth.provider++ // D-B4: the public callback base URL MUST be configured. Without it the+ // callback would derive from the internal Host behind the funnel and the+ // operator would register a broken redirect URI at the provider.+ if (!config.oauthCallbackBaseUrl || config.oauthCallbackBaseUrl.trim().length === 0) {+ res.status(400).json({+ error:+ 'oauth: CONTROL_API_OAUTH_CALLBACK_BASE_URL is not configured; cannot install an OAuth server',+ })+ return+ }++ if (body.oauth === undefined || body.oauth === null) {+ res.status(400).json({+ error:+ 'oauth: client credentials are required (managed values or a Secret reference)',+ })+ return+ }+ const parsedInput = InstallOAuthInputSchema.safeParse(body.oauth)+ if (!parsedInput.success) {+ // Describe the real validation failure. Zod issue paths/messages are+ // field names and type descriptions — never the submitted values — so+ // this cannot leak a client secret.+ const detail = parsedInput.error.issues+ .map(issue => {+ const path = issue.path.join('.')+ return path ? `${path}: ${issue.message}` : issue.message+ })+ .join('; ')+ res.status(400).json({ error: `oauth: invalid oauth input: ${detail}` })+ return+ }+ const oauthInput = parsedInput.data++ // grantScope: operator selector wins, else catalog, else 'user'. Immutable+ // once set (D-B7) — this saga only ever creates.+ const grantScope = oauthInput.grantScope ?? catalogOAuth.grantScope ?? 'user'++ // Scopes: operator edit → catalog prefill → baked defaultScopes (D-B6).+ const adapter = getOAuthProviderAdapter(provider)+ const scopes = computeInstallOAuthScopes({+ operatorScopes: oauthInput.scopes,+ catalogScopes: catalogOAuth.scopes,+ defaultScopes: adapter.defaultScopes,+ })+ if (scopes.length === 0) {+ // GAP-6: google/salesforce/slack/notion/monday/clickup have empty+ // defaultScopes, so a server with no scopes supplied is rejected rather+ // than created inert with scopes: [].+ res.status(400).json({+ error: `oauth: provider "${provider}" requires explicit scopes; none supplied`,+ })+ return+ }++ // D-B5: control-api derives the immutable id and pre-checks uniqueness.+ const oauthId = deriveOAuthClientId(serverName)+ if (!oauthId) {+ res+ .status(400)+ .json({ error: 'oauth: could not derive a valid oauth.id from serverName' })+ return+ }+ if (await oauthClientIdInUse(gateway, targetNs, oauthId)) {+ res.status(409).json({+ error: `oauth.id "${oauthId}" is already in use by another server; choose a different serverName`,+ })+ return+ }++ // Secret refs by mode (D-B3).+ let clientIdRef: { name: string; key: string }+ let clientSecretRef: { name: string; key: string }+ if (oauthInput.secret.mode === 'reference') {+ const verify = await verifyReferencedOAuthSecret(gateway, targetNs, oauthInput.secret)+ if (!verify.ok) {+ res.status(verify.status).json({ error: verify.error })+ return+ }+ clientIdRef = {+ name: oauthInput.secret.secretName,+ key: oauthInput.secret.clientIdKey,+ }+ clientSecretRef = {+ name: oauthInput.secret.secretName,+ key: oauthInput.secret.clientSecretKey,+ }+ } else {+ const oauthSecretName = `${serverName}-oauth-client`+ clientIdRef = { name: oauthSecretName, key: OAUTH_CLIENT_ID_KEY }+ clientSecretRef = { name: oauthSecretName, key: OAUTH_CLIENT_SECRET_KEY }+ managedOAuthSecret = {+ name: oauthSecretName,+ data: {+ [OAUTH_CLIENT_ID_KEY]: oauthInput.secret.clientId,+ [OAUTH_CLIENT_SECRET_KEY]: oauthInput.secret.clientSecret,+ },+ }+ }++ // The CRD couples auth.type=='oauth' iff spec.oauth is present and+ // forbids a static auth.secretRef alongside oauth.+ mcpServerSpec.auth = { type: 'oauth' }+ mcpServerSpec.oauth = {+ id: oauthId,+ provider,+ clientIdRef,+ clientSecretRef,+ scopes,+ grantScope,+ }+ }+ }+const preflightErrors = await validateMcpServerSpecPreflight(mcpServerSpec, {allowedImagePrefixes: config.allowedPluginImagePrefixes,enforceImageAllowlist: config.enforcePluginImageAllowlist,@@@ -1943,53 -2117,10 +2558,75 @@@}}+ // ── Step 3b: Create the managed OAuth client Secret (D-B3) ────────+ // Only for managed mode; reference mode was verified above and creates+ // nothing. Written before the CR that references it, and rolled back with- // the CR/context on any later failure.++ // the CR/context on any later failure via its snapshot (same UID/RV-fenced++ // mechanism dev uses for the envSecret) so a failed install leaves no++ // orphaned Secret (H-2/H-3).+ if (managedOAuthSecret) {+ const oauthSecretReq: SecretUpsertRequest = {+ name: managedOAuthSecret.name,+ namespace: targetNs,+ type: 'Opaque',+ labels: registryLabels,+ annotations: registryAnnotations,+ stringData: managedOAuthSecret.data,+ }+ try {- await gateway.createSecret(oauthSecretReq)++ createdOAuthClientSecretSnapshot = await gateway.createSecret(oauthSecretReq)+ } catch (err) {- // Roll back the envSecret created in Step 3 (if any) so a failed OAuth- // Secret write leaves nothing behind.- if (secretCreated) {++ // The OAuth client Secret write failed. Roll back the envSecret created++ // in Step 3 (if any) with the same identity-fenced helper dev uses for++ // credential rollback; a failed compensation escalates to++ // compensation_failed so the operator knows a Secret may be orphaned.++ let rollbackFailed = false++ if (createdSecretSnapshot) {+ try {- await gateway.deleteSecret(secretName, targetNs)++ await rollbackCreatedSecret(gateway, createdSecretSnapshot)+ } catch {- // Best-effort rollback; do not mask the original error.++ rollbackFailed = true+ }+ }++ if (rollbackFailed) {++ res.status(500).json({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return++ }+ const k8sErr = extractK8sError(err)- if (k8sErr) {++ if (k8sErr && k8sErr.status < 500) {+ res+ .status(k8sErr.status)+ .json({ error: `OAuth client Secret creation failed: ${k8sErr.message}` })+ return+ }- throw err++ // A create has no pre-write UID/RV to fence; its response cannot be++ // recovered into a compensable success, even if the named Secret later++ // looks like the requested intent.++ res.status(503).json({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ resourceName: managedOAuthSecret.name,++ resourceType: 'secret',++ namespace: targetNs,++ })++ return+ }- oauthClientSecretCreated = true+ // Key NAMES only; the client_id/client_secret VALUES are never logged.+ auditLog('oauth_client_secret_created', {+ secretName: managedOAuthSecret.name,+ namespace: targetNs,+ registryEntry: body.registryEntryName,+ credentialKeys: Object.keys(managedOAuthSecret.data),+ })+ }+- // ── Step 4: Create McpServer CRD (rollback Secret on failure) ─────+ // ── Step 4: Create McpServer CRD (rollback by UID on failure) ────+ let createdMcpServerSnapshot: RegistryResourceSnapshot | null = nulltry {- await gateway.createResource(+ const created = await gateway.createResource('mcpservers',{metadata: {@@@ -2001,23 -2132,50 +2638,60 @@@},targetNs)+ createdMcpServerSnapshot = normalizeRegistryResourceSnapshot(+ created,+ serverName,+ targetNs+ )+ if (+ !createdMcpServerSnapshot.metadata?.uid ||+ !createdMcpServerSnapshot.metadata.resourceVersion+ ) {+ throw new RegistryInstallRollbackError()+ }} catch (err) {- // Rollback: delete the Secret(s) if we created any- if (secretCreated) {+ const k8sErr = extractK8sError(err)+ if (+ err instanceof RegistryInstallRollbackError ||+ !isDeterministicRegistryNoCommit(err)+ ) {+ res.status(503).json({+ error: 'registry_resource_outcome_ambiguous',+ outcome: 'repair_required',+ resourceName: serverName,+ resourceType: 'mcp-server',+ namespace: targetNs,+ })+ return+ }++ // A deterministic create rejection proves there is no CR to- // compensate; only the earlier credential object needs rollback.++ // compensate; only the earlier credential objects need rollback++ // (the envSecret and the managed OAuth client Secret). Both are++ // fenced on their captured UID/RV, and a failed compensation++ // escalates to compensation_failed.+ let rollbackFailed = false+ if (createdSecretSnapshot) {try {- await gateway.deleteSecret(secretName, targetNs)+ await rollbackCreatedSecret(gateway, createdSecretSnapshot)} catch {- // Best-effort rollback; log but do not mask the original error+ rollbackFailed = true}}- if (oauthClientSecretCreated && managedOAuthSecret) {++ if (createdOAuthClientSecretSnapshot) {+ try {- await gateway.deleteSecret(managedOAuthSecret.name, targetNs)++ await rollbackCreatedSecret(gateway, createdOAuthClientSecretSnapshot)+ } catch {- // Best-effort rollback; log but do not mask the original error++ rollbackFailed = true+ }+ }- const k8sErr = extractK8sError(err)+ if (rollbackFailed) {+ res.status(500).json({+ error: 'registry_install_rollback_incomplete',+ outcome: 'compensation_failed',+ })+ return+ }if (k8sErr) {res.status(k8sErr.status).json({ error: k8sErr.message })return@@@ -2037,56 -2206,100 +2722,103 @@@mcpServers?: string[]}}+ contextBefore = normalizeRegistryResourceSnapshot(ctx, contextRef, contextsNs)+ if (!contextBefore.metadata?.uid || !contextBefore.metadata.resourceVersion) {+ throw Object.assign(new Error('Context identity is unavailable'), {+ statusCode: 503,+ code: 'context_identity_unavailable',+ })+ }const existing: string[] = ctx.spec?.mcpServers ?? []if (!existing.includes(serverName)) {- await gateway.updateResource('contexts', contextRef, {- spec: {- ...ctx.spec,- contextId: ctx.spec?.contextId ?? contextRef,- mcpServers: [...existing, serverName],- } as Record<string, unknown>,- })+ await gateway.updateResource(+ 'contexts',+ contextRef,+ {+ metadata: {+ uid: contextBefore.metadata.uid,+ ...(ctx.metadata?.resourceVersion+ ? { resourceVersion: ctx.metadata.resourceVersion }+ : {}),+ },+ spec: {+ ...ctx.spec,+ contextId: ctx.spec?.contextId ?? contextRef,+ mcpServers: [...existing, serverName],+ } as Record<string, unknown>,+ },+ contextsNs+ )}} catch (err) {- try {- await gateway.deleteResource('mcpservers', serverName, targetNs)- await waitForDeletion(- () => gateway.getResource('mcpservers', serverName, targetNs),- `McpServer/${serverName}`+ let associationOutcome: RegistryMutationOutcome = isDeterministicRegistryNoCommit(err)+ ? 'not-committed'+ : 'ambiguous'+ if (contextBefore && associationOutcome === 'ambiguous') {+ associationOutcome = await readRegistryAssociationOutcome(+ gateway,+ 'contexts',+ contextRef,+ contextsNs,+ contextBefore,+ spec =>+ Array.isArray(spec.mcpServers) &&+ (spec.mcpServers as unknown[]).includes(serverName))- } catch {- // Best-effort rollback; preserve the original context-update error.}- if (secretCreated) {- try {- await gateway.deleteSecret(secretName, targetNs)- await waitForDeletion(- () => gateway.getSecret(secretName, targetNs),- `Secret/${secretName}`- )- } catch {- // Best-effort rollback; preserve the original context-update error.- }+ if (contextBefore && associationOutcome === 'ambiguous') {+ res.status(503).json({+ error: 'registry_install_outcome_ambiguous',+ outcome: 'repair_required',+ resourceName: contextRef,+ resourceType: 'context',+ namespace: contextsNs,+ })+ return}- if (oauthClientSecretCreated && managedOAuthSecret) {+ if (associationOutcome !== 'committed') {+ let resourceRollbackFailed = falsetry {- await gateway.deleteSecret(managedOAuthSecret.name, targetNs)- await waitForDeletion(- () => gateway.getSecret(managedOAuthSecret.name, targetNs),- `Secret/${managedOAuthSecret.name}`+ await rollbackCreatedResource(+ gateway,+ 'mcpservers',+ createdMcpServerSnapshot!,+ `McpServer/${serverName}`)} catch {- // Best-effort rollback; preserve the original context-update error.+ resourceRollbackFailed = true+ }+ if (resourceRollbackFailed) {+ res.status(500).json({+ error: 'registry_install_rollback_incomplete',+ outcome: 'compensation_failed',+ })+ return}- if (createdSecretSnapshot) {++ if (createdSecretSnapshot || createdOAuthClientSecretSnapshot) {+ // The CR was live during this saga. There is no Kubernetes+ // transaction that atomically proves its absence and deletes a- // separately named Secret. Preserve the dependency for repair;- // deleting it after the CR rollback would permit a replacement- // CR to race into the same name and reference.++ // separately named Secret (the envSecret or the managed OAuth++ // client Secret). Preserve the dependency for repair; deleting it++ // after the CR rollback would permit a replacement CR to race into++ // the same name and reference. The compensation_failed 500 flags++ // the leftover Secret for the operator, so a failed install never++ // silently orphans one (H-2/H-3).+ res.status(500).json({+ error: 'registry_install_rollback_incomplete',+ outcome: 'compensation_failed',+ })+ return+ }+ const k8sErr = extractK8sError(err)+ const message =+ k8sErr?.message ||+ (err instanceof Error ? err.message : 'Failed to update Context allowlist')+ res+ .status(k8sErr?.status ?? 500)+ .json({ error: `Context allowlist update failed: ${message}` })+ return}- const k8sErr = extractK8sError(err)- const message =- k8sErr?.message ||- (err instanceof Error ? err.message : 'Failed to update Context allowlist')- res- .status(k8sErr?.status ?? 500)- .json({ error: `Context allowlist update failed: ${message}` })- return}// ── Step 6: Report install to registry (fire-and-forget) ──────────diff --cc control-api/src/routes/admin/resources.tsindex 512ed8988,8757580a5..0f664e563--- a/control-api/src/routes/admin/resources.ts+++ b/control-api/src/routes/admin/resources.ts@@@ -1027,126 -1090,123 +1099,234 @@@ export function createAdminResourcesRou}}+ // Capture the credential Secret identity BEFORE deleting the parent CR.+ // A same-name Secret can be created in the gap, and a name-addressed+ // delete afterwards would remove that replacement — a different owner's+ // object — on the strength of a decision made about something that no+ // longer exists. Every cleanup below is bound to the snapshot taken here.+ // Same reasoning, and same shape, as the registry uninstall path.+ const captureSecretForCleanup = async (+ secretName: string+ ): Promise<+ | { status: 'ready'; precondition: SecretPreconditions }+ | { status: 'absent' | 'recipe-owned' | 'identity-unavailable' | 'read-failed' }+ > => {+ let raw: unknown+ try {+ raw = await gateway.getSecret(secretName, ns)+ } catch (err) {+ if (extractK8sStatusCode(err) === 404) return { status: 'absent' }+ // Deleting the CR is the request's actual intent; the Secret is a+ // cascade. A failed read means we cannot fence the cascade delete, so+ // it is skipped and logged — the same policy this PR already applies+ // to the rollback paths ("rollback skipped: identity unavailable").+ // Failing the whole request here would leave the CR undeleted because+ // its dependent Secret could not be read.+ log.error(+ { secretName, namespace: ns, err },+ 'Secret cleanup capture failed; cascade delete will be skipped'+ )+ return { status: 'read-failed' }+ }+ // Recipe-owned Secrets belong to /admin/recipe-secrets. The mcp-secret+ // route refuses them with 409; deleting one here would route around+ // that guard.+ if (isRecipeOwnedSecret(raw)) return { status: 'recipe-owned' }+ const precondition = secretIdentityPreconditions(raw)+ if (!precondition) return { status: 'identity-unavailable' }+ return { status: 'ready', precondition }+ }++ const ccSecretCleanup =+ plural === 'communicationchannels' && ccSecretRefName+ ? await captureSecretForCleanup(ccSecretRefName)+ : null+ const mcpCredentialsSecretName = `${name}-credentials`+ const mcpSecretCleanup =+ plural === 'mcpservers' ? await captureSecretForCleanup(mcpCredentialsSecretName) : null++ // Pre-registered confidential remote installs create a `${name}-oauth-client`++ // Secret in the install saga with NO ownerReferences (it predates the CR), so++ // K8s GC never reaps it — control-api must delete it here. Fence it on the++ // identity captured BEFORE the CR delete, exactly like the credentials Secret:++ // a name-addressed delete could otherwise clobber a fresh same-name Secret++ // written by a concurrent reinstall in the gap (the bug this capture shape++ // exists to prevent). 'absent' (404) is the norm for non-pre-registered servers.++ const mcpOAuthClientSecretName = `${name}-oauth-client`++ const mcpOAuthClientSecretCleanup =++ plural === 'mcpservers' ? await captureSecretForCleanup(mcpOAuthClientSecretName) : null+const deleted = await gateway.deleteResource(plural, name, ns)- if (plural === 'communicationchannels' && ccSecretRefName) {- try {- await gateway.deleteSecret(ccSecretRefName, ns)- log.info(- { event: 'cc_credentials_secret_deleted', secretName: ccSecretRefName, namespace: ns },- 'deleted CC credentials secret'+ if (plural === 'communicationchannels' && ccSecretRefName && ccSecretCleanup) {+ if (ccSecretCleanup.status !== 'ready') {+ log.warn(+ { secretName: ccSecretRefName, namespace: ns, reason: ccSecretCleanup.status },+ 'Skipped CommunicationChannel credentials Secret cleanup')- } catch (err) {- if (extractK8sStatusCode(err) === 404) {+ } else {+ try {+ await gateway.deleteSecret(ccSecretRefName, ns, ccSecretCleanup.precondition)log.info(- { event: 'cc_credentials_secret_absent', secretName: ccSecretRefName, namespace: ns },- 'CC credentials secret already gone'- )- } else {- // CC is already gone; log and swallow so the operator gets a 200- // and can clean the orphan Secret manually if needed.- log.error(- {- event: 'cc_credentials_secret_cleanup_failed',- secretName: ccSecretRefName,- namespace: ns,- err,- },- 'CC delete succeeded but credentials secret cleanup failed'+ { secretName: ccSecretRefName, namespace: ns },+ 'Deleted CommunicationChannel credentials Secret')+ } catch (err) {+ if (extractK8sStatusCode(err) === 404) {+ log.info(+ { secretName: ccSecretRefName, namespace: ns },+ 'CommunicationChannel credentials Secret already gone'+ )+ } else {+ // CC is already gone; log and swallow so the operator gets a 200+ // and can clean the orphan Secret manually if needed.+ log.error(+ { secretName: ccSecretRefName, namespace: ns, err },+ 'CommunicationChannel delete succeeded but credentials cleanup failed'+ )+ }}}}if (plural === 'mcpservers') {const contextsNs = resourceNamespace('contexts')- try {- await gateway.deleteSecret(`${name}-credentials`, ns)- log.info(- { event: 'mcpserver_credentials_secret_deleted', name, namespace: ns },- 'deleted mcp-server credentials secret'- )- } catch (err) {- log.info(- { event: 'mcpserver_credentials_secret_absent', name, namespace: ns, err },- 'no mcp-server credentials secret to delete'+ if (mcpSecretCleanup && mcpSecretCleanup.status !== 'ready') {+ log.warn(+ {+ secretName: mcpCredentialsSecretName,+ namespace: ns,+ reason: mcpSecretCleanup.status,+ },+ 'Skipped MCP credentials Secret cleanup')+ } else if (mcpSecretCleanup) {+ try {+ await gateway.deleteSecret(mcpCredentialsSecretName, ns, mcpSecretCleanup.precondition)+ log.info(+ { secretName: mcpCredentialsSecretName, namespace: ns },+ 'Deleted MCP credentials Secret'+ )+ } catch (err) {+ if (extractK8sStatusCode(err) === 404) {+ log.info(+ { secretName: mcpCredentialsSecretName, namespace: ns },+ 'MCP credentials Secret already gone'+ )+ } else {+ // The McpServer is already gone, so a 200 is still the honest+ // outcome — but this is a cleanup FAILURE, not an absence. The+ // previous catch reported every error class, 403 included, as+ // "no Secret to delete", telling the operator a credential had+ // been removed while it was still live.+ log.error(+ { secretName: mcpCredentialsSecretName, namespace: ns, err },+ 'McpServer delete succeeded but credentials cleanup failed'+ )+ }+ }}- // Pre-registered confidential remote installs create a- // `${name}-oauth-client` Secret with no ownerReferences (created in the- // install saga before the CR exists, so K8s GC can't own it). Best-effort- // delete here so uninstall→reinstall doesn't 409 on the residual Secret- // and the client_secret doesn't linger. A 404 is expected for every- // non-pre-registered server; never fail the uninstall.- try {- await gateway.deleteSecret(`${name}-oauth-client`, ns)- log.info(- { event: 'mcpserver_oauth_client_secret_deleted', name, namespace: ns },- 'deleted mcp-server oauth client secret'- )- } catch (err) {- log.info(- { event: 'mcpserver_oauth_client_secret_absent', name, namespace: ns, err },- 'no mcp-server oauth client secret to delete'- )++ // Pre-registered confidential remote installs leave a `${name}-oauth-client`++ // Secret with no ownerReferences (see the capture above). Delete it fenced on++ // the identity captured before the CR delete; 'absent' (404) is expected for++ // every non-pre-registered server and never fails the uninstall.++ if (mcpOAuthClientSecretCleanup) {++ if (mcpOAuthClientSecretCleanup.status === 'ready') {++ try {++ await gateway.deleteSecret(++ mcpOAuthClientSecretName,++ ns,++ mcpOAuthClientSecretCleanup.precondition++ )++ log.info(++ { secretName: mcpOAuthClientSecretName, namespace: ns },++ 'Deleted MCP OAuth client Secret'++ )++ } catch (err) {++ if (extractK8sStatusCode(err) === 404) {++ log.info(++ { secretName: mcpOAuthClientSecretName, namespace: ns },++ 'MCP OAuth client Secret already gone'++ )++ } else {++ log.error(++ { secretName: mcpOAuthClientSecretName, namespace: ns, err },++ 'McpServer delete succeeded but OAuth client Secret cleanup failed'++ )++ }++ }++ } else if (mcpOAuthClientSecretCleanup.status === 'absent') {++ // Expected for every non-pre-registered server: no OAuth client Secret exists.++ log.info(++ { secretName: mcpOAuthClientSecretName, namespace: ns },++ 'No MCP OAuth client Secret to delete'++ )++ } else {++ log.warn(++ {++ secretName: mcpOAuthClientSecretName,++ namespace: ns,++ reason: mcpOAuthClientSecretCleanup.status,++ },++ 'Skipped MCP OAuth client Secret cleanup'++ )++ }+ }++ // Remote DCR client teardown (K, DEC-18): revoke the encrypted+ // `dynamic_clients` row (reliable) + best-effort RFC 7592 delete at the AS+ // (courtesy). Keyed per-server-CR; idempotent (0 rows ⇒ not a DCR server).+ // Never blocks or fails the uninstall — the CR is already deleted.+ try {+ const teardown = await cleanupDynamicClientForServer(+ dcrDb,+ oauthEncryptionKey,+ { logger: log },+ {+ ownerKind: 'mcpserver',+ serverNamespace: ns,+ serverName: name,+ }+ )+ if (teardown.localRowsDeleted > 0) {+ log.info(+ {- event: 'mcpserver_dynamic_client_revoked',- name,++ serverName: name,+ namespace: ns,+ attemptedRemoteDelete: teardown.attemptedRemoteDelete,+ },- 'revoked remote oauth dynamic client on uninstall'++ 'Revoked remote OAuth dynamic client on uninstall'+ )+ }+ } catch (err) {+ log.error(- { event: 'mcpserver_dynamic_client_cleanup_failed', name, namespace: ns, err },- 'dynamic client cleanup failed on uninstall (CR already deleted)'++ { serverName: name, namespace: ns, err },++ 'Dynamic client cleanup failed on uninstall (CR already deleted)'+ )+ }++ // Server teardown (DEC-R2): wipe ALL of this server's oauth_grants rows —+ // every user / context / client / flavor. Idempotent; never blocks the+ // uninstall (the CR is already deleted). This is NOT the per-user+ // revocation path — see deleteOAuthGrantsForServer.+ try {+ const purged = await deleteOAuthGrantsForServer(dcrDb, {+ recipeNamespace: ns,+ recipeName: name,+ })+ if (purged > 0) {+ log.info(- { event: 'mcpserver_oauth_grants_purged', name, namespace: ns, count: purged },- 'purged oauth grants on uninstall'++ { serverName: name, namespace: ns, count: purged },++ 'Purged OAuth grants on uninstall'+ )+ }+ } catch (err) {+ log.error(- { event: 'mcpserver_oauth_grants_purge_failed', name, namespace: ns, err },- 'oauth grants purge failed on uninstall (CR already deleted)'++ { serverName: name, namespace: ns, err },++ 'OAuth grants purge failed on uninstall (CR already deleted)'+ )+ }+try {const ctxList = (await gateway.listResource('contexts', contextsNs)) as Array<{metadata?: { name?: string }diff --cc control-api/src/routes/mcpOauth.tsindex ad8c7392e,d7368b0e6..22ade3f2a--- a/control-api/src/routes/mcpOauth.ts+++ b/control-api/src/routes/mcpOauth.ts@@@ -405,14 -376,9 +405,15 @@@ export function createMcpOauthRouter(gamaxPerMinute: config.oauthBrokerRlPerMin,getBucketKey: req => {const claims = req.res?.locals?.mcpHostControl as McpHostControlClaims | undefined- return claims ? `mcp-oauth:${claims.sub}` : 'mcp-oauth:unknown'+ // Standalone 1st-party hosts all share sub=<hostsNamespace>/standalone,+ // so keying by sub would collapse every standalone host into one bucket.+ // The verified principal keys standalone hosts by hostRefs[0] instead,+ // keeping each host isolated.+ return (+ mcpHostRateLimitBucketKey('mcp-oauth', claims, 'mcp-oauth:unknown') ?? 'mcp-oauth:unknown'+ )},+ onBackendUnavailable: 'process-memory',}),async (req, res, next) => {const claims = res.locals.mcpHostControl as McpHostControlClaims | undefined@@@ -575,14 -541,9 +576,15 @@@maxPerMinute: config.oauthBrokerRlPerMin,getBucketKey: req => {const claims = req.res?.locals?.mcpHostControl as McpHostControlClaims | undefined- return claims ? `mcp-oauth:${claims.sub}` : 'mcp-oauth:unknown'+ // Standalone 1st-party hosts all share sub=<hostsNamespace>/standalone,+ // so keying by sub would collapse every standalone host into one bucket.+ // The verified principal keys standalone hosts by hostRefs[0] instead,+ // keeping each host isolated.+ return (+ mcpHostRateLimitBucketKey('mcp-oauth', claims, 'mcp-oauth:unknown') ?? 'mcp-oauth:unknown'+ )},+ onBackendUnavailable: 'process-memory',}),async (req, res, next) => {const claims = res.locals.mcpHostControl as McpHostControlClaims | undefineddiff --cc control-api/test/db.oauthGrantsOwnerGeneralization.test.tsindex 83c56a4dc,30bdc76d0..10014c8fd--- a/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts+++ b/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts@@@ -21,7 -21,20 +21,31 @@@ describe('0101 oauth_grants owner generconst { CONTROL_API_MIGRATIONS } = await import('../src/db.js')const versions = CONTROL_API_MIGRATIONS.map(m => m.version)expect(versions).toContain('0106_oauth_grants_owner_generalization')- expect(versions.at(-1)).toBe('0117_dynamic_clients_runtime_access')+ // Ordering, not tail position: this test guards where 0106 sits relative to+ // its neighbours. Pinning `.at(-1)` asserted that the migration named there+ // is the last one that will ever exist, which every subsequent additive+ // migration breaks — 0116_mcp_secret_rollback_permits did.+ //+ // `indexOf` returns -1 for an absent version, and -1 is less than any real+ // index, so the ordering assertion alone would pass vacuously if the left+ // operand were dropped from the list. The two `toContain` assertions are the+ // liveness witness: they fail first if either version stops being registered.+ expect(versions).toContain('0108_llm_provider_attempts_sdk_link_on_delete_set_null')+ expect(versions).toContain('0116_mcp_secret_rollback_permits')+ expect(versions.indexOf('0108_llm_provider_attempts_sdk_link_on_delete_set_null')).toBeLessThan(+ versions.indexOf('0116_mcp_secret_rollback_permits')+ )++ // oauth-19 dynamic-clients pair, renumbered past dev's 0116 during the sync++ // (0116->0117 table, 0117->0118 runtime-access). Same liveness+ordering++ // guard so a future re-number or drop fails here first.++ expect(versions).toContain('0117_dynamic_clients_table')++ expect(versions).toContain('0118_dynamic_clients_runtime_access')++ expect(versions.indexOf('0116_mcp_secret_rollback_permits')).toBeLessThan(++ versions.indexOf('0117_dynamic_clients_table')++ )++ expect(versions.indexOf('0117_dynamic_clients_table')).toBeLessThan(++ versions.indexOf('0118_dynamic_clients_runtime_access')++ )expect(versions.indexOf('0100_seed_minimax_allowed_model')).toBeLessThan(versions.indexOf('0106_oauth_grants_owner_generalization'))diff --cc control-ui/app/constants/routes.tsindex 18d1aa1c3,260fe451e..976f4da21--- a/control-ui/app/constants/routes.ts+++ b/control-ui/app/constants/routes.ts@@@ -35,7 -35,7 +35,8 @@@ export const CONTROL_ROUTES =connectors: {root: '/connectors',new: '/connectors/new',+ remoteNew: '/connectors/remote/new',+ detail: (name: string) => `/connectors/${segment(name)}`,edit: (name: string) => `/connectors/${segment(name)}/edit`,editTab: (name: string, tab: string) => `/connectors/${segment(name)}/edit/${segment(tab)}`,},diff --cc control-ui/app/globals.cssindex 0ec8aa734,1b029d415..e4c2142c6--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@@ -14276,42 -14337,62 +14337,102 @@@ button.cu-gfs-tree__button:focus-visibldisplay: flex;}+/* ── Generic OAuth carril install wizard (S3-B4) ──────────────────────────── */+.cu-generic-field-row {+ display: flex;+ align-items: center;+ gap: var(--cu-space-2);+}++.cu-generic-field-row > :first-child {+ flex: 1;+ min-width: 0;+}++.cu-generic-origin {+ flex: none;+ white-space: nowrap;+}++.cu-generic-toggles {+ display: flex;+ flex-direction: column;+ gap: var(--cu-space-2);+}++.cu-generic-params {+ display: flex;+ flex-direction: column;+ gap: var(--cu-space-2);+}++.cu-generic-param-row {+ display: flex;+ align-items: center;+ gap: var(--cu-space-2);+}++.cu-generic-param-row > input {+ flex: 1;+ min-width: 0;+}+++ .cu-identity-preview__document {+ width: 100%;+ min-width: 0;+ }++ .cu-identity-preview__document > .cu-gfs-markdown-preview__content {+ width: 100%;+ max-width: none;+ margin: 0;+ }++ .cu-identity-preview--editable {+ cursor: pointer;+ }++ .cu-identity-preview--editable:hover {+ border-color: var(--cu-accent);+ }++ .eft-dialog.cu-identity-edit-dialog {+ width: 100%;+ max-width: min(96vw, 90rem);+ height: min(94vh, 64rem);+ max-height: calc(100vh - 2 * var(--cu-space-4));+ overflow: hidden;+ }++ .eft-dialog.cu-identity-edit-dialog .eft-dialog__content {+ display: flex;+ flex-direction: column;+ flex: 1;+ min-height: 0;+ }++ .eft-dialog.cu-identity-edit-dialog .eft-dialog__form {+ display: flex;+ flex-direction: column;+ flex: 1;+ min-height: 0;+ }++ @supports (height: 100dvh) {+ .eft-dialog.cu-identity-edit-dialog {+ max-height: calc(100dvh - 2 * var(--cu-space-4));+ }+ }++ @media (max-width: 40rem) {+ .eft-dialog.cu-identity-edit-dialog {+ height: calc(100vh - 2 * var(--cu-space-4));+ max-width: 100%;+ }++ @supports (height: 100dvh) {+ .eft-dialog.cu-identity-edit-dialog {+ height: calc(100dvh - 2 * var(--cu-space-4));+ }+ }+ }diff --cc deploy/scripts/control-api-runtime-access-profiles.tsvindex 087ca6c95,a2151d658..09fcf3ccd--- a/deploy/scripts/control-api-runtime-access-profiles.tsv+++ b/deploy/scripts/control-api-runtime-access-profiles.tsv@@@ -42,8 -42,8 +42,9 @@@ llm_model_prices legacy_dmllm_provider_attempt_tickets upsertllm_provider_attempts upsertmember_registration_credentials upsert+ mcp_secret_rollback_permits legacy_dmlnotification_deliveries legacy_dml+dynamic_clients legacy_dmloauth_grants legacy_dmlplugin_workload_sdk_credential_ticket_jtis legacy_dmlplugin_workload_sdk_invocation_attempts legacy_dml