Skip to content

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

TypeScript
134 KB
Raw Blame
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import { randomUUID } from 'node:crypto'
import request from 'supertest'
import { config } from '../src/config.js'
import type { DbClient, DbTransactionClient } from '../src/db.js'
import type { PinnedTransport } from '../src/http/pinnedFetch.js'
import type { K8sGateway } from '../src/k8s.js'
import {
  type DiscoveryOutcome,
  type DiscoveryResult,
  discoverRemoteOAuth,
} from '../src/oauth/discovery.js'
import {
  PENDING_TTL_MS,
  bindDynamicClientToResource,
  claimDeleteDynamicClientForResource,
  getDynamicClient,
  insertDynamicClientPending,
  reclaimOrphanDynamicClient,
} from '../src/oauth/dynamicClientStore.js'
import { decryptOAuthSecret, deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
import { probeMcpTransport } from '../src/oauth/mcpTransportProbe.js'
import { remoteCallbackVariant } from '../src/oauth/remoteCallback.js'
import {
  type AdminRemoteMcpDeps,
  createAdminRemoteMcpRouter,
} from '../src/routes/admin/remoteMcp.js'
import { K8sNotFoundError } from '../src/services/resourceService.js'
import {
  ATLASSIAN_V2_PILOT,
  DCR_BASIC_REGISTRATION_RESPONSE,
  DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,
  DCR_PUBLIC_REGISTRATION_RESPONSE,
  DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON,
  DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_RESPONSE,
  DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON,
  DCR_VERCEL_DOWNGRADE_REGISTRATION_RESPONSE,
  ENTRA_AGENT365_MAIL_PILOT,
  ENTRA_GRAPH_SCOPE_PILOT,
  ENTRA_NO_SCOPES_PILOT,
  ENTRA_SHAREPOINT_SCOPE_PILOT,
  ENTRA_UNKNOWN_GUID_PILOT,
  ENTRA_WORKIQ_PILOT,
  NOTION_PRM_JSON,
  PILOTS,
  type PilotFixture,
  VERCEL_PILOT,
  dcrPilot,
  makeDcrTransport,
  makeDiscoveryTransport,
  makeInMemoryDynamicClientsDb,
  workIqPilotWithPrm,
} from './fixtures/remoteOAuthDiscovery.js'
import { MockGateway } from './mockGateway.js'

/**
 * C1.5 "C-install" admin routes (spec 02, DEC-12). The saga is tested against a
 * MOCKED K8sGateway — the `remote`×`oauth` CR shape is not admissible until C3 lands
 * the CRD (batch model, §8), so live admission is out of scope here.
 *
 * Discovery is module-mocked, but the DiscoveryResult it returns is DERIVED FROM THE
 * REAL PRODUCER (T1): the actual `discoverRemoteOAuth` is run once against the real
 * 2026-09-20 probe fixtures to produce it — never hand-authored.
 */

// The kernel resolves the admin-typed baseUrl via node:dns; keep it public + offline.
vi.mock('node:dns/promises', () => ({
  lookup: vi.fn(async () => [{ address: '93.184.216.34', family: 4 }]),
}))

vi.mock('../src/oauth/discovery.js', async importActual => {
  const actual = await importActual<typeof import('../src/oauth/discovery.js')>()
  return { ...actual, discoverRemoteOAuth: vi.fn() }
})

const NS = config.mcpServersNamespace // 'mcp-server'

/** The two request fields the auth and correlation middlewares set in production. */
type UiAuthedRequestLike = { adminAuth?: { sub: string; jti: string }; log?: unknown }

// F1 collateral: the router now probes the MCP transport in BOTH discover and install.
// Every app injects a `probe` derived from the REAL producer (`probeMcpTransport` bound
// to a fixture transport) — never a hand-stubbed outcome — so no test escapes to the
// network. `GENERIC_ALIVE_TRANSPORT` mirrors the real pilots: a tokenless POST
// `initialize` answers 401 with a Bearer challenge (transport alive, token required).
const PROBE_DNS = async () => ['93.184.216.34']
const GENERIC_ALIVE_TRANSPORT: PinnedTransport = async ({ method }) =>
  method === 'POST'
    ? { status: 401, headers: { 'www-authenticate': 'Bearer realm="OAuth"' }, bodyText: '' }
    : { status: 404, headers: {}, bodyText: '' }

/** Bind the real `probeMcpTransport` to a fixture transport + offline DNS (T1). */
function boundProbe(transport: PinnedTransport): typeof probeMcpTransport {
  return (baseUrl, deps, opts) =>
    probeMcpTransport(baseUrl, { ...deps, transport, resolveDns: PROBE_DNS }, opts)
}
const genericProbe = boundProbe(GENERIC_ALIVE_TRANSPORT)
/** Vercel: POST `/mcp` → 404 (dead), POST `/` → 200, root PRM → suggested `/`. */
const vercelProbe = boundProbe(makeDiscoveryTransport(VERCEL_PILOT))
/** A 5xx POST → inconclusive/unexpected_status (must NOT block install). */
const inconclusiveProbe = boundProbe(async () => ({ status: 503, headers: {}, bodyText: '' }))

// Real Vercel DiscoveryResult, derived from the real producer (T1): the actual
// discovery client run against the 2026-09-25 Vercel probe fixtures.
let vercelResult: DiscoveryResult

function makeApp(
  gateway: MockGateway,
  probe: typeof probeMcpTransport = genericProbe,
  deps: AdminRemoteMcpDeps = {}
) {
  const app = express()
  app.use(express.json())
  app.use(createAdminRemoteMcpRouter(gateway as unknown as K8sGateway, { probe, ...deps }))
  app.use(
    (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
      res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })
    }
  )
  return app
}

/** Seed a Context in the gateway's default namespace (where the route reads it). */
function gatewayWithContext(contextName = 'ctx-a'): MockGateway {
  const gw = new MockGateway(NS)
  void gw.createResource(
    'contexts',
    { metadata: { name: contextName }, spec: { contextId: contextName } },
    NS
  )
  return gw
}

// Real DiscoveryResult, derived from the real Notion probe fixtures (T1). Notion's
// real AS metadata does NOT advertise RFC 9207 (see oauth.discovery.test.ts), so this
// carries NO `issForCallback` — the fixture the install must now REJECT (R3F-H1).
let notionResult: DiscoveryResult
// A DiscoveryResult that DOES advertise RFC 9207, derived from the real producer (T1)
// by documented substitution (like `bodyBearerResult`): the real Notion pilot with
// `authorization_response_iss_parameter_supported:true` added to the AS metadata, then
// run through the real discovery client so `issForCallback` is producer-derived, not
// hand-authored. Every remote install SUCCESS path needs an RFC-9207 AS now that the
// install guard is fail-closed; all other endpoints stay Notion's, so success-path
// assertions are unchanged except for the added `issForCallback`.
let rfc9207Result: DiscoveryResult
// A DiscoveryResult whose resource requires the token in the BODY, derived from the
// real producer (T1) by documented substitution of the Notion PRM's
// `bearer_methods_supported` to `["body"]` — the only field changed.
let bodyBearerResult: DiscoveryResult
// Real Linear DiscoveryResult (T1): the 2026-09-29 Linear probe advertises CIMD + `none`
// AND RFC 9207, so it still resolves to CIMD on the shared callback.
let linearResult: DiscoveryResult
// An AS that genuinely offers NO registration endpoint, derived from the real producer
// (T1) by documented subtraction: the real Linear pilot minus `registration_endpoint`.
// Linear keeps CIMD + RFC 9207, so discovery resolves to `cimd`, never `dcr`.
let noDcrResult: DiscoveryResult

/** Documented T1 subtraction: drop `registration_endpoint` from a pilot's AS metadata. */
function withoutRegistrationEndpoint<T extends { as: { json: string } }>(pilot: T): T {
  const as = JSON.parse(pilot.as.json)
  delete as.registration_endpoint
  return { ...pilot, as: { ...pilot.as, json: JSON.stringify(as) } }
}

/**
 * Documented T1 substitution: add `authorization_response_iss_parameter_supported`
 * to a pilot's AS metadata (parsed-object level, key-order agnostic) so the real
 * discovery producer derives `issForCallback`. Never hand-authors the DiscoveryResult.
 */
function withRfc9207<T extends { as: { json: string } }>(pilot: T): T {
  const as = JSON.parse(pilot.as.json)
  as.authorization_response_iss_parameter_supported = true
  return { ...pilot, as: { ...pilot.as, json: JSON.stringify(as) } }
}

beforeAll(async () => {
  const actual = await vi.importActual<typeof import('../src/oauth/discovery.js')>(
    '../src/oauth/discovery.js'
  )
  const outcome = await actual.discoverRemoteOAuth(PILOTS.notion.mcpUrl, {
    transport: makeDiscoveryTransport(PILOTS.notion),
    resolveDns: async () => ['93.184.216.34'],
  })
  if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)
  notionResult = outcome.result

  const rfc9207Outcome = await actual.discoverRemoteOAuth(PILOTS.notion.mcpUrl, {
    transport: makeDiscoveryTransport(withRfc9207(PILOTS.notion)),
    resolveDns: async () => ['93.184.216.34'],
  })
  if (!rfc9207Outcome.ok)
    throw new Error(`rfc9207 fixture discovery failed: ${rfc9207Outcome.error.kind}`)
  rfc9207Result = rfc9207Outcome.result

  const vercelOutcome = await actual.discoverRemoteOAuth(VERCEL_PILOT.mcpUrl, {
    transport: makeDiscoveryTransport(VERCEL_PILOT),
    resolveDns: async () => ['93.184.216.34'],
  })
  if (!vercelOutcome.ok)
    throw new Error(`vercel fixture discovery failed: ${vercelOutcome.error.kind}`)
  vercelResult = vercelOutcome.result

  // Documented substitution (like the DCR fixtures): the real Notion pilot with the
  // PRM's `bearer_methods_supported` set to body-only. The real producer then derives
  // `quirks.bearerInBody === true` — no hand-authored DiscoveryResult (T1).
  const bodyBearerPilot = {
    ...PILOTS.notion,
    prm: {
      ...PILOTS.notion.prm,
      json: NOTION_PRM_JSON.replace(
        '"bearer_methods_supported":["header"]',
        '"bearer_methods_supported":["body"]'
      ),
    },
  }
  const bodyBearerOutcome = await actual.discoverRemoteOAuth(bodyBearerPilot.mcpUrl, {
    transport: makeDiscoveryTransport(bodyBearerPilot),
    resolveDns: async () => ['93.184.216.34'],
  })
  if (!bodyBearerOutcome.ok)
    throw new Error(`body-bearer fixture discovery failed: ${bodyBearerOutcome.error.kind}`)
  bodyBearerResult = bodyBearerOutcome.result

  const linearOutcome = await actual.discoverRemoteOAuth(PILOTS.linear.mcpUrl, {
    transport: makeDiscoveryTransport(PILOTS.linear),
    resolveDns: async () => ['93.184.216.34'],
  })
  if (!linearOutcome.ok)
    throw new Error(`linear fixture discovery failed: ${linearOutcome.error.kind}`)
  linearResult = linearOutcome.result

  const noDcrOutcome = await actual.discoverRemoteOAuth(PILOTS.linear.mcpUrl, {
    transport: makeDiscoveryTransport(withoutRegistrationEndpoint(PILOTS.linear)),
    resolveDns: async () => ['93.184.216.34'],
  })
  if (!noDcrOutcome.ok)
    throw new Error(`no-DCR fixture discovery failed: ${noDcrOutcome.error.kind}`)
  noDcrResult = noDcrOutcome.result
})

beforeEach(() => {
  vi.mocked(discoverRemoteOAuth).mockReset()
})

function mockDiscovery(result: DiscoveryResult): void {
  vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result } as DiscoveryOutcome)
}

describe('POST /admin/mcp-servers/remote/discover (dry-run)', () => {
  it('kernel-rejects a non-https baseUrl → 400, no discovery', async () => {
    const gw = gatewayWithContext()
    const res = await request(makeApp(gw))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: 'http://mcp.notion.com/mcp' })
    expect(res.status).toBe(400)
    expect(discoverRemoteOAuth).not.toHaveBeenCalled()
  })

  it('returns the "Detected" prefill for a CIMD server (Linear: CIMD + RFC 9207) → 200', async () => {
    expect(linearResult.registrationMode).toBe('cimd')
    mockDiscovery(linearResult)
    const res = await request(makeApp(gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: 'https://mcp.linear.app/mcp' })
    expect(res.status).toBe(200)
    expect(res.body.detected.registrationMode).toBe('cimd')
    expect(res.body.detected.endpoints.token).toBe('https://mcp.linear.app/token')
    expect(res.body.detected.resource).toBe('https://mcp.linear.app/mcp')
    expect(res.body.detected.issForCallback).toBe('https://mcp.linear.app')
    expect(res.body.detected.quirks).toEqual({ bearerInBody: false, supportsRefresh: true })
    // No DCR marker for a CIMD server.
    expect(res.body.detected.dcr).toBeUndefined()
  })

  it('CIMD-capable AS WITHOUT RFC 9207 (Notion) is detected as DCR, not CIMD → 200', async () => {
    // Notion advertises CIMD + `none` but no `iss`: CIMD's single platform identity can
    // only list the shared callback, so discovery falls back to its registration endpoint.
    expect(notionResult.registrationMode).toBe('dcr')
    mockDiscovery(notionResult)
    const res = await request(makeApp(gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: 'https://mcp.notion.com/mcp' })
    expect(res.status).toBe(200)
    expect(res.body.detected.registrationMode).toBe('dcr')
    expect(res.body.detected.issForCallback).toBeUndefined()
    expect(res.body.detected.endpoints.token).toBe('https://mcp.notion.com/token')
    expect(res.body.detected.dcr).toEqual({
      available: true,
      clientMode: 'public',
      supportsRefresh: true,
    })
  })

  it('marks DCR mode available (C2) with resolved clientMode + supportsRefresh → 200', async () => {
    mockDiscovery({ ...notionResult, registrationMode: 'dcr' })
    const res = await request(makeApp(gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: 'https://mcp.example.com/mcp' })
    expect(res.status).toBe(200)
    expect(res.body.detected.registrationMode).toBe('dcr')
    // Notion's AS lists `none` in its auth methods → public DCR client.
    expect(res.body.detected.dcr).toEqual({
      available: true,
      clientMode: 'public',
      supportsRefresh: true,
    })
  })

  it('maps a discovery failure → 400', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({
      ok: false,
      error: { kind: 'no_s256', detail: 'no S256' },
    } as DiscoveryOutcome)
    const res = await request(makeApp(gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: 'https://mcp.example.com/mcp' })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('discovery_failed')
  })

  // Repro (issue 26-09-25): OAuth discovery resolves on Vercel's `/mcp` path, but the
  // MCP transport there is dead (404). Detect must surface a `dead` verdict + the
  // canonical-root suggestion WITHOUT changing the OAuth `detected` block.
  it('Vercel /mcp: discovery ok but the transport probe reports dead + suggests the root → 200', async () => {
    mockDiscovery(vercelResult)
    const res = await request(makeApp(gatewayWithContext(), vercelProbe))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: 'https://mcp.vercel.com/mcp' })
    expect(res.status).toBe(200)
    // OAuth `detected` is unchanged: the path-suffixed PRM resource is what fooled Detect.
    expect(res.body.detected.resource).toBe('https://mcp.vercel.com/mcp')
    // The new sibling: transport probe verdict.
    expect(res.body.transport).toEqual({
      status: 'dead',
      probedUrl: 'https://mcp.vercel.com/mcp',
      httpStatus: 404,
      suggestedBaseUrl: 'https://mcp.vercel.com/',
    })
  })

  it('Notion /mcp: transport probe reports alive with a challenge → 200', async () => {
    mockDiscovery(notionResult)
    const res = await request(makeApp(gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: 'https://mcp.notion.com/mcp' })
    expect(res.status).toBe(200)
    expect(res.body.transport.status).toBe('alive')
    expect(res.body.transport.challenge).toBe(true)
  })
})

describe('POST /admin/mcp-servers/remote (install saga)', () => {
  // CIMD now backfills `oauth.id` from the platform self-URL (DEC-23), which needs
  // a configured public callback base URL — same precondition DCR already has.
  let savedCallbackBaseUrl = ''
  beforeEach(() => {
    savedCallbackBaseUrl = config.oauthCallbackBaseUrl
    config.oauthCallbackBaseUrl = 'https://control.example.com'
  })
  afterEach(() => {
    config.oauthCallbackBaseUrl = savedCallbackBaseUrl
  })

  const CIMD_SELF_CLIENT_ID = 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client'

  it('CIMD (public): creates the CR with the pinned spec.oauth shape + attaches to Context', async () => {
    mockDiscovery(rfc9207Result)
    const gw = gatewayWithContext('ctx-a')
    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'notion-remote',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'cimd',
    })
    expect(res.status).toBe(201)
    expect(res.body).toMatchObject({
      serverName: 'notion-remote',
      namespace: NS,
      clientMode: 'public',
      registrationMode: 'cimd',
    })
    // No secret material echoed.
    expect(res.body.clientSecret).toBeUndefined()

    const cr = (await gw.getResource('mcpservers', 'notion-remote', NS)) as {
      spec: Record<string, unknown>
    }
    expect(cr.spec.auth).toEqual({ type: 'oauth' })
    expect(cr.spec.remote).toEqual({ baseUrl: 'https://mcp.notion.com/mcp' })
    expect(cr.spec.oauth).toEqual({
      source: 'remote',
      // DEC-23: CIMD-public backfills the platform self-URL client_id.
      id: CIMD_SELF_CLIENT_ID,
      clientMode: 'public',
      authorizationEndpoint: 'https://mcp.notion.com/authorize',
      tokenEndpoint: 'https://mcp.notion.com/token',
      registrationEndpoint: 'https://mcp.notion.com/register',
      issuer: 'https://mcp.notion.com',
      // RFC 9207 advertised (rfc9207Result) ⇒ pinned for the shared remote callback.
      issForCallback: 'https://mcp.notion.com',
      resource: 'https://mcp.notion.com',
      grantScope: 'user',
      scopes: ['default'],
      bearerInBody: false,
      supportsRefresh: true,
    })

    // Context now allowlists the server.
    const ctx = (await gw.getResource('contexts', 'ctx-a', NS)) as {
      spec: { mcpServers?: string[] }
    }
    expect(ctx.spec.mcpServers).toContain('notion-remote')
  })

  // Before the per-server callback, an AS without RFC 9207 was refused outright (422
  // `issuer_binding_required`, R3F-H1): the shared callback has no mix-up defence without
  // `iss`. Now such an install proceeds on a redirect URI of the server's own. A
  // pre-registered client gets `/remote/<serverName>` (no nonce: the client is
  // confidential and its secret dies with the CR), returned so the operator can register
  // it. `notionResult` is the REAL Notion discovery (no RFC 9207).
  it('pre-registered against an AS without RFC 9207 → 201 on a per-server redirect URI', async () => {
    expect(notionResult.issForCallback).toBeUndefined()
    mockDiscovery(notionResult)
    const gw = gatewayWithContext('ctx-a')
    const { db } = makeInMemoryDynamicClientsDb()

    const res = await request(makeApp(gw, genericProbe, { db }))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'no-rfc9207-remote',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'pre-registered',
        clientId: 'client-abc',
        clientSecret: 'fixture-client-secret',
      })

    expect(res.status).toBe(201)
    expect(res.body.callbackVariant).toBe('per-server')
    expect(res.body.redirectUri).toBe(
      'https://control.example.com/api/v1/oauth-callback/remote/no-rfc9207-remote'
    )
    const cr = (await gw.getResource('mcpservers', 'no-rfc9207-remote', NS)) as {
      spec: { oauth: Record<string, unknown> }
    }
    expect(cr.spec.oauth.issForCallback).toBeUndefined()
    expect(cr.spec.oauth.id).toBe('client-abc')
    const ctx = (await gw.getResource('contexts', 'ctx-a', NS)) as {
      spec: { mcpServers?: string[] }
    }
    expect(ctx.spec.mcpServers).toContain('no-rfc9207-remote')
  })

  // The CIMD identity lists only the shared callback, so a CIMD install on an AS without
  // RFC 9207 stays refused. Discovery never resolves `cimd` there; this mutant of its
  // real output (Notion, no RFC 9207, mode forced to `cimd`) stands for a regression in
  // mode selection, which the defensive gate must still stop before any write.
  it('CIMD against an AS without RFC 9207 (mode-selection regression) → 422, no CR', async () => {
    expect(notionResult.issForCallback).toBeUndefined()
    mockDiscovery({ ...notionResult, registrationMode: 'cimd' })
    const gw = gatewayWithContext('ctx-a')
    const createResourceSpy = vi.spyOn(gw, 'createResource')
    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'cimd-no-iss',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'cimd',
    })
    expect(res.status).toBe(422)
    expect(res.body.error).toBe('issuer_binding_required')
    expect(createResourceSpy).not.toHaveBeenCalled()
  })

  it('body-bearer resource: rejects at admission and creates no CR (the runtime cannot honor bearerInBody)', async () => {
    // Self-check the T1 fixture: the real producer must have derived the body-bearer
    // quirk, or this test would pass vacuously against any server.
    expect(bodyBearerResult.quirks.bearerInBody).toBe(true)
    mockDiscovery(bodyBearerResult)
    const gw = gatewayWithContext('ctx-a')
    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'notion-remote',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'cimd',
    })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('bearer_in_body_unsupported')

    // No CR persisted, and the Context is not mutated: the install failed closed.
    await expect(gw.getResource('mcpservers', 'notion-remote', NS)).rejects.toBeDefined()
    const ctx = (await gw.getResource('contexts', 'ctx-a', NS)) as {
      spec: { mcpServers?: string[] }
    }
    expect(ctx.spec.mcpServers ?? []).not.toContain('notion-remote')
  })

  it('pre-registered confidential: creates the client Secret + references it in spec.oauth', async () => {
    mockDiscovery(rfc9207Result)
    const gw = gatewayWithContext('ctx-a')
    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'slack-remote',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'pre-registered',
      clientId: 'client-abc',
      clientSecret: 'shhh-secret',
    })
    expect(res.status).toBe(201)
    expect(res.body.clientMode).toBe('confidential')

    // getSecret returns the base64 `data` map (K8s materializes write-only
    // stringData into data on apply), so decode before comparing plaintext.
    const secret = (await gw.getSecret('slack-remote-oauth-client', NS)) as {
      data?: Record<string, string>
    }
    const decoded = Object.fromEntries(
      Object.entries(secret.data ?? {}).map(([k, v]) => [
        k,
        Buffer.from(v, 'base64').toString('utf8'),
      ])
    )
    expect(decoded).toEqual({ client_id: 'client-abc', client_secret: 'shhh-secret' })

    const cr = (await gw.getResource('mcpservers', 'slack-remote', NS)) as {
      spec: { oauth: Record<string, unknown> }
    }
    expect(cr.spec.oauth.clientMode).toBe('confidential')
    // DEC-23: pre-registered backfills `oauth.id` from the operator's plaintext client_id.
    expect(cr.spec.oauth.id).toBe('client-abc')
    expect(cr.spec.oauth.clientIdRef).toEqual({
      name: 'slack-remote-oauth-client',
      key: 'client_id',
    })
    expect(cr.spec.oauth.clientSecretRef).toEqual({
      name: 'slack-remote-oauth-client',
      key: 'client_secret',
    })
  })

  it('rejects mode "dcr" when server-side discovery resolves a non-DCR AS → 400 mode_unsupported', async () => {
    // The AS offers CIMD but no registration endpoint; the operator's "dcr" request loses.
    expect(noDcrResult.endpoints.registration).toBeUndefined()
    expect(noDcrResult.registrationMode).toBe('cimd')
    mockDiscovery(noDcrResult)
    const gw = gatewayWithContext('ctx-a')
    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'stripe-remote',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.linear.app/mcp',
      mode: 'dcr',
    })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('mode_unsupported')
    // No CR written.
    await expect(gw.getResource('mcpservers', 'stripe-remote', NS)).rejects.toThrow()
  })

  it('pre-registered without clientSecret → 400', async () => {
    const gw = gatewayWithContext('ctx-a')
    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'x-remote',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'pre-registered',
      clientId: 'only-id',
    })
    expect(res.status).toBe(400)
  })

  it('CIMD requested but AS is DCR-only → 400 mode_unsupported (server-side discovery is authoritative)', async () => {
    mockDiscovery({ ...notionResult, registrationMode: 'dcr' })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'y-remote',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.example.com/mcp',
      mode: 'cimd',
    })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('mode_unsupported')
  })

  it('rolls back the Secret when the CR create fails', async () => {
    mockDiscovery(rfc9207Result)
    const gw = gatewayWithContext('ctx-a')
    const k8sErr = Object.assign(new Error('already exists'), { code: 409 })
    vi.spyOn(gw, 'createResource').mockRejectedValueOnce(k8sErr)
    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'roll-remote',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'pre-registered',
      clientId: 'cid',
      clientSecret: 'csecret',
    })
    expect(res.status).toBe(409)
    // The client Secret created before the CR must be rolled back.
    await expect(gw.getSecret('roll-remote-oauth-client', NS)).rejects.toThrow()
  })

  it('rolls back the CR AND Secret when the Context attach fails', async () => {
    mockDiscovery(rfc9207Result)
    // Context does NOT exist → getResource('contexts', …) throws K8sNotFoundError.
    const gw = new MockGateway(NS)
    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'attach-remote',
      contextRef: 'missing-ctx',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'pre-registered',
      clientId: 'cid',
      clientSecret: 'csecret',
    })
    expect(res.status).toBeGreaterThanOrEqual(400)
    // Both the CR and the Secret are rolled back.
    await expect(gw.getResource('mcpservers', 'attach-remote', NS)).rejects.toThrow()
    await expect(gw.getSecret('attach-remote-oauth-client', NS)).rejects.toThrow()
  })

  it('fenced Secret rollback: a homonym recreated with a NEW uid survives the CR-create rollback (P1)', async () => {
    mockDiscovery(rfc9207Result)
    const gw = gatewayWithContext('ctx-a')
    const secretName = 'race-remote-oauth-client'

    // Force step-2 (CR create) to fail, but first simulate a concurrent
    // uninstall+reinstall of the same serverName: delete the just-created client
    // Secret and recreate a homonym carrying a DIFFERENT uid. `createSecret` is
    // the real producer (T1) — the mock's allocateUid is monotonic, so the
    // recreated Secret's uid necessarily differs from the one the saga captured.
    let recreatedUid: string | undefined
    vi.spyOn(gw, 'createResource').mockImplementationOnce(async () => {
      await gw.deleteSecret(secretName, NS)
      const recreated = await gw.createSecret({
        name: secretName,
        namespace: NS,
        type: 'Opaque',
        stringData: { client_id: 'other-tenant', client_secret: 'other-secret' },
      })
      recreatedUid = recreated.uid
      throw Object.assign(new Error('already exists'), { code: 409 })
    })

    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'race-remote',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'pre-registered',
      clientId: 'cid',
      clientSecret: 'csecret',
    })

    expect(res.status).toBe(409)
    // The homonym belongs to the concurrent install: the fenced rollback's uid
    // precondition rejects the delete (409, swallowed best-effort), so the other
    // tenant's credentials survive intact. A by-name rollback would raze them.
    const survivor = await gw.getSecret(secretName, NS)
    expect(survivor.metadata.uid).toBe(recreatedUid)
  })

  it('fenced CR rollback: a homonym recreated with a NEW uid survives the Context-attach rollback (P1)', async () => {
    mockDiscovery(rfc9207Result)
    const gw = gatewayWithContext('ctx-a')
    const serverName = 'race2-remote'

    // Let the CR create succeed, then fail the Context attach (updateResource).
    // Between the two, simulate a concurrent uninstall+reinstall that replaces
    // the McpServer CR with a homonym carrying a NEW uid (createResource is the
    // real producer, T1). A by-name rollback would delete the wrong object.
    let recreatedCrUid: string | undefined
    vi.spyOn(gw, 'updateResource').mockImplementationOnce(async () => {
      await gw.deleteResource('mcpservers', serverName, NS)
      const recreated = (await gw.createResource(
        'mcpservers',
        { metadata: { name: serverName }, spec: { image: 'other' } },
        NS
      )) as { metadata: { uid: string } }
      recreatedCrUid = recreated.metadata.uid
      // Not a 409: the attach re-reads and retries on a conflict (the Context status
      // subresource moves its resourceVersion), so only a non-retryable failure
      // reaches the compensation this test is about.
      throw Object.assign(new Error('context write failed'), { code: 500 })
    })

    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName,
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'pre-registered',
      clientId: 'cid',
      clientSecret: 'csecret',
    })

    expect(res.status).toBeGreaterThanOrEqual(400)
    // The recreated CR (a different uid) must survive: the fenced deleteResource
    // precondition rejects the compensating delete instead of razing it.
    const survivor = (await gw.getResource('mcpservers', serverName, NS)) as {
      metadata: { uid: string }
    }
    expect(survivor.metadata.uid).toBe(recreatedCrUid)
  })

  it('forces the namespace server-side (caller-supplied namespace is ignored)', async () => {
    mockDiscovery(rfc9207Result)
    const gw = gatewayWithContext('ctx-a')
    const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
      serverName: 'ns-remote',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'cimd',
      namespace: 'attacker-ns',
    })
    expect(res.status).toBe(201)
    expect(res.body.namespace).toBe(NS)
    // Created in the config namespace, nothing in the attacker-supplied one.
    await expect(gw.getResource('mcpservers', 'ns-remote', NS)).resolves.toBeTruthy()
    await expect(gw.getResource('mcpservers', 'ns-remote', 'attacker-ns')).rejects.toThrow()
  })

  it('rejects a metadata.namespace that disagrees with the server namespace → 400', async () => {
    mockDiscovery(notionResult)
    const gw = gatewayWithContext('ctx-a')
    const res = await request(makeApp(gw))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'md-remote',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'cimd',
        metadata: { namespace: 'evil' },
      })
    expect(res.status).toBe(400)
  })

  // Repro (issue 26-09-25, T3+T4): a Vercel `/mcp` install passes OAuth discovery (mode
  // dcr) but the transport there is dead (404). The hard gate must return 400
  // `transport_unreachable` BEFORE minting any AS client or writing K8s — observable:
  // no DCR POST, no CR, Context allowlist untouched.
  it('Vercel /mcp install (dcr): transport probe dead → 400 transport_unreachable, nothing minted or written', async () => {
    mockDiscovery(vercelResult)
    const { db } = makeInMemoryDynamicClientsDb()
    const { transport: dcrTransport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
    })
    const gw = gatewayWithContext('ctx-a')
    const app = express()
    app.use(express.json())
    app.use(
      createAdminRemoteMcpRouter(gw as unknown as K8sGateway, {
        db,
        dcr: { transport: dcrTransport, resolveDns: PROBE_DNS },
        probe: vercelProbe,
      })
    )
    const res = await request(app).post('/admin/mcp-servers/remote').send({
      serverName: 'vercel-remote',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.vercel.com/mcp',
      mode: 'dcr',
    })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('transport_unreachable')
    expect(res.body.detail).toMatchObject({
      probedUrl: 'https://mcp.vercel.com/mcp',
      httpStatus: 404,
      suggestedBaseUrl: 'https://mcp.vercel.com/',
    })
    // No AS client minted (the DCR POST never fired).
    expect(calls).toHaveLength(0)
    // No CR written.
    await expect(gw.getResource('mcpservers', 'vercel-remote', NS)).rejects.toThrow()
    // Context allowlist untouched.
    const ctx = (await gw.getResource('contexts', 'ctx-a', NS)) as {
      spec: { mcpServers?: string[] }
    }
    expect(ctx.spec.mcpServers ?? []).not.toContain('vercel-remote')
  })

  // An inconclusive probe (5xx) must NOT block: the install proceeds to 201.
  it('install proceeds to 201 when the transport probe is inconclusive (5xx)', async () => {
    mockDiscovery(rfc9207Result)
    const gw = gatewayWithContext('ctx-a')
    const res = await request(makeApp(gw, inconclusiveProbe))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'inconclusive-remote',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'cimd',
      })
    expect(res.status).toBe(201)
    // The CR was written despite the inconclusive probe.
    await expect(gw.getResource('mcpservers', 'inconclusive-remote', NS)).resolves.toBeTruthy()
  })
})

// ─── C2: DCR install saga (spec 02 C2, DEC-18/DEC-19) ───────────────────────
describe('POST /admin/mcp-servers/remote — DCR install saga (C2)', () => {
  const ENC_KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
  const PUBLIC_IP = async () => ['93.184.216.34']
  // The DCR request needs a configured public callback origin for redirect_uris.
  let savedCallbackBaseUrl: string
  // Origin the live Vercel DCR captures were registered under (their echoed redirect_uris).
  const CAPTURED_DCR_ORIGIN = 'http://127.0.0.1:8090'

  // Real DCR DiscoveryResults, DERIVED FROM THE REAL PRODUCER by documented
  // subtraction (DEC-19): the actual discovery client is run against the Notion
  // probe with CIMD support removed (→ DCR) and, for confidential, `none` dropped.
  let dcrPublicResult: DiscoveryResult
  let dcrConfidentialResult: DiscoveryResult
  // Real DCR DiscoveryResult WITHOUT RFC 9207 (pristine `dcrPilot`, no substitution):
  // the fixture the install must reject before any AS registration (R3F-H1).
  let dcrNoIssResult: DiscoveryResult

  beforeAll(async () => {
    const actual = await vi.importActual<typeof import('../src/oauth/discovery.js')>(
      '../src/oauth/discovery.js'
    )
    const noIssPilot = dcrPilot('public')
    const noIssOutcome = await actual.discoverRemoteOAuth(noIssPilot.mcpUrl, {
      transport: makeDiscoveryTransport(noIssPilot),
      resolveDns: PUBLIC_IP,
    })
    if (!noIssOutcome.ok)
      throw new Error(`dcr no-iss fixture discovery failed: ${noIssOutcome.error.kind}`)
    expect(noIssOutcome.result.issForCallback).toBeUndefined()
    dcrNoIssResult = noIssOutcome.result

    for (const [mode, assign] of [
      ['public', (r: DiscoveryResult) => (dcrPublicResult = r)],
      ['confidential', (r: DiscoveryResult) => (dcrConfidentialResult = r)],
    ] as const) {
      // RFC 9207 is mandatory for a remote install (R3F-H1); a DCR AS that omits it
      // is rejected before registration. Add the advertisement via the same
      // producer-derived substitution so the DCR success paths exercise the saga.
      const pilot = withRfc9207(dcrPilot(mode))
      const outcome = await actual.discoverRemoteOAuth(pilot.mcpUrl, {
        transport: makeDiscoveryTransport(pilot),
        resolveDns: PUBLIC_IP,
      })
      if (!outcome.ok) throw new Error(`dcr fixture discovery failed: ${outcome.error.kind}`)
      expect(outcome.result.registrationMode).toBe('dcr')
      expect(outcome.result.issForCallback).toBeTruthy()
      assign(outcome.result)
    }
  })

  beforeEach(() => {
    vi.mocked(discoverRemoteOAuth).mockReset()
    savedCallbackBaseUrl = config.oauthCallbackBaseUrl
    config.oauthCallbackBaseUrl = 'https://control.example.com'
  })

  afterEach(() => {
    config.oauthCallbackBaseUrl = savedCallbackBaseUrl
  })

  function makeAppWithDeps(gateway: MockGateway, deps: AdminRemoteMcpDeps) {
    const app = express()
    app.use(express.json())
    // Inject the generic-alive probe by default (F1 collateral: DCR installs baseUrl
    // mcp.notion.com/mcp, which probes alive); a test may override via `deps.probe`.
    app.use(
      createAdminRemoteMcpRouter(gateway as unknown as K8sGateway, { probe: genericProbe, ...deps })
    )
    app.use(
      (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
        res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })
      }
    )
    return app
  }

  // Before the per-server callback, a DCR AS without RFC 9207 was refused before
  // registering (422, R3F-H1). Now the client registers a redirect URI of this
  // installation's own — `/remote/<serverName>/<installId>` — and the install succeeds.
  // `dcrNoIssResult` is producer-derived (no iss), T1; the AS echoes what we POSTed.
  it('DCR against an AS without RFC 9207 → 201, registers /remote/<name>/<installId>', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrNoIssResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
      redirectUris: 'requested',
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'no-rfc9207-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })

    expect(res.status).toBe(201)
    expect(res.body.callbackVariant).toBe('per-server')
    const stored = [...rows.values()][0]
    expect(res.body.redirectUri).toBe(
      `https://control.example.com/api/v1/oauth-callback/remote/no-rfc9207-dcr/${stored.install_id}`
    )
    // The one DCR POST registered exactly the URI the install reports.
    const posts = calls.filter(c => c.method === 'POST')
    expect(posts).toHaveLength(1)
    expect(JSON.parse(posts[0].body ?? '{}').redirect_uris).toEqual([res.body.redirectUri])
    await expect(gw.getResource('mcpservers', 'no-rfc9207-dcr', NS)).resolves.toBeTruthy()
  })

  // T3(a) — fails at parent 9e4677652: DCR install returns 400 dcr_not_available there.
  it('public DCR → 201, persists a dynamic_clients row, sets spec.oauth.id, no Secret refs', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrPublicResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'notion-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(201)
    expect(res.body).toMatchObject({
      serverName: 'notion-dcr',
      clientMode: 'public',
      registrationMode: 'dcr',
    })
    // A dynamic_clients row was persisted.
    expect(rows.size).toBe(1)
    const stored = [...rows.values()][0]
    expect(stored.client_id).toBe(DCR_PUBLIC_REGISTRATION_RESPONSE.client_id)
    // Public → no secret persisted.
    expect(stored.client_secret_encrypted).toBeNull()

    const cr = (await gw.getResource('mcpservers', 'notion-dcr', NS)) as {
      spec: { oauth: Record<string, unknown> }
    }
    expect(cr.spec.oauth.id).toBe(DCR_PUBLIC_REGISTRATION_RESPONSE.client_id)
    expect(cr.spec.oauth.clientMode).toBe('public')
    // The C4 discriminator: DCR omits the K8s Secret refs.
    expect(cr.spec.oauth.clientIdRef).toBeUndefined()
    expect(cr.spec.oauth.clientSecretRef).toBeUndefined()
  })

  // T3(a)+T3(c) — fails at parent: no row, no encrypted envelope.
  it('confidential DCR → 201, NO K8s Secret, secret persisted as an encrypted envelope', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'vercel-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(201)
    expect(res.body.clientMode).toBe('confidential')

    // DEC-8: a DCR-confidential client gets NO K8s Secret — the secret lives in the store.
    await expect(gw.getSecret('vercel-dcr-oauth-client', NS)).rejects.toThrow()

    // T3(c): the stored secret is an encrypted envelope, never plaintext, and it
    // decrypts back to the registration secret.
    const stored = [...rows.values()][0]
    const secretEnc = stored.client_secret_encrypted as string
    expect(secretEnc).not.toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.client_secret)
    expect(secretEnc.startsWith('v1.')).toBe(true)
    expect(decryptOAuthSecret(ENC_KEY, secretEnc)).toBe(
      DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.client_secret
    )
    // The RFC 7592 registration_access_token is also stored encrypted.
    const regEnc = stored.registration_access_token_encrypted as string
    expect(regEnc.startsWith('v1.')).toBe(true)
    expect(decryptOAuthSecret(ENC_KEY, regEnc)).toBe(
      DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_access_token
    )

    const cr = (await gw.getResource('mcpservers', 'vercel-dcr', NS)) as {
      spec: { oauth: Record<string, unknown> }
    }
    expect(cr.spec.oauth.id).toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.client_id)
    expect(cr.spec.oauth.clientMode).toBe('confidential')
    expect(cr.spec.oauth.clientSecretRef).toBeUndefined()
  })

  // Regression: the AS DOWNGRADES a confidential request to public (Vercel). The
  // effective auth method (`none`, no secret) must win end to end — persisted and
  // written to the CR as a PUBLIC client. Fails at parent 054c62c7: the DCR guard
  // anchored on the REQUESTED method, so this returned 400 dcr_registration_failed.
  it('confidential-requested DCR that the AS downgrades to public (Vercel) → 201 as PUBLIC, no secret persisted', async () => {
    // `dcrConfidentialResult` has no `none` in its AS auth methods, so the install
    // derives confidential a-priori and requests `client_secret_post` — exactly what
    // triggered the Vercel downgrade in production.
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    // The captured body echoes the redirect URI registered under the dev origin it was
    // captured with; the shared variant rejects an echo that differs from the request,
    // so the install runs under that same origin.
    config.oauthCallbackBaseUrl = CAPTURED_DCR_ORIGIN
    const { transport } = makeDcrTransport({
      responseJson: DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON,
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'vercel-downgrade-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(201)
    // The AS is authoritative: the client persists and reports as PUBLIC.
    expect(res.body.clientMode).toBe('public')

    // A public client stores NO secret envelope.
    const stored = [...rows.values()][0]
    expect(stored.client_mode).toBe('public')
    expect(stored.client_id).toBe(DCR_VERCEL_DOWNGRADE_REGISTRATION_RESPONSE.client_id)
    expect(stored.client_secret_encrypted).toBeNull()

    // No DCR-confidential K8s Secret exists (there is no Secret for DCR at all).
    await expect(gw.getSecret('vercel-downgrade-dcr-oauth-client', NS)).rejects.toThrow()

    const cr = (await gw.getResource('mcpservers', 'vercel-downgrade-dcr', NS)) as {
      spec: { oauth: Record<string, unknown> }
    }
    expect(cr.spec.oauth.clientMode).toBe('public')
    expect(cr.spec.oauth.id).toBe(DCR_VERCEL_DOWNGRADE_REGISTRATION_RESPONSE.client_id)
    // Public → resolves via PKCE + `oauth.id`, no Secret refs (mirrors ClickUp).
    expect(cr.spec.oauth.clientIdRef).toBeUndefined()
    expect(cr.spec.oauth.clientSecretRef).toBeUndefined()
  })

  // Security: a PUBLIC assignment (`none`) that ALSO echoes a client_secret must
  // classify public and DISCARD the secret — never persist it. Observable result:
  // the stored row is public with a NULL secret envelope.
  it('public DCR where the AS echoes a stray client_secret → 201 public, secret DISCARDED (not persisted)', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrPublicResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    // The captured body echoes the redirect URI registered under the dev origin it was
    // captured with; the shared variant rejects an echo that differs from the request,
    // so the install runs under that same origin.
    config.oauthCallbackBaseUrl = CAPTURED_DCR_ORIGIN
    const { transport } = makeDcrTransport({
      responseJson: DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON,
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'echoed-secret-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(201)
    expect(res.body.clientMode).toBe('public')

    const stored = [...rows.values()][0]
    expect(stored.client_mode).toBe('public')
    expect(stored.client_id).toBe(DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_RESPONSE.client_id)
    // The echoed secret is discarded — no envelope persisted.
    expect(stored.client_secret_encrypted).toBeNull()

    const cr = (await gw.getResource('mcpservers', 'echoed-secret-dcr', NS)) as {
      spec: { oauth: Record<string, unknown> }
    }
    expect(cr.spec.oauth.clientMode).toBe('public')
    expect(cr.spec.oauth.clientSecretRef).toBeUndefined()
  })

  // T3(b) — fails at parent ffb2005: the minted-but-rejected auth_method_unsupported
  // error carried no RFC 7592 handle there, so NO cleanup DELETE was attempted.
  it('confidential DCR where the AS assigns client_secret_basic → 400 auth_method_unsupported, cleans up the minted client', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_BASIC_REGISTRATION_RESPONSE),
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'basic-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('auth_method_unsupported')
    // Fail-closed: no row persisted, no CR written.
    expect(rows.size).toBe(0)
    await expect(gw.getResource('mcpservers', 'basic-dcr', NS)).rejects.toThrow()
    // The AS DID mint a client (2xx + client_id) before we rejected the auth method —
    // a best-effort RFC 7592 DELETE against its management endpoint was attempted.
    const deleteCall = calls.find(c => c.method === 'DELETE')
    expect(deleteCall?.url).toBe(DCR_BASIC_REGISTRATION_RESPONSE.registration_client_uri)
    expect(deleteCall?.headers.authorization).toBe(
      `Bearer ${DCR_BASIC_REGISTRATION_RESPONSE.registration_access_token}`
    )
  })

  it('rolls back the dynamic client (local delete + best-effort RFC 7592 DELETE) when the CR create fails', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    const gw = gatewayWithContext('ctx-a')
    const k8sErr = Object.assign(new Error('already exists'), { code: 409 })
    vi.spyOn(gw, 'createResource').mockRejectedValueOnce(k8sErr)
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'rollback-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(409)
    // Local store row deleted.
    expect(rows.size).toBe(0)
    // Best-effort RFC 7592 DELETE against the management endpoint was attempted.
    const deleteCall = calls.find(c => c.method === 'DELETE')
    expect(deleteCall?.url).toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri)
    expect(deleteCall?.headers.authorization).toBe(
      `Bearer ${DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_access_token}`
    )
  })

  // T3(a) — fails at parent ffb2005: the persist had no try/catch there, so the
  // upsert throw unwound to a 500 with NO cleanup of the just-minted AS client.
  it('cleans up the minted client and returns 503 when the local persist throws', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db: baseDb, rows } = makeInMemoryDynamicClientsDb()
    // Inject a store whose INSERT rejects (e.g. pool exhausted / encryption error).
    // DELETE still routes to the in-memory store so the idempotent local revocation
    // runs (the row never landed → 0 rows removed).
    const db = {
      query: async (text: string, values: unknown[] = []) => {
        if (text.includes('INSERT INTO dynamic_clients')) throw new Error('pool exhausted')
        return baseDb.query(text, values)
      },
    } as unknown as typeof baseDb
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'persistfail-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    // Transient/server-side, not a client error.
    expect(res.status).toBe(503)
    expect(res.body.error).toBe('dcr_persist_failed')
    // No dynamic_clients row remains (the INSERT rejected; nothing orphaned locally).
    expect(rows.size).toBe(0)
    // The AS client minted before the persist failed was cleaned up: a best-effort
    // RFC 7592 DELETE against its management endpoint was attempted.
    const deleteCall = calls.find(c => c.method === 'DELETE')
    expect(deleteCall?.url).toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri)
    expect(deleteCall?.headers.authorization).toBe(
      `Bearer ${DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_access_token}`
    )
    // The CR was never created (we aborted before the saga's step-2).
    await expect(gw.getResource('mcpservers', 'persistfail-dcr', NS)).rejects.toThrow()
  })

  it('rolls back the dynamic client when the Context attach fails', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    // Context exists at the step-0 precheck, then the ATTACH update fails.
    const gw = gatewayWithContext('ctx-a')
    vi.spyOn(gw, 'updateResource').mockRejectedValueOnce(new Error('attach boom'))
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'attach-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBeGreaterThanOrEqual(400)
    expect(rows.size).toBe(0)
    expect(calls.some(c => c.method === 'DELETE')).toBe(true)
    // The CR minted before attach is rolled back too.
    await expect(gw.getResource('mcpservers', 'attach-dcr', NS)).rejects.toThrow()
  })

  it('DCR with an unconfigured public callback base URL → 503, nothing registered', async () => {
    config.oauthCallbackBaseUrl = ''
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrPublicResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'unconfigured-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(503)
    expect(res.body.error).toBe('callback_base_url_unconfigured')
    // Fail-closed BEFORE any registration POST.
    expect(calls).toHaveLength(0)
    expect(rows.size).toBe(0)
  })

  it('DCR against a missing Context → 404 before minting a throwaway client', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrPublicResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
    })
    const gw = new MockGateway(NS) // no Context seeded
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'noctx-dcr',
        contextRef: 'missing-ctx',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(404)
    // No registration POST fired; no row persisted.
    expect(calls).toHaveLength(0)
    expect(rows.size).toBe(0)
  })

  // ── R3-H1: install identity fences the DCR row writes ──────────────────────
  // The install saga must NEVER clobber or delete a live server's dynamic_clients
  // row. Rows are seeded via the REAL producers (insertDynamicClientPending + bind),
  // read through the REAL getDynamicClient (T1).

  /** Every persisted column; `ageMs` is a read-time measurement, not row state. */
  const rowState = (row: Awaited<ReturnType<typeof getDynamicClient>>) => {
    if (!row) return row
    const { ageMs: _ageMs, ...state } = row
    return state
  }

  const LIVE_ROW = {
    ownerKind: 'mcpserver' as const,
    serverNamespace: NS,
    issuer: 'https://as.example.com',
    clientId: 'live-client-id',
    clientMode: 'confidential' as const,
    clientSecret: 'live-secret',
    registrationAccessToken: 'live-reg-token',
    registrationClientUri: 'https://as.example.com/register/live',
  }

  // T4/invariant-1 (R3-H1): installing a name already held by a LIVE McpServer must
  // leave that install's row byte-identical and mint NOTHING at the AS. Fails at
  // parent 6938afbd3: with no pre-check and the old clobbering upsert, the CR-create
  // 409 rolls back and DELETEs the (now overwritten) row → the row is gone and the
  // error is the create 409, not `server_name_in_use`.
  it('install over a live McpServer of the same name → 409 server_name_in_use, live row untouched, nothing minted', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const seededInstall = randomUUID()
    await insertDynamicClientPending(db, ENC_KEY, {
      ...LIVE_ROW,
      serverName: 'live-dcr',
      installId: seededInstall,
    })
    await bindDynamicClientToResource(
      db,
      { serverNamespace: NS, serverName: 'live-dcr' },
      seededInstall,
      'uid-live-cr'
    )
    const before = await getDynamicClient(db, ENC_KEY, {
      serverNamespace: NS,
      serverName: 'live-dcr',
    })

    const gw = gatewayWithContext('ctx-a')
    await gw.createResource('mcpservers', { metadata: { name: 'live-dcr' }, spec: {} }, NS)

    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'live-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })

    expect(res.status).toBe(409)
    expect(res.body.error).toBe('server_name_in_use')
    // Pre-check short-circuits BEFORE discovery/mint: no AS interaction at all.
    expect(calls).toHaveLength(0)
    // The live row is byte-identical — never clobbered, never deleted (R3-H1).
    const after = await getDynamicClient(db, ENC_KEY, {
      serverNamespace: NS,
      serverName: 'live-dcr',
    })
    expect(rowState(after)).toEqual(rowState(before))
    expect(rows.size).toBe(1)
  })

  // The INSERT fence itself (not the pre-check): a live CR that appears AFTER the
  // pre-check but before the persist (TOCTOU) is caught by the ON CONFLICT + classify
  // `in-use`. The row stays byte-identical; the throwaway client we minted is revoked.
  it('TOCTOU: a live CR appears after the pre-check → 409 server_name_in_use via the INSERT fence, row untouched', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db } = makeInMemoryDynamicClientsDb()
    const seededInstall = randomUUID()
    await insertDynamicClientPending(db, ENC_KEY, {
      ...LIVE_ROW,
      serverName: 'toctou-dcr',
      installId: seededInstall,
    })
    await bindDynamicClientToResource(
      db,
      { serverNamespace: NS, serverName: 'toctou-dcr' },
      seededInstall,
      'uid-toctou-cr'
    )
    const before = await getDynamicClient(db, ENC_KEY, {
      serverNamespace: NS,
      serverName: 'toctou-dcr',
    })

    const gw = gatewayWithContext('ctx-a')
    const realGet = gw.getResource.bind(gw)
    let mcpReads = 0
    vi.spyOn(gw, 'getResource').mockImplementation(async (plural, name, ns) => {
      if (plural === 'mcpservers' && name === 'toctou-dcr') {
        mcpReads += 1
        // First read is the pre-check (name still free); the CR appears by the time
        // the INSERT conflicts and we re-read the live uid for classification.
        if (mcpReads === 1) throw new K8sNotFoundError('mcpservers/toctou-dcr not found')
        return { metadata: { uid: 'uid-toctou-cr' } }
      }
      return realGet(plural, name, ns)
    })

    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'toctou-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })

    expect(res.status).toBe(409)
    expect(res.body.error).toBe('server_name_in_use')
    // The row we seeded is untouched (the INSERT never clobbered it).
    const after = await getDynamicClient(db, ENC_KEY, {
      serverNamespace: NS,
      serverName: 'toctou-dcr',
    })
    expect(rowState(after)).toEqual(rowState(before))
    // The throwaway client minted before the conflict was revoked at the AS, and the
    // seeded live client's handle was NOT touched.
    const deleteCalls = calls.filter(c => c.method === 'DELETE')
    expect(deleteCalls.map(c => c.url)).toContain(
      DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri
    )
    expect(deleteCalls.map(c => c.url)).not.toContain(LIVE_ROW.registrationClientUri)
  })

  // Regression guard for the class fix: a transient throw in the conflict-resolution
  // block (here the live-uid re-read) must STILL revoke the client we just minted —
  // otherwise a confidential client is orphaned at the AS. Before the fix this path
  // propagated to a 500 with zero 7592 DELETEs (reproduced by review).
  it('a transient error while classifying a name conflict still revokes the minted client', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db } = makeInMemoryDynamicClientsDb()
    // Seed a fresh pending row so the install's INSERT conflicts and we enter the
    // classify path (which re-reads the live uid).
    await insertDynamicClientPending(db, ENC_KEY, {
      ...LIVE_ROW,
      serverName: 'throwrevoke-dcr',
      installId: randomUUID(),
    })

    const gw = gatewayWithContext('ctx-a')
    const realGet = gw.getResource.bind(gw)
    let mcpReads = 0
    vi.spyOn(gw, 'getResource').mockImplementation(async (plural, name, ns) => {
      if (plural === 'mcpservers' && name === 'throwrevoke-dcr') {
        mcpReads += 1
        // 1st read = pre-check (name free → proceed to mint + INSERT conflict);
        // 2nd read = the conflict re-read of the live uid → transient non-404 error.
        if (mcpReads === 1) throw new K8sNotFoundError('mcpservers/throwrevoke-dcr not found')
        throw Object.assign(new Error('apiserver unavailable'), { code: 500 })
      }
      return realGet(plural, name, ns)
    })

    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'throwrevoke-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })

    // The transient error surfaces (not swallowed), but the minted client is revoked.
    expect(res.status).toBe(500)
    const deleteCalls = calls.filter(c => c.method === 'DELETE')
    expect(deleteCalls.map(c => c.url)).toContain(
      DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri
    )
  })

  // A fresh pending row (another saga of the same name in flight) → 409
  // install_in_progress; the in-flight row is untouched and our throwaway client is
  // revoked.
  it('install over a fresh pending row → 409 install_in_progress, in-flight row untouched', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const inflightInstall = randomUUID()
    await insertDynamicClientPending(db, ENC_KEY, {
      ...LIVE_ROW,
      serverName: 'inprogress-dcr',
      clientId: 'inflight-client-id',
      installId: inflightInstall,
    })
    const before = await getDynamicClient(db, ENC_KEY, {
      serverNamespace: NS,
      serverName: 'inprogress-dcr',
    })

    const gw = gatewayWithContext('ctx-a') // no McpServer seeded → pre-check passes
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    const res = await request(
      makeAppWithDeps(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'inprogress-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })

    expect(res.status).toBe(409)
    expect(res.body.error).toBe('install_in_progress')
    // The in-flight row is untouched (its install still owns it).
    const after = await getDynamicClient(db, ENC_KEY, {
      serverNamespace: NS,
      serverName: 'inprogress-dcr',
    })
    expect(rowState(after)).toEqual(rowState(before))
    expect(rows.size).toBe(1)
    // Our throwaway minted client was revoked at the AS.
    expect(calls.some(c => c.method === 'DELETE')).toBe(true)
  })

  // An orphan row (bound to a uid with no live CR) does NOT block a reinstall: it is
  // reclaimed (CAS in a tx), the OLD client is revoked, and the install proceeds to 201.
  it('install over a reclaimable orphan → reclaims the row, revokes the old client, 201', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const orphanInstall = randomUUID()
    await insertDynamicClientPending(db, ENC_KEY, {
      ...LIVE_ROW,
      serverName: 'reclaim-dcr',
      clientId: 'orphan-client-id',
      installId: orphanInstall,
    })
    // Bound to a uid whose CR no longer exists → orphan (reclaimable, no live CR).
    await bindDynamicClientToResource(
      db,
      { serverNamespace: NS, serverName: 'reclaim-dcr' },
      orphanInstall,
      'uid-orphan-gone'
    )

    const gw = gatewayWithContext('ctx-a') // no live McpServer → orphan is reclaimable
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    const res = await request(
      makeAppWithDeps(gw, {
        db,
        dcr: { transport, resolveDns: PUBLIC_IP },
        // The reclaim opens a tx; bind it to the same in-memory db.
        runInTransaction: work => work(db as unknown as DbTransactionClient),
      })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'reclaim-dcr',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })

    expect(res.status).toBe(201)
    // Still exactly one row, now owned by the new install (minted client_id).
    expect(rows.size).toBe(1)
    const owned = await getDynamicClient(db, ENC_KEY, {
      serverNamespace: NS,
      serverName: 'reclaim-dcr',
    })
    expect(owned?.clientId).toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.client_id)
    // The OLD (orphan) client was revoked at the AS via its handle read under the lock.
    const deleteCalls = calls.filter(c => c.method === 'DELETE')
    expect(deleteCalls.map(c => c.url)).toContain(LIVE_ROW.registrationClientUri)
  })

  // ── The live-uid read must follow the LAST row read ─────────────────────────
  // Install A of the same name finishes (CR created, row bound) while B is resolving
  // its INSERT conflict. The hook below plays A's steps with the REAL producers
  // (gateway createResource + bindDynamicClientToResource) at the exact point in B's
  // flow under test. Asserted on what is observable: A's client is never revoked at
  // the AS and A's row is byte-identical. The status is 409 either way, so it does
  // not discriminate.

  const RACE_A_ROW = {
    ...LIVE_ROW,
    clientId: 'owner-a-client-id',
    clientSecret: 'owner-a-secret',
    registrationAccessToken: 'owner-a-reg-token',
    registrationClientUri: 'https://as.example.com/register/owner-a',
  }

  /**
   * Wrap the in-memory db so hooks run around B's Nth plain row read
   * (`getDynamicClient`), counted only once armed: `before` effects are visible to
   * that read, `after` effects land once its snapshot is taken.
   */
  function withRowReadHook(
    inner: DbClient,
    plan: Record<number, { before?: () => Promise<void>; after?: () => Promise<void> }>
  ): { db: DbClient; arm: () => void } {
    let armed = false
    let reads = 0
    const db = {
      query: async (text: string, values?: unknown[]) => {
        const isRowRead =
          armed &&
          text.includes('FROM dynamic_clients') &&
          !text.includes('UPDATE') &&
          !text.includes('DELETE') &&
          !text.includes('FOR UPDATE')
        if (!isRowRead) return inner.query(text, values)
        reads += 1
        const step = plan[reads]
        await step?.before?.()
        const result = await inner.query(text, values)
        await step?.after?.()
        return result
      },
    } as unknown as DbClient
    return { db, arm: () => (armed = true) }
  }

  const rowKey = (serverName: string) => `mcpserver/${NS}/${serverName}`

  /**
   * Age a real row past the pending TTL. Only `updated_at` moves (what the store's
   * age column measures); every other column stays as the producer wrote it.
   */
  function expirePending(rows: Map<string, Record<string, unknown>>, serverName: string): void {
    const row = rows.get(rowKey(serverName))
    if (!row) throw new Error(`no row for ${serverName}`)
    row.updated_at = new Date(Date.now() - PENDING_TTL_MS - 60_000)
  }

  /**
   * A's CR appears (real gateway create) and A binds its row to that CR's uid.
   * Returns A's row as persisted right after the bind — the state that must survive.
   */
  async function ownerAFinishes(
    gw: MockGateway,
    inner: DbClient,
    serverName: string,
    installA: string
  ) {
    const cr = (await gw.createResource(
      'mcpservers',
      { metadata: { name: serverName }, spec: {} },
      NS
    )) as { metadata: { uid: string } }
    const bound = await bindDynamicClientToResource(
      inner,
      { serverNamespace: NS, serverName },
      installA,
      cr.metadata.uid
    )
    if (!bound.bound) throw new Error('owner A failed to bind its row')
    return rowState(await getDynamicClient(inner, ENC_KEY, { serverNamespace: NS, serverName }))
  }

  async function installB(gw: MockGateway, db: DbClient, serverName: string) {
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    const res = await request(
      makeAppWithDeps(gw, {
        db,
        dcr: { transport, resolveDns: PUBLIC_IP },
        runInTransaction: work => work(db as unknown as DbTransactionClient),
      })
    )
      .post('/admin/mcp-servers/remote')
      .send({
        serverName,
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    return { res, deleteUrls: calls.filter(c => c.method === 'DELETE').map(c => c.url) }
  }

  it("A binds its row between B's row read and B's live-CR read → A's client is never revoked, A's row untouched", async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db: inner, rows } = makeInMemoryDynamicClientsDb()
    const serverName = 'race-bind-dcr'
    const installA = randomUUID()
    await insertDynamicClientPending(inner, ENC_KEY, {
      ...RACE_A_ROW,
      serverName,
      installId: installA,
    })
    // A's saga has been slow: B reads a pending row already past the TTL.
    expirePending(rows, serverName)

    const gw = gatewayWithContext('ctx-a')
    let aState: Awaited<ReturnType<typeof ownerAFinishes>> | undefined
    const { db, arm } = withRowReadHook(inner, {
      1: {
        after: async () => {
          aState = await ownerAFinishes(gw, inner, serverName, installA)
        },
      },
    })
    arm()
    const { res, deleteUrls } = await installB(gw, db, serverName)

    expect(res.status).toBe(409)
    expect(aState).toBeDefined()
    expect(deleteUrls).not.toContain(RACE_A_ROW.registrationClientUri)
    // B still revokes the throwaway client it minted.
    expect(deleteUrls).toContain(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri)
    const afterA = await getDynamicClient(inner, ENC_KEY, { serverNamespace: NS, serverName })
    expect(rowState(afterA)).toEqual(aState)
  })

  // A finishes (CR created, row bound) before B even reads the row. The row B reads
  // is already bound, so only a live-CR read taken AFTER that row read can tell it
  // is in use; with the K8s read first, B sees no CR, classifies the bound row as an
  // orphan, and its reclaim guard matches the row it just read.
  it("A binds its row before B's row read → B's live-CR read follows it, A's client is never revoked", async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db: inner, rows } = makeInMemoryDynamicClientsDb()
    const serverName = 'race-prebind-dcr'
    const installA = randomUUID()
    await insertDynamicClientPending(inner, ENC_KEY, {
      ...RACE_A_ROW,
      serverName,
      installId: installA,
    })
    expirePending(rows, serverName)

    const gw = gatewayWithContext('ctx-a')
    let aState: Awaited<ReturnType<typeof ownerAFinishes>> | undefined
    const { db, arm } = withRowReadHook(inner, {
      1: {
        before: async () => {
          aState = await ownerAFinishes(gw, inner, serverName, installA)
        },
      },
    })
    arm()
    const { res, deleteUrls } = await installB(gw, db, serverName)

    expect(res.status).toBe(409)
    expect(aState).toBeDefined()
    expect(deleteUrls).not.toContain(RACE_A_ROW.registrationClientUri)
    expect(deleteUrls).toContain(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri)
    const afterA = await getDynamicClient(inner, ENC_KEY, { serverNamespace: NS, serverName })
    expect(rowState(afterA)).toEqual(aState)
  })

  // Same race through the retry branch: B's first row read finds the row gone (a
  // teardown), A reinstalls the name before B's retried INSERT, and A creates its CR
  // and binds before B's second row read.
  it("retry branch: A reinserts and binds before B's re-read → A's client is never revoked, A's row untouched", async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db: inner } = makeInMemoryDynamicClientsDb()
    const serverName = 'race-retry-dcr'
    // The row B's INSERT first conflicts with: an orphan of an earlier install.
    const orphanInstall = randomUUID()
    await insertDynamicClientPending(inner, ENC_KEY, {
      ...LIVE_ROW,
      serverName,
      installId: orphanInstall,
    })
    await bindDynamicClientToResource(
      inner,
      { serverNamespace: NS, serverName },
      orphanInstall,
      'uid-orphan-gone'
    )

    const gw = gatewayWithContext('ctx-a')
    const installA = randomUUID()
    let aState: Awaited<ReturnType<typeof ownerAFinishes>> | undefined
    const { db, arm } = withRowReadHook(inner, {
      // B's first read finds the orphan torn down; A then claims the name again,
      // ahead of B's retried INSERT.
      1: {
        before: async () => {
          await claimDeleteDynamicClientForResource(
            inner,
            ENC_KEY,
            { serverNamespace: NS, serverName },
            'uid-orphan-gone'
          )
        },
        after: async () => {
          await insertDynamicClientPending(inner, ENC_KEY, {
            ...RACE_A_ROW,
            serverName,
            installId: installA,
          })
        },
      },
      // A creates its CR and binds before B re-reads the row.
      2: {
        before: async () => {
          aState = await ownerAFinishes(gw, inner, serverName, installA)
        },
      },
    })
    arm()
    const { res, deleteUrls } = await installB(gw, db, serverName)

    expect(res.status).toBe(409)
    expect(aState).toBeDefined()
    expect(deleteUrls).not.toContain(RACE_A_ROW.registrationClientUri)
    expect(deleteUrls).toContain(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri)
    const afterA = await getDynamicClient(inner, ENC_KEY, { serverNamespace: NS, serverName })
    expect(rowState(afterA)).toEqual(aState)
  })

  // ── Saga step 2b: compensations of the bind phase ───────────────────────────
  // Each failure after the CR create must undo the CR, OUR pending row and OUR minted
  // AS client — and nothing else. Asserted on observable state: the gateway store, the
  // dynamic_clients rows, and the RFC 7592 DELETEs the AS received.

  const MINTED_URI = DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri

  async function installDcr(gw: MockGateway, db: DbClient, serverName: string) {
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
    })
    const res = await request(
      makeAppWithDeps(gw, {
        db,
        dcr: { transport, resolveDns: PUBLIC_IP },
        runInTransaction: work => work(db as unknown as DbTransactionClient),
      })
    )
      .post('/admin/mcp-servers/remote')
      .send({ serverName, contextRef: 'ctx-a', baseUrl: 'https://mcp.notion.com/mcp', mode: 'dcr' })
    return { res, deleteUrls: calls.filter(c => c.method === 'DELETE').map(c => c.url) }
  }

  // Unreachable in production (the apiserver always assigns a uid); tested as the
  // defensive branch it is. The REAL gateway create runs and stores the CR, so "CR
  // absent" proves the rollback deleted it — only the returned value loses its uid.
  it('bind phase, created CR without uid → 503 dcr_bind_failed; CR, own row and minted client undone', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const serverName = 'bind-nouid-dcr'
    const gw = gatewayWithContext('ctx-a')
    const realCreate = gw.createResource.bind(gw)
    vi.spyOn(gw, 'createResource').mockImplementation(async (plural, body, namespace) => {
      const created = (await realCreate(plural, body, namespace)) as {
        metadata: Record<string, unknown>
      }
      if (plural !== 'mcpservers') return created
      const { uid: _uid, ...metadata } = created.metadata
      return { ...created, metadata }
    })

    const { res, deleteUrls } = await installDcr(gw, db, serverName)

    expect(res.status).toBe(503)
    expect(res.body.error).toBe('dcr_bind_failed')
    await expect(gw.getResource('mcpservers', serverName, NS)).rejects.toThrow()
    expect(rows.has(rowKey(serverName))).toBe(false)
    expect(deleteUrls).toEqual([MINTED_URI])
  })

  it('bind phase, bind UPDATE throws → error propagates; CR, own row and minted client undone', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db: inner, rows } = makeInMemoryDynamicClientsDb()
    const serverName = 'bind-throws-dcr'
    // Only the bind statement (`SET cr_uid = $5`) rejects; every other statement —
    // including the compensation DELETE — reaches the in-memory store.
    const db = {
      query: async (text: string, values?: unknown[]) => {
        if (text.includes('UPDATE dynamic_clients') && text.includes('SET cr_uid = $5')) {
          throw new Error('bind boom')
        }
        return inner.query(text, values)
      },
    } as unknown as DbClient
    const gw = gatewayWithContext('ctx-a')

    const { res, deleteUrls } = await installDcr(gw, db, serverName)

    // The route rethrows; the app's error handler maps it to a 500 with the message.
    expect(res.status).toBe(500)
    expect(res.body.error).toBe('bind boom')
    await expect(gw.getResource('mcpservers', serverName, NS)).rejects.toThrow()
    expect(rows.has(rowKey(serverName))).toBe(false)
    expect(deleteUrls).toEqual([MINTED_URI])
  })

  // The pending row expires and another install reclaims it between our CR create and
  // our bind. The reclaim is played by the REAL producer (`reclaimOrphanDynamicClient`
  // with the `observed` identity read through the real `getDynamicClient`) from the
  // gateway's create hook — i.e. after the CR exists, before the bind runs.
  it('bind phase, row reclaimed before bind → 503 install_superseded; CR undone, reclaimer row byte-identical', async () => {
    vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result: dcrConfidentialResult })
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const serverName = 'bind-lost-dcr'
    const key = { serverNamespace: NS, serverName }
    const gw = gatewayWithContext('ctx-a')
    let reclaimerState: ReturnType<typeof rowState> | undefined
    gw.setResourceCreateFault(async ({ plural }) => {
      if (plural !== 'mcpservers') return
      expirePending(rows, serverName)
      const observed = await getDynamicClient(db, ENC_KEY, key)
      if (!observed) throw new Error('no pending row to reclaim')
      const { reclaimed } = await reclaimOrphanDynamicClient(
        ENC_KEY,
        {
          key,
          newCredentials: { ...RACE_A_ROW, serverName },
          newInstallId: randomUUID(),
          observed,
        },
        work => work(db as unknown as DbTransactionClient)
      )
      if (!reclaimed) throw new Error('reclaim did not apply')
      reclaimerState = rowState(await getDynamicClient(db, ENC_KEY, key))
    })

    const { res, deleteUrls } = await installDcr(gw, db, serverName)

    expect(res.status).toBe(503)
    expect(res.body.error).toBe('install_superseded')
    expect(reclaimerState).toBeDefined()
    await expect(gw.getResource('mcpservers', serverName, NS)).rejects.toThrow()
    expect(rowState(await getDynamicClient(db, ENC_KEY, key))).toEqual(reclaimerState)
    expect(deleteUrls).toEqual([MINTED_URI])
  })
})

// ─── Per-server callback for an AS without RFC 9207 ─────────────────────────
describe('POST /admin/mcp-servers/remote — per-server callback (AS without RFC 9207)', () => {
  const PUBLIC_IP = async () => ['93.184.216.34']
  const ORIGIN = 'https://control.example.com'
  /** ORIGIN as a literal inside a RegExp (its dots must not match any character). */
  const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  const CIMD_SELF_CLIENT_ID = `${ORIGIN}/api/v1/.well-known/evenfire-mcp-client`
  const ATLASSIAN_REGISTRATION =
    'https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3/dcr/register'
  const NONCE_RE = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
  let savedCallbackBaseUrl: string

  // All producer-derived (T1): the real discovery client over real probe fixtures, with
  // documented substitutions only where named.
  let atlassianResult: DiscoveryResult
  // Notion minus CIMD, confidential, no RFC 9207 → per-server DCR-confidential. Its
  // registration responses carry an RFC 7592 handle, so the cleanup DELETE is observable.
  let dcrConfNoIssResult: DiscoveryResult
  // Same AS with RFC 9207 → shared DCR-confidential.
  let dcrConfSharedResult: DiscoveryResult
  // Linear minus its registration endpoint and minus RFC 9207: CIMD-only without `iss` →
  // `manual`, i.e. the operator must pre-register.
  let cimdOnlyNoIssResult: DiscoveryResult

  function withoutRfc9207<T extends { as: { json: string } }>(pilot: T): T {
    const as = JSON.parse(pilot.as.json)
    delete as.authorization_response_iss_parameter_supported
    return { ...pilot, as: { ...pilot.as, json: JSON.stringify(as) } }
  }

  async function discoverPilot(pilot: Parameters<typeof makeDiscoveryTransport>[0]) {
    const actual = await vi.importActual<typeof import('../src/oauth/discovery.js')>(
      '../src/oauth/discovery.js'
    )
    const outcome = await actual.discoverRemoteOAuth(pilot.mcpUrl, {
      transport: makeDiscoveryTransport(pilot),
      resolveDns: PUBLIC_IP,
    })
    if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)
    return outcome.result
  }

  beforeAll(async () => {
    atlassianResult = await discoverPilot(ATLASSIAN_V2_PILOT)
    dcrConfNoIssResult = await discoverPilot(dcrPilot('confidential'))
    dcrConfSharedResult = await discoverPilot(withRfc9207(dcrPilot('confidential')))
    cimdOnlyNoIssResult = await discoverPilot(
      withoutRfc9207(withoutRegistrationEndpoint(PILOTS.linear))
    )
  })

  beforeEach(() => {
    vi.mocked(discoverRemoteOAuth).mockReset()
    savedCallbackBaseUrl = config.oauthCallbackBaseUrl
    config.oauthCallbackBaseUrl = ORIGIN
  })
  afterEach(() => {
    config.oauthCallbackBaseUrl = savedCallbackBaseUrl
  })

  function app(gw: MockGateway, deps: AdminRemoteMcpDeps) {
    return makeApp(gw, genericProbe, deps)
  }

  it('fixtures: Atlassian is CIMD+DCR without RFC 9207 on one site → dcr; the others as named', () => {
    expect(atlassianResult.issForCallback).toBeUndefined()
    expect(atlassianResult.as.client_id_metadata_document_supported).toBe(true)
    expect(atlassianResult.registrationMode).toBe('dcr')
    expect(dcrConfNoIssResult.issForCallback).toBeUndefined()
    expect(dcrConfSharedResult.issForCallback).toBeTruthy()
    expect(cimdOnlyNoIssResult.registrationMode).toBe('manual')
  })

  // I7 — the e2e origin of this change: Atlassian v2 returned 422 issuer_binding_required.
  it('Atlassian (CIMD+DCR, no RFC 9207, same site) → 201 by DCR on /remote/<name>/<installId>', async () => {
    mockDiscovery(atlassianResult)
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      registrationEndpoint: ATLASSIAN_REGISTRATION,
      responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
      redirectUris: 'requested',
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'atlassian',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.atlassian.com/v2/mcp',
        mode: 'dcr',
      })

    expect(res.status).toBe(201)
    expect(res.body).toMatchObject({
      registrationMode: 'dcr',
      clientMode: 'public',
      callbackVariant: 'per-server',
    })
    expect(res.body.redirectUri).toMatch(
      new RegExp(`^${escapeRegExp(ORIGIN)}/api/v1/oauth-callback/remote/atlassian/${NONCE_RE}$`)
    )
    // The nonce is this installation's install_id (what the callback will check).
    const stored = [...rows.values()][0]
    expect(res.body.redirectUri.endsWith(`/${stored.install_id}`)).toBe(true)
    // I4 (partial): the DCR POST registered exactly the URI the 201 reports.
    const post = calls.find(c => c.method === 'POST')
    expect(JSON.parse(post?.body ?? '{}').redirect_uris).toEqual([res.body.redirectUri])

    const cr = (await gw.getResource('mcpservers', 'atlassian', NS)) as {
      spec: { oauth: Record<string, unknown> }
    }
    expect(cr.spec.oauth.issForCallback).toBeUndefined()
    expect(cr.spec.oauth.id).toBe(DCR_PUBLIC_REGISTRATION_RESPONSE.client_id)
  })

  // I15 — one derivation: the variant the install decided before registering equals the
  // variant the runtime will derive from the CR the saga actually wrote.
  const I15_CASES = [
    { label: 'shared CIMD (Linear)', mode: 'cimd', result: () => linearResult },
    { label: 'shared DCR', mode: 'dcr', result: () => dcrConfSharedResult },
    { label: 'per-server DCR', mode: 'dcr', result: () => dcrConfNoIssResult },
    { label: 'shared pre-registered', mode: 'pre-registered', result: () => rfc9207Result },
    { label: 'per-server pre-registered', mode: 'pre-registered', result: () => notionResult },
  ] as const
  for (const c of I15_CASES) {
    it(`I15 ${c.label}: variant(install block) === variant(written CR)`, async () => {
      mockDiscovery(c.result())
      const { db } = makeInMemoryDynamicClientsDb()
      const { transport } = makeDcrTransport({
        responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
        redirectUris: 'requested',
      })
      const gw = gatewayWithContext('ctx-a')
      const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
        .post('/admin/mcp-servers/remote')
        .send({
          serverName: 'i15-server',
          contextRef: 'ctx-a',
          baseUrl: 'https://mcp.notion.com/mcp',
          mode: c.mode,
          ...(c.mode === 'pre-registered' ? { clientId: 'cid-i15', clientSecret: 's' } : {}),
        })
      expect(res.status).toBe(201)
      const cr = (await gw.getResource('mcpservers', 'i15-server', NS)) as {
        spec: { oauth: Record<string, unknown> }
      }
      const expected = c.result().issForCallback ? 'shared' : 'per-server'
      expect(res.body.callbackVariant).toBe(expected)
      expect(remoteCallbackVariant(cr.spec.oauth)).toBe(res.body.callbackVariant)
    })
  }

  // I12 — the registration response must report the per-server URI we asked for.
  const PER_SERVER_REJECTIONS = [
    {
      label: 'a different redirect URI (the shared one)',
      redirectUris: [`${ORIGIN}/api/v1/oauth-callback/remote`] as string[],
      kind: 'redirect_uris_mismatch',
    },
    { label: 'no redirect_uris', redirectUris: 'omit' as const, kind: 'redirect_uris_missing' },
  ]
  for (const c of PER_SERVER_REJECTIONS) {
    it(`I12 per-server DCR response with ${c.label} → 400, no CR, no row, RFC 7592 DELETE sent`, async () => {
      mockDiscovery(dcrConfNoIssResult)
      const { db, rows } = makeInMemoryDynamicClientsDb()
      const { transport, calls } = makeDcrTransport({
        responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
        redirectUris: c.redirectUris,
      })
      const gw = gatewayWithContext('ctx-a')
      const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
        .post('/admin/mcp-servers/remote')
        .send({
          serverName: 'i12-server',
          contextRef: 'ctx-a',
          baseUrl: 'https://mcp.notion.com/mcp',
          mode: 'dcr',
        })
      expect(res.status).toBe(400)
      expect(res.body).toEqual({ error: 'dcr_registration_failed', detail: { kind: c.kind } })
      expect(rows.size).toBe(0)
      await expect(gw.getResource('mcpservers', 'i12-server', NS)).rejects.toThrow()
      const deletes = calls.filter(call => call.method === 'DELETE')
      expect(deletes.map(d => d.url)).toEqual([
        DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_client_uri,
      ])
      // The management bearer never reaches the response.
      expect(JSON.stringify(res.body)).not.toContain(
        DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.registration_access_token
      )
    })
  }

  it('I12 shared DCR response reporting a different redirect URI → 400, no CR, no row, DELETE sent', async () => {
    mockDiscovery(dcrConfSharedResult)
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
      redirectUris: ['https://elsewhere.example.com/api/v1/oauth-callback/remote'],
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'i12-shared',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(400)
    expect(res.body.detail).toEqual({ kind: 'redirect_uris_mismatch' })
    expect(rows.size).toBe(0)
    await expect(gw.getResource('mcpservers', 'i12-shared', NS)).rejects.toThrow()
    expect(calls.filter(call => call.method === 'DELETE')).toHaveLength(1)
  })

  it('I12 shared DCR response without redirect_uris is tolerated → 201', async () => {
    mockDiscovery(dcrConfSharedResult)
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
      redirectUris: 'omit',
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'i12-omit',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(201)
    expect(res.body.redirectUri).toBe(`${ORIGIN}/api/v1/oauth-callback/remote`)
    expect(rows.size).toBe(1)
  })

  for (const c of [
    { label: 'per-server', result: () => dcrConfNoIssResult },
    { label: 'shared', result: () => dcrConfSharedResult },
  ]) {
    it(`I12 ${c.label} DCR assigning the platform CIMD client_id → 400, no CR, no row, DELETE sent`, async () => {
      mockDiscovery(c.result())
      const { db, rows } = makeInMemoryDynamicClientsDb()
      const { transport, calls } = makeDcrTransport({
        responseJson: JSON.stringify({
          ...DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,
          client_id: CIMD_SELF_CLIENT_ID,
        }),
        redirectUris: 'requested',
      })
      const gw = gatewayWithContext('ctx-a')
      const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
        .post('/admin/mcp-servers/remote')
        .send({
          serverName: 'i12-cimd',
          contextRef: 'ctx-a',
          baseUrl: 'https://mcp.notion.com/mcp',
          mode: 'dcr',
        })
      expect(res.status).toBe(400)
      expect(res.body.detail).toEqual({ kind: 'client_id_is_cimd_identity' })
      expect(rows.size).toBe(0)
      await expect(gw.getResource('mcpservers', 'i12-cimd', NS)).rejects.toThrow()
      expect(calls.filter(call => call.method === 'DELETE')).toHaveLength(1)
    })
  }

  it('DCR response with an oversized client_id → 400, no CR, no row, RFC 7592 DELETE sent', async () => {
    mockDiscovery(dcrConfNoIssResult)
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify({
        ...DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,
        client_id: `https://as.example.com/${'/'.repeat(200_000)}a`,
      }),
      redirectUris: 'requested',
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'huge-client-id',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('dcr_registration_failed')
    expect(res.body.detail.kind).toBe('invalid_response')
    expect(rows.size).toBe(0)
    await expect(gw.getResource('mcpservers', 'huge-client-id', NS)).rejects.toThrow()
    expect(calls.filter(call => call.method === 'DELETE')).toHaveLength(1)
  })

  it('DCR oversized client_id without an RFC 7592 handle → 400, no DELETE, internal flag not echoed', async () => {
    mockDiscovery(dcrConfNoIssResult)
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const {
      registration_client_uri: _u,
      registration_access_token: _t,
      ...noHandle
    } = DCR_CONFIDENTIAL_REGISTRATION_RESPONSE
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify({ ...noHandle, client_id: 'c'.repeat(513) }),
      redirectUris: 'requested',
    })
    const gw = gatewayWithContext('ctx-a')
    const res = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'huge-no-handle',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(res.status).toBe(400)
    expect(res.body.detail.kind).toBe('invalid_response')
    expect(res.body.detail.minted).toBeUndefined()
    expect(calls.filter(call => call.method === 'DELETE')).toHaveLength(0)
    expect(rows.size).toBe(0)
  })

  it('pre-registered clientId longer than the CRD cap (512) → 400 before discovery', async () => {
    const gw = gatewayWithContext('ctx-a')
    const res = await request(app(gw, {}))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'long-cid',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'pre-registered',
        clientId: 'c'.repeat(513),
        clientSecret: 's',
      })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('invalid_request')
    expect(discoverRemoteOAuth).not.toHaveBeenCalled()
  })

  // I17 — a per-server pre-registered client belongs to exactly one server.
  async function installPreRegistered(
    gw: MockGateway,
    deps: AdminRemoteMcpDeps,
    serverName: string,
    clientId: string,
    result: DiscoveryResult = notionResult
  ) {
    mockDiscovery(result)
    return request(app(gw, deps)).post('/admin/mcp-servers/remote').send({
      serverName,
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'pre-registered',
      clientId,
      clientSecret: 'fixture-pre-reg-secret',
    })
  }

  it('I17 client_id already used by another remote server → 409, no Secret, no CR', async () => {
    const gw = gatewayWithContext('ctx-a')
    const { db } = makeInMemoryDynamicClientsDb()
    // The first server is written by the real saga (T1), not seeded by hand.
    expect((await installPreRegistered(gw, { db }, 'first-server', 'shared-cid')).status).toBe(201)
    const res = await installPreRegistered(gw, { db }, 'second-server', 'shared-cid')
    expect(res.status).toBe(409)
    expect(res.body).toMatchObject({ error: 'oauth_client_id_in_use', conflict: 'remote_server' })
    expect(res.body.message).toMatch(/separate OAuth client/)
    await expect(gw.getResource('mcpservers', 'second-server', NS)).rejects.toThrow()
    await expect(gw.getSecret('second-server-oauth-client', NS)).rejects.toThrow()
  })

  it('I17 client_id of a live DCR client → 409 (dynamic_client), no Secret, no CR', async () => {
    const gw = gatewayWithContext('ctx-a')
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
      redirectUris: 'requested',
    })
    // A real DCR install leaves the live dynamic_clients row (T1).
    mockDiscovery(dcrConfNoIssResult)
    const dcr = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'dcr-server',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(dcr.status).toBe(201)
    const dcrClientId = [...rows.values()][0].client_id as string
    expect(dcrClientId).toBe(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE.client_id)
    // With the CR still present the CR check answers first; remove it the way a
    // `kubectl delete` does (the row, and the client at the AS, stay behind).
    await gw.deleteResource('mcpservers', 'dcr-server', NS)
    expect(rows.size).toBe(1)

    const res = await installPreRegistered(gw, { db }, 'pre-server', dcrClientId)
    expect(res.status).toBe(409)
    expect(res.body).toMatchObject({ error: 'oauth_client_id_in_use', conflict: 'dynamic_client' })
    expect(res.body.message).toMatch(/separate OAuth client/)
    await expect(gw.getResource('mcpservers', 'pre-server', NS)).rejects.toThrow()
    await expect(gw.getSecret('pre-server-oauth-client', NS)).rejects.toThrow()
  })

  it('I17 client_id equal to the platform CIMD identity (any origin) → 409 (cimd_client)', async () => {
    const gw = gatewayWithContext('ctx-a')
    const { db } = makeInMemoryDynamicClientsDb()
    for (const clientId of [
      CIMD_SELF_CLIENT_ID,
      'https://old-origin.example.org/api/v1/.well-known/evenfire-mcp-client',
    ]) {
      const res = await installPreRegistered(gw, { db }, 'cimd-pre', clientId)
      expect(res.status).toBe(409)
      expect(res.body).toMatchObject({ error: 'oauth_client_id_in_use', conflict: 'cimd_client' })
      expect(res.body.message).toMatch(/separate OAuth client/)
    }
    await expect(gw.getResource('mcpservers', 'cimd-pre', NS)).rejects.toThrow()
  })

  // A client_id is only unique within its AS: the same string at another provider is
  // another client, registered there with its own redirect URI.
  function atOtherProvider(result: DiscoveryResult): DiscoveryResult {
    return JSON.parse(
      JSON.stringify(result).split('https://mcp.notion.com').join('https://auth.other-provider.io')
    ) as DiscoveryResult
  }

  it('I17 the same client_id at another provider (remote server) → 201', async () => {
    const gw = gatewayWithContext('ctx-a')
    const { db } = makeInMemoryDynamicClientsDb()
    const other = atOtherProvider(notionResult)
    expect(other.issuer).toBe('https://auth.other-provider.io')
    expect((await installPreRegistered(gw, { db }, 'first-server', 'shared-cid')).status).toBe(201)
    const res = await installPreRegistered(gw, { db }, 'second-server', 'shared-cid', other)
    expect(res.status).toBe(201)
  })

  it('I17 the same client_id as a DCR client at another provider → 201', async () => {
    const gw = gatewayWithContext('ctx-a')
    const { db, rows } = makeInMemoryDynamicClientsDb()
    const { transport } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
      redirectUris: 'requested',
    })
    mockDiscovery(dcrConfNoIssResult)
    const dcr = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'dcr-server',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'dcr',
      })
    expect(dcr.status).toBe(201)
    const dcrClientId = [...rows.values()][0].client_id as string
    await gw.deleteResource('mcpservers', 'dcr-server', NS)

    const res = await installPreRegistered(
      gw,
      { db },
      'pre-server',
      dcrClientId,
      atOtherProvider(notionResult)
    )
    expect(res.status).toBe(201)
  })

  // The conflict is keyed on the AS issuer, never on the protected resource: with the
  // two distinct, only the issuer can find the first server's client.
  it('I17 conflicts on the issuer even when the resource differs from it → 409', async () => {
    const gw = gatewayWithContext('ctx-a')
    const { db } = makeInMemoryDynamicClientsDb()
    const distinctResource: DiscoveryResult = {
      ...notionResult,
      resource: 'https://mcp.notion.com/mcp',
    }
    expect(distinctResource.resource).not.toBe(distinctResource.issuer)
    expect(
      (await installPreRegistered(gw, { db }, 'first-server', 'shared-cid', distinctResource))
        .status
    ).toBe(201)
    const res = await installPreRegistered(
      gw,
      { db },
      'second-server',
      'shared-cid',
      distinctResource
    )
    expect(res.status).toBe(409)
    expect(res.body).toMatchObject({ error: 'oauth_client_id_in_use', conflict: 'remote_server' })
  })

  it('I17 a different client_id at the same provider → 201', async () => {
    const gw = gatewayWithContext('ctx-a')
    const { db } = makeInMemoryDynamicClientsDb()
    expect((await installPreRegistered(gw, { db }, 'first-server', 'cid-one')).status).toBe(201)
    expect((await installPreRegistered(gw, { db }, 'second-server', 'cid-two')).status).toBe(201)
  })

  it('I17 does not constrain a shared (RFC 9207) pre-registered install → 201', async () => {
    const gw = gatewayWithContext('ctx-a')
    const { db } = makeInMemoryDynamicClientsDb()
    expect(
      (await installPreRegistered(gw, { db }, 'a-shared', 'cid-x', rfc9207Result)).status
    ).toBe(201)
    expect(
      (await installPreRegistered(gw, { db }, 'b-shared', 'cid-x', rfc9207Result)).status
    ).toBe(201)
  })

  // Per-server origin fails closed; shared keeps its historical behaviour.
  for (const baseUrl of ['', 'https://control.example.com/some/prefix']) {
    it(`per-server install with callback base URL ${JSON.stringify(baseUrl)} → 503, nothing written or minted`, async () => {
      config.oauthCallbackBaseUrl = baseUrl
      const gw = gatewayWithContext('ctx-a')
      const { db, rows } = makeInMemoryDynamicClientsDb()
      const { transport, calls } = makeDcrTransport({
        responseJson: JSON.stringify(DCR_CONFIDENTIAL_REGISTRATION_RESPONSE),
        redirectUris: 'requested',
      })
      mockDiscovery(dcrConfNoIssResult)
      const dcr = await request(app(gw, { db, dcr: { transport, resolveDns: PUBLIC_IP } }))
        .post('/admin/mcp-servers/remote')
        .send({
          serverName: 'no-origin-dcr',
          contextRef: 'ctx-a',
          baseUrl: 'https://mcp.notion.com/mcp',
          mode: 'dcr',
        })
      expect(dcr.status).toBe(503)
      expect(dcr.body).toEqual({ error: 'callback_base_url_unconfigured' })
      expect(calls).toHaveLength(0)
      expect(rows.size).toBe(0)

      const pre = await installPreRegistered(gw, { db }, 'no-origin-pre', 'cid-no-origin')
      expect(pre.status).toBe(503)
      expect(pre.body).toEqual({ error: 'callback_base_url_unconfigured' })
      await expect(gw.getSecret('no-origin-pre-oauth-client', NS)).rejects.toThrow()
      await expect(gw.getResource('mcpservers', 'no-origin-pre', NS)).rejects.toThrow()
    })
  }

  it('shared pre-registered install without a callback base URL still succeeds (no redirectUri reported)', async () => {
    config.oauthCallbackBaseUrl = ''
    const gw = gatewayWithContext('ctx-a')
    const res = await installPreRegistered(gw, {}, 'shared-no-origin', 'cid-y', rfc9207Result)
    expect(res.status).toBe(201)
    expect(res.body.callbackVariant).toBe('shared')
    expect(res.body.redirectUri).toBeUndefined()
  })

  // mode_unsupported names the missing RFC 9207 and the mode that does work.
  for (const c of [
    { label: 'DCR available (Notion)', result: () => notionResult, next: 'dcr' },
    {
      label: 'no DCR (Linear minus registration)',
      result: () => cimdOnlyNoIssResult,
      next: 'pre-registered',
    },
  ]) {
    it(`CIMD requested on a CIMD AS without RFC 9207, ${c.label} → 400 naming "${c.next}"`, async () => {
      mockDiscovery(c.result())
      const gw = gatewayWithContext('ctx-a')
      const res = await request(app(gw, {})).post('/admin/mcp-servers/remote').send({
        serverName: 'cimd-req',
        contextRef: 'ctx-a',
        baseUrl: 'https://mcp.notion.com/mcp',
        mode: 'cimd',
      })
      expect(res.status).toBe(400)
      expect(res.body).toEqual({
        error: 'mode_unsupported',
        message: `this authorization server supports CIMD but not RFC 9207; install with mode "${c.next}"`,
      })
    })
  }

  it('CIMD requested on a DCR-only AS keeps the generic message', async () => {
    mockDiscovery(dcrConfNoIssResult)
    const gw = gatewayWithContext('ctx-a')
    const res = await request(app(gw, {})).post('/admin/mcp-servers/remote').send({
      serverName: 'cimd-req2',
      contextRef: 'ctx-a',
      baseUrl: 'https://mcp.notion.com/mcp',
      mode: 'cimd',
    })
    expect(res.status).toBe(400)
    expect(res.body.message).toBe(
      'this authorization server requires dynamic client registration; install with mode "dcr"'
    )
  })

  describe('/discover callback preview', () => {
    async function discoverWith(result: DiscoveryResult) {
      mockDiscovery(result)
      return request(makeApp(gatewayWithContext()))
        .post('/admin/mcp-servers/remote/discover')
        .send({ baseUrl: 'https://mcp.example.com/mcp' })
    }

    it('per-server DCR (Atlassian): template with {serverName}/{installId} + AS endpoint hosts', async () => {
      const res = await discoverWith(atlassianResult)
      expect(res.status).toBe(200)
      expect(res.body.callback).toEqual({
        configured: true,
        variant: 'per-server',
        redirectUriTemplate: `${ORIGIN}/api/v1/oauth-callback/remote/{serverName}/{installId}`,
      })
      const atlassianHost = 'auth.atlassian.com'
      expect(res.body.detected.asEndpointHosts).toEqual({
        authorization: atlassianHost,
        token: atlassianHost,
        registration: atlassianHost,
      })
    })

    it('per-server pre-registered (CIMD-only AS without RFC 9207): template /remote/{serverName}', async () => {
      const res = await discoverWith(cimdOnlyNoIssResult)
      expect(res.body.callback).toEqual({
        configured: true,
        variant: 'per-server',
        redirectUriTemplate: `${ORIGIN}/api/v1/oauth-callback/remote/{serverName}`,
      })
      const linearHost = 'mcp.linear.app'
      expect(res.body.detected.asEndpointHosts).toEqual({
        authorization: linearHost,
        token: linearHost,
      })
    })

    it('shared (Linear, RFC 9207): the real shared URI, no endpoint hosts', async () => {
      const res = await discoverWith(linearResult)
      expect(res.body.callback).toEqual({
        configured: true,
        variant: 'shared',
        redirectUriTemplate: `${ORIGIN}/api/v1/oauth-callback/remote`,
      })
      expect(res.body.detected.asEndpointHosts).toBeUndefined()
    })

    for (const baseUrl of ['', 'https://control.example.com/some/prefix']) {
      it(`per-server with callback base URL ${JSON.stringify(baseUrl)} → configured:false, no template`, async () => {
        config.oauthCallbackBaseUrl = baseUrl
        const res = await discoverWith(atlassianResult)
        expect(res.status).toBe(200)
        expect(res.body.callback).toEqual({ configured: false, variant: 'per-server' })
      })
    }
  })
})

describe('Microsoft Entra ID — authorizationServer override on /discover and install', () => {
  const PUBLIC_IP = async () => ['93.184.216.34']
  const ORIGIN = 'https://control.example.com'
  const TENANT_AUTHORITY =
    'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0'
  let savedCallbackBaseUrl: string

  beforeEach(() => {
    vi.mocked(discoverRemoteOAuth).mockReset()
    savedCallbackBaseUrl = config.oauthCallbackBaseUrl
    config.oauthCallbackBaseUrl = ORIGIN
  })
  afterEach(() => {
    config.oauthCallbackBaseUrl = savedCallbackBaseUrl
  })

  /**
   * The router wired to the REAL discovery client and transport probe over a pilot's
   * recorded bytes (T1), through the `discover`/`probe` seams, so what the route passes
   * to discovery (the override included) decides the outcome.
   */
  async function entraApp(
    pilot: PilotFixture,
    gw: MockGateway,
    deps: AdminRemoteMcpDeps = {}
  ): Promise<express.Express> {
    const actual = await vi.importActual<typeof import('../src/oauth/discovery.js')>(
      '../src/oauth/discovery.js'
    )
    const transport = makeDiscoveryTransport(pilot)
    return makeApp(gw, boundProbe(transport), {
      discover: (url, discoveryDeps, opts) =>
        actual.discoverRemoteOAuth(
          url,
          { ...discoveryDeps, transport, resolveDns: PUBLIC_IP },
          opts
        ),
      ...deps,
    })
  }

  async function expectNoWrites(gw: MockGateway, serverName: string): Promise<void> {
    await expect(gw.getSecret(`${serverName}-oauth-client`, NS)).rejects.toThrow()
    await expect(gw.getResource('mcpservers', serverName, NS)).rejects.toThrow()
  }

  it('/discover without baseUrl → 400 invalid_request with the schema issues', async () => {
    const res = await request(makeApp(gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({})
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('invalid_request')
    expect(Array.isArray(res.body.detail)).toBe(true)
    expect(res.body.detail[0].path).toEqual(['baseUrl'])
    expect(discoverRemoteOAuth).not.toHaveBeenCalled()
  })

  it('row 7: /discover kernel-rejects a non-https authorizationServer before discovery', async () => {
    const res = await request(makeApp(gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({
        baseUrl: ENTRA_WORKIQ_PILOT.mcpUrl,
        authorizationServer: TENANT_AUTHORITY.replace('https:', 'http:'),
      })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('must use https')
    expect(res.body.errors[0].field).toBe('authorizationServer')
    expect(discoverRemoteOAuth).not.toHaveBeenCalled()
  })

  it('row 7: install kernel-rejects a non-https authorizationServer before discovery or writes', async () => {
    const gw = gatewayWithContext()
    const res = await request(makeApp(gw))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'workiq',
        contextRef: 'ctx-a',
        baseUrl: ENTRA_WORKIQ_PILOT.mcpUrl,
        mode: 'pre-registered',
        clientId: 'entra-client',
        clientSecret: 'entra-secret',
        authorizationServer: TENANT_AUTHORITY.replace('https:', 'http:'),
      })
    expect(res.status).toBe(400)
    expect(res.body.errors[0].field).toBe('authorizationServer')
    expect(discoverRemoteOAuth).not.toHaveBeenCalled()
    await expectNoWrites(gw, 'workiq')
  })

  it('/discover of Work IQ without an override → 400 tenant_required with the template', async () => {
    const res = await request(await entraApp(ENTRA_WORKIQ_PILOT, gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: ENTRA_WORKIQ_PILOT.mcpUrl })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('discovery_failed')
    expect(res.body.detail).toMatchObject({
      kind: 'tenant_required',
      authorizationServer: 'https://login.microsoftonline.com/organizations/v2.0',
      tenantAuthorityTemplate: 'https://login.microsoftonline.com/{tenantId}/v2.0',
    })
  })

  it('row 2: /discover of Work IQ with the tenant → profile and PRM scopes plus offline_access', async () => {
    const res = await request(await entraApp(ENTRA_WORKIQ_PILOT, gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: ENTRA_WORKIQ_PILOT.mcpUrl, authorizationServer: TENANT_AUTHORITY })
    expect(res.status).toBe(200)
    expect(res.body.detected.asProfile).toBe('entra-v2')
    expect(res.body.detected.registrationMode).toBe('manual')
    expect(res.body.detected.quirks).toEqual({ bearerInBody: false, supportsRefresh: true })
    expect(res.body.detected.scopes).toEqual([
      'fdcc1f02-fc51-4226-8753-f668596af7f7/WorkIQAgent.Ask',
      'offline_access',
    ])
    expect(res.body.callback.variant).toBe('per-server')
    expect(res.body.detected.issForCallback).toBeUndefined()
  })

  it("row 4: an unknown tenant → 424 fetch_failed carrying Entra's 400 and its URL", async () => {
    const unknownTenant =
      'https://login.microsoftonline.com/00000000-0000-0000-0000-000000000001/v2.0'
    const res = await request(await entraApp(ENTRA_WORKIQ_PILOT, gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: ENTRA_WORKIQ_PILOT.mcpUrl, authorizationServer: unknownTenant })
    expect(res.status).toBe(424)
    expect(res.body.error).toBe('discovery_failed')
    expect(res.body.detail.kind).toBe('fetch_failed')
    expect(res.body.detail.status).toBe(400)
    expect(res.body.detail.url.startsWith('https://login.microsoftonline.com/')).toBe(true)
  })

  it('Agent 365 Mail: offline_access, already in its PRM, is not added twice', async () => {
    const res = await request(await entraApp(ENTRA_AGENT365_MAIL_PILOT, gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: ENTRA_AGENT365_MAIL_PILOT.mcpUrl, authorizationServer: TENANT_AUTHORITY })
    expect(res.status).toBe(200)
    expect(res.body.detected.scopes).toEqual([
      'https://agent365.svc.cloud.microsoft/agents/tenants/72f988bf-86f1-41af-91ab-2d7cd011db47/servers/mcp_MailTools/.default',
      'openid',
      'profile',
      'offline_access',
    ])
  })

  it('/discover ignores a PRM scopes_supported that is a string, not a list', async () => {
    const res = await request(
      await entraApp(
        workIqPilotWithPrm('entra-string-scopes', prm => {
          prm.scopes_supported = 'fdcc1f02-fc51-4226-8753-f668596af7f7/WorkIQAgent.Ask'
        }),
        gatewayWithContext()
      )
    )
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: ENTRA_WORKIQ_PILOT.mcpUrl, authorizationServer: TENANT_AUTHORITY })
    expect(res.status).toBe(200)
    // The real Entra tenant metadata advertises only sign-in scopes.
    expect(res.body.detected.scopes).toEqual(['openid', 'profile', 'email', 'offline_access'])
    expect(res.body.detected.scopeAudienceMissing).toBe(true)
  })

  it('/discover keeps an empty-string audience violation in the response', async () => {
    const res = await request(
      await entraApp(
        workIqPilotWithPrm('entra-empty-scope', prm => {
          prm.scopes_supported = ['', 'https://graph.microsoft.com/x']
        }),
        gatewayWithContext()
      )
    )
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: ENTRA_WORKIQ_PILOT.mcpUrl, authorizationServer: TENANT_AUTHORITY })
    expect(res.status).toBe(200)
    expect(res.body.detected.scopeAudienceViolation).toBe('')
  })

  it('row 10: /discover passes the override to discovery (Linear rejects a tenant authority)', async () => {
    const res = await request(await entraApp(PILOTS.linear, gatewayWithContext()))
      .post('/admin/mcp-servers/remote/discover')
      .send({ baseUrl: PILOTS.linear.mcpUrl, authorizationServer: TENANT_AUTHORITY })
    expect(res.status).toBe(400)
    expect(res.body.detail.kind).toBe('authorization_server_override_rejected')
  })

  it('row 10: install passes the override to discovery and writes nothing when it is rejected', async () => {
    const gw = gatewayWithContext()
    const res = await request(await entraApp(PILOTS.linear, gw))
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'linear-entra',
        contextRef: 'ctx-a',
        baseUrl: PILOTS.linear.mcpUrl,
        mode: 'cimd',
        authorizationServer: TENANT_AUTHORITY,
      })
    expect(res.status).toBe(400)
    expect(res.body.detail.kind).toBe('authorization_server_override_rejected')
    await expectNoWrites(gw, 'linear-entra')
  })
})

describe('Microsoft Entra ID — remote install with scopes, scope audience and asProfile', () => {
  const PUBLIC_IP = async () => ['93.184.216.34']
  const ORIGIN = 'https://control.example.com'
  const TENANT_AUTHORITY =
    'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0'
  const WORKIQ_GUID_SCOPE = 'fdcc1f02-fc51-4226-8753-f668596af7f7/WorkIQAgent.Ask'
  const WORKIQ_URL_SCOPE = 'api://workiq.svc.cloud.microsoft/WorkIQAgent.Ask'
  const UNKNOWN_GUID_SCOPE = '11111111-2222-3333-4444-555555555555/Tools.Read'
  const SHAREPOINT_SCOPE = '00000003-0000-0ff1-ce00-000000000000/AllSites.Read'
  let savedCallbackBaseUrl: string

  beforeEach(() => {
    vi.mocked(discoverRemoteOAuth).mockReset()
    savedCallbackBaseUrl = config.oauthCallbackBaseUrl
    config.oauthCallbackBaseUrl = ORIGIN
  })
  afterEach(() => {
    config.oauthCallbackBaseUrl = savedCallbackBaseUrl
  })

  /** Real discovery + probe over the pilot's recorded bytes (T1), through the router seams. */
  async function pilotDeps(pilot: PilotFixture): Promise<AdminRemoteMcpDeps> {
    const actual = await vi.importActual<typeof import('../src/oauth/discovery.js')>(
      '../src/oauth/discovery.js'
    )
    const transport = makeDiscoveryTransport(pilot)
    return {
      probe: boundProbe(transport),
      discover: (url, discoveryDeps, opts) =>
        actual.discoverRemoteOAuth(
          url,
          { ...discoveryDeps, transport, resolveDns: PUBLIC_IP },
          opts
        ),
    }
  }

  /**
   * The router behind a stand-in for the auth middleware and the correlation logger, so
   * the audit record's `admin` and the request logger are what production would see.
   */
  async function entraInstall(
    pilot: PilotFixture,
    gw: MockGateway,
    body: Record<string, unknown>,
    extra: { reqLog?: unknown; deps?: AdminRemoteMcpDeps } = {}
  ) {
    const { db } = makeInMemoryDynamicClientsDb()
    const app = express()
    app.use(express.json())
    app.use((req, _res, next) => {
      ;(req as UiAuthedRequestLike).adminAuth = { sub: 'admin-7', jti: 'jti-7' }
      if (extra.reqLog) (req as UiAuthedRequestLike).log = extra.reqLog
      next()
    })
    app.use(
      createAdminRemoteMcpRouter(gw as unknown as K8sGateway, {
        db,
        ...(await pilotDeps(pilot)),
        ...extra.deps,
      })
    )
    return request(app)
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'workiq',
        contextRef: 'ctx-a',
        baseUrl: pilot.mcpUrl,
        mode: 'pre-registered',
        clientId: 'entra-client-id',
        clientSecret: 'entra-client-secret',
        authorizationServer: TENANT_AUTHORITY,
        ...body,
      })
  }

  async function expectNoWrites(gw: MockGateway, serverName = 'workiq'): Promise<void> {
    await expect(gw.getSecret(`${serverName}-oauth-client`, NS)).rejects.toThrow()
    await expect(gw.getResource('mcpservers', serverName, NS)).rejects.toThrow()
  }

  async function installedOauth(gw: MockGateway, serverName = 'workiq') {
    const cr = (await gw.getResource('mcpservers', serverName, NS)) as {
      spec: { oauth: Record<string, unknown> }
    }
    return cr.spec.oauth
  }

  it('row 19: with the profile, an install without scopes → 400 invalid_request, no writes', async () => {
    const gw = gatewayWithContext()
    const res = await entraInstall(ENTRA_WORKIQ_PILOT, gw, {})
    expect(res.status).toBe(400)
    expect(res.body).toEqual({
      error: 'invalid_request',
      message: 'scopes is required for Microsoft Entra ID servers',
    })
    await expectNoWrites(gw)
  })

  it('rows 2/13: Work IQ with its detected GUID scope → 201 and a CR pinned to the profile', async () => {
    const gw = gatewayWithContext()
    const res = await entraInstall(ENTRA_WORKIQ_PILOT, gw, { scopes: [WORKIQ_GUID_SCOPE] })
    expect(res.status).toBe(201)
    const oauth = await installedOauth(gw)
    expect(oauth.asProfile).toBe('entra-v2')
    expect(oauth.supportsRefresh).toBe(true)
    expect(oauth.issuer).toBe(TENANT_AUTHORITY)
    expect(oauth.scopes).toEqual([WORKIQ_GUID_SCOPE, 'offline_access'])
    expect(oauth.resource).toBe('https://workiq.svc.cloud.microsoft/mcp')
    expect('issForCallback' in oauth).toBe(false)
  })

  it('I7: the URL-form scope without offline_access → the CR still requests offline_access', async () => {
    const gw = gatewayWithContext()
    const res = await entraInstall(ENTRA_WORKIQ_PILOT, gw, { scopes: [WORKIQ_URL_SCOPE] })
    expect(res.status).toBe(201)
    expect((await installedOauth(gw)).scopes).toEqual([WORKIQ_URL_SCOPE, 'offline_access'])
  })

  it('row 17: only offline_access → 400 scope_audience_missing, no writes', async () => {
    const gw = gatewayWithContext()
    const res = await entraInstall(ENTRA_NO_SCOPES_PILOT, gw, { scopes: ['offline_access'] })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('scope_audience_missing')
    await expectNoWrites(gw)
  })

  it('row 18: a Graph GUID smuggled as userinfo → 400 scope_audience_mismatch, no writes', async () => {
    const gw = gatewayWithContext()
    const smuggled =
      'api://[email protected]/Mail.Read'
    const res = await entraInstall(ENTRA_WORKIQ_PILOT, gw, { scopes: [smuggled] })
    expect(res.status).toBe(400)
    expect(res.body).toMatchObject({ error: 'scope_audience_mismatch', scope: smuggled })
    await expectNoWrites(gw)
  })

  it('row 12: the Graph scope the PRM suggests, installed as detected → 400, no Secret or CR', async () => {
    const gw = gatewayWithContext()
    const graph = 'https://graph.microsoft.com/Mail.ReadWrite'
    const res = await entraInstall(ENTRA_GRAPH_SCOPE_PILOT, gw, { scopes: [graph] })
    expect(res.status).toBe(400)
    expect(res.body).toMatchObject({ error: 'scope_audience_mismatch', scope: graph })
    await expectNoWrites(gw)
  })

  it('I10: a bare scope name (read by Entra as Microsoft Graph) → 400, no writes', async () => {
    const gw = gatewayWithContext()
    const res = await entraInstall(ENTRA_GRAPH_SCOPE_PILOT, gw, { scopes: ['Mail.Read'] })
    expect(res.status).toBe(400)
    expect(res.body).toMatchObject({ error: 'scope_audience_mismatch', scope: 'Mail.Read' })
    await expectNoWrites(gw)
  })

  it('128 scopes plus the profile offline_access → 400 invalid_request, no writes', async () => {
    const gw = gatewayWithContext()
    const scopes = Array.from({ length: 128 }, (_, i) => `api://workiq.svc.cloud.microsoft/s${i}`)
    const res = await entraInstall(ENTRA_WORKIQ_PILOT, gw, { scopes })
    expect(res.status).toBe(400)
    expect(res.body).toEqual({
      error: 'invalid_request',
      message: 'at most 128 scopes, including those the authorization server requires',
    })
    await expectNoWrites(gw)
  })

  it('127 scopes plus the profile offline_access (128 in all) → 201', async () => {
    const gw = gatewayWithContext()
    const scopes = Array.from({ length: 127 }, (_, i) => `api://workiq.svc.cloud.microsoft/s${i}`)
    const res = await entraInstall(ENTRA_WORKIQ_PILOT, gw, { scopes })
    expect(res.status).toBe(201)
    expect((await installedOauth(gw)).scopes).toHaveLength(128)
  })

  for (const scopes of [['bad scope'], []]) {
    it(`scopes ${JSON.stringify(scopes)} → 400 invalid_request, no writes`, async () => {
      const gw = gatewayWithContext()
      const res = await entraInstall(ENTRA_WORKIQ_PILOT, gw, { scopes })
      expect(res.status).toBe(400)
      expect(res.body.error).toBe('invalid_request')
      await expectNoWrites(gw)
    })
  }

  it('row 14: an unknown GUID without confirmation → 400 scope_audience_unverified, no writes', async () => {
    const gw = gatewayWithContext()
    const res = await entraInstall(ENTRA_UNKNOWN_GUID_PILOT, gw, { scopes: [UNKNOWN_GUID_SCOPE] })
    expect(res.status).toBe(400)
    expect(res.body).toMatchObject({
      error: 'scope_audience_unverified',
      scopes: [UNKNOWN_GUID_SCOPE],
    })
    await expectNoWrites(gw)
  })

  it('row 14: a confirmation that does not name the scope → still 400, no writes', async () => {
    const gw = gatewayWithContext()
    const res = await entraInstall(ENTRA_UNKNOWN_GUID_PILOT, gw, {
      scopes: [UNKNOWN_GUID_SCOPE],
      confirmedUnverifiedScopes: ['11111111-2222-3333-4444-555555555555/Tools.Write'],
    })
    expect(res.status).toBe(400)
    expect(res.body.error).toBe('scope_audience_unverified')
    await expectNoWrites(gw)
  })

  it('row 14: the exact confirmation → 201, the CR carries the scope and the admin is audited', async () => {
    const gw = gatewayWithContext()
    const reqLog = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
    const res = await entraInstall(
      ENTRA_UNKNOWN_GUID_PILOT,
      gw,
      { scopes: [UNKNOWN_GUID_SCOPE], confirmedUnverifiedScopes: [UNKNOWN_GUID_SCOPE] },
      { reqLog }
    )
    expect(res.status).toBe(201)
    expect((await installedOauth(gw)).scopes).toEqual([UNKNOWN_GUID_SCOPE, 'offline_access'])
    const audits = reqLog.info.mock.calls.filter(
      ([fields]) =>
        (fields as { event?: string }).event === 'remote_install_unverified_scopes_confirmed'
    )
    expect(audits).toHaveLength(1)
    expect(audits[0][0]).toEqual({
      event: 'remote_install_unverified_scopes_confirmed',
      serverName: 'workiq',
      admin: 'admin-7',
      scopes: [UNKNOWN_GUID_SCOPE],
    })
  })

  it('row 14: the confirmation is audited once the CR exists, even if attach and its rollback fail', async () => {
    const gw = gatewayWithContext()
    vi.spyOn(gw, 'updateResource').mockRejectedValueOnce(new Error('attach boom'))
    vi.spyOn(gw, 'deleteResource').mockRejectedValue(new Error('delete boom'))
    const reqLog = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
    const res = await entraInstall(
      ENTRA_UNKNOWN_GUID_PILOT,
      gw,
      { scopes: [UNKNOWN_GUID_SCOPE], confirmedUnverifiedScopes: [UNKNOWN_GUID_SCOPE] },
      { reqLog }
    )
    expect(res.status).toBe(500)
    // The rollback failed, so the CR — and with it the confirmation — is live.
    expect((await installedOauth(gw)).scopes).toEqual([UNKNOWN_GUID_SCOPE, 'offline_access'])
    expect(reqLog.info).toHaveBeenCalledWith(
      {
        event: 'remote_install_unverified_scopes_confirmed',
        serverName: 'workiq',
        admin: 'admin-7',
        scopes: [UNKNOWN_GUID_SCOPE],
      },
      expect.any(String)
    )
  })

  it('row 13: a known GUID on its host needs no confirmation and leaves no audit record', async () => {
    const gw = gatewayWithContext()
    const reqLog = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
    const res = await entraInstall(
      ENTRA_WORKIQ_PILOT,
      gw,
      { scopes: [WORKIQ_GUID_SCOPE] },
      { reqLog }
    )
    expect(res.status).toBe(201)
    expect(
      reqLog.info.mock.calls.some(
        ([fields]) =>
          (fields as { event?: string }).event === 'remote_install_unverified_scopes_confirmed'
      )
    ).toBe(false)
  })

  it('row 15: a SharePoint Online scope → 400 scope_audience_mismatch even when confirmed', async () => {
    const gw = gatewayWithContext()
    const res = await entraInstall(ENTRA_SHAREPOINT_SCOPE_PILOT, gw, {
      scopes: [SHAREPOINT_SCOPE],
      confirmedUnverifiedScopes: [SHAREPOINT_SCOPE],
    })
    expect(res.status).toBe(400)
    expect(res.body).toMatchObject({ error: 'scope_audience_mismatch', scope: SHAREPOINT_SCOPE })
    await expectNoWrites(gw)
  })

  it('row 16: the Agent 365 GUID on the Work IQ host → 400 scope_audience_mismatch even when confirmed', async () => {
    const gw = gatewayWithContext()
    const agent365Scope = '05879165-0320-489e-b644-f72b33f3edf0/McpServers.Mail.All'
    const res = await entraInstall(ENTRA_WORKIQ_PILOT, gw, {
      scopes: [agent365Scope],
      confirmedUnverifiedScopes: [agent365Scope],
    })
    expect(res.status).toBe(400)
    expect(res.body).toMatchObject({ error: 'scope_audience_mismatch', scope: agent365Scope })
    await expectNoWrites(gw)
  })

  it('a rejected audience is logged on the request logger without the scope', async () => {
    const gw = gatewayWithContext()
    const reqLog = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
    await entraInstall(ENTRA_GRAPH_SCOPE_PILOT, gw, { scopes: ['Mail.Read'] }, { reqLog })
    expect(reqLog.warn).toHaveBeenCalledWith(
      { event: 'remote_install_scope_audience_rejected', serverName: 'workiq', reason: 'mismatch' },
      'remote install rejected: scope outside the server audience'
    )
  })

  it('a missing server audience is logged on the request logger', async () => {
    const gw = gatewayWithContext()
    const reqLog = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
    const res = await entraInstall(
      ENTRA_NO_SCOPES_PILOT,
      gw,
      { scopes: ['offline_access'] },
      { reqLog }
    )
    expect(res.body.error).toBe('scope_audience_missing')
    expect(reqLog.warn).toHaveBeenCalledWith(
      { event: 'remote_install_scope_audience_rejected', serverName: 'workiq', reason: 'missing' },
      'remote install rejected: no scope belongs to the server audience'
    )
  })

  it('unconfirmed unverified scopes are logged on the request logger with those scopes', async () => {
    const gw = gatewayWithContext()
    const reqLog = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
    const res = await entraInstall(
      ENTRA_UNKNOWN_GUID_PILOT,
      gw,
      { scopes: [UNKNOWN_GUID_SCOPE] },
      { reqLog }
    )
    expect(res.body.error).toBe('scope_audience_unverified')
    expect(reqLog.warn).toHaveBeenCalledWith(
      {
        event: 'remote_install_scope_audience_rejected',
        serverName: 'workiq',
        reason: 'unverified',
        scopes: [UNKNOWN_GUID_SCOPE],
      },
      'remote install rejected: scopes not confirmed as belonging to the server'
    )
  })

  it('DCR with a scopes override: the registration request carries exactly those scopes', async () => {
    const gw = gatewayWithContext()
    const { db } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
      redirectUris: 'requested',
    })
    const pilot = dcrPilot('public')
    const app = makeApp(gw, genericProbe, {
      ...(await pilotDeps(pilot)),
      db,
      dcr: { transport, resolveDns: PUBLIC_IP },
    })
    const res = await request(app)
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'notion-dcr-scopes',
        contextRef: 'ctx-a',
        baseUrl: pilot.mcpUrl,
        mode: 'dcr',
        scopes: ['custom'],
      })
    expect(res.status).toBe(201)
    const post = calls.find(c => c.method === 'POST')
    expect(JSON.parse(post?.body ?? '{}').scope).toBe('custom')
    expect((await installedOauth(gw, 'notion-dcr-scopes')).scopes).toEqual(['custom'])
  })

  it('DCR without a profile: a repeated scope is requested and installed once, in first-seen order', async () => {
    const gw = gatewayWithContext()
    const { db } = makeInMemoryDynamicClientsDb()
    const { transport, calls } = makeDcrTransport({
      responseJson: JSON.stringify(DCR_PUBLIC_REGISTRATION_RESPONSE),
      redirectUris: 'requested',
    })
    const pilot = dcrPilot('public')
    const app = makeApp(gw, genericProbe, {
      ...(await pilotDeps(pilot)),
      db,
      dcr: { transport, resolveDns: PUBLIC_IP },
    })
    const res = await request(app)
      .post('/admin/mcp-servers/remote')
      .send({
        serverName: 'notion-dcr-dup-scopes',
        contextRef: 'ctx-a',
        baseUrl: pilot.mcpUrl,
        mode: 'dcr',
        scopes: ['a', 'b', 'a'],
      })
    expect(res.status).toBe(201)
    const post = calls.find(c => c.method === 'POST')
    expect(JSON.parse(post?.body ?? '{}').scope).toBe('a b')
    expect((await installedOauth(gw, 'notion-dcr-dup-scopes')).scopes).toEqual(['a', 'b'])
  })
})