Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): accept the Entra tenant authority and report tenant_required in remote discovery
Diego Zacarias8cc5d7f2c79e
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 9a218b1c4..1a579479e 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.793",+ "version": "0.1.794","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.793",+ "version": "0.1.794","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex 130c9f9db..d81d73740 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.793",+ "version": "0.1.794","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/oauth/discovery.ts b/control-api/src/oauth/discovery.tsindex 3bb2d1d62..c6fc62a00 100644--- a/control-api/src/oauth/discovery.ts+++ b/control-api/src/oauth/discovery.ts@@ -11,6 +11,11 @@ import {validateOAuthEndpointUrl,} from '../http/validateMcpServerSpec.js'import { type Logger, rootLogger } from '../observability/logger.js'+import {+ ENTRA_TENANT_AUTHORITY_TEMPLATE,+ isEntraMultiTenantAuthority,+ isEntraTenantAuthority,+} from './asProfiles.js'/*** Remote MCP-OAuth discovery client (spec 19 §4/§5 C1, D-3/D-8).@@ -284,6 +289,19 @@ export type DiscoveryError =| { kind: 'content_encoding_rejected'; url: string; encoding: string }/** Without RFC 9207, an AS endpoint is not on the issuer's registrable domain. */| { kind: 'as_endpoints_cross_site'; field: string; detail: string }+ /**+ * The authorization server is Microsoft Entra ID's multi-tenant authority, whose+ * metadata declares a templated issuer that can never match. The operator must name+ * the tenant; `tenantAuthorityTemplate` is the URL to complete.+ */+ | {+ kind: 'tenant_required'+ authorizationServer: string+ tenantAuthorityTemplate: string+ detail: string+ }+ /** The operator-supplied authorization server is not accepted for this resource. */+ | { kind: 'authorization_server_override_rejected'; detail: string }export interface DiscoveryResult {prm: ProtectedResourceMetadata@@ -637,6 +655,32 @@ async function resolvePrm(return { ok: false, error: lastError }}+/**+ * Why an operator-supplied authorization server cannot replace the one the PRM+ * advertises, or null when it can. Accepted only to name the tenant of Microsoft+ * Entra ID's multi-tenant authority: on authorization servers that separate tenants+ * by path on one origin (`auth.atlassian.com/<id>`, Keycloak realms, Okta+ * `/oauth2/<id>`), a "same origin" override would let the operator point a resource at+ * another tenant's issuer, so no wider override is offered.+ */+function authorizationServerOverrideRejection(+ override: string,+ prm: ProtectedResourceMetadata+): string | null {+ if (!isEntraTenantAuthority(override)) {+ return 'authorizationServer must be a Microsoft Entra ID tenant authority (https://login.microsoftonline.com/<tenant-id>/v2.0)'+ }+ const advertised = Array.isArray(prm.authorization_servers) ? prm.authorization_servers : []+ const advertisesEntraMultiTenant = advertised.some(entry => {+ if (typeof entry !== 'string' || !URL.canParse(entry)) return false+ return isEntraMultiTenantAuthority(new URL(entry))+ })+ if (!advertisesEntraMultiTenant) {+ return 'the protected resource does not advertise the Microsoft Entra ID multi-tenant authority'+ }+ return null+}+/*** Full RFC 9728 → 8414 discovery for a remote MCP server URL. Returns the pinned* endpoints, `resource` (RFC 8707), issuer/`iss` handling (RFC 9207), the@@ -646,7 +690,10 @@ async function resolvePrm(* (`as_endpoints_cross_site`), before anything is registered against it.** `hasPreRegisteredClient` reflects operator config (a pre-registered Secret),- * defaulting to false.+ * defaulting to false. `authorizationServer` is the operator's tenant authority for a+ * resource that advertises Microsoft Entra ID's multi-tenant authority+ * (`tenant_required`); any other override is `authorization_server_override_rejected`+ * and nothing is fetched from it.** Contract with control-ui: the `/discover` and install responses built from this* result are pinned as wire goldens by test/routes.adminRemoteMcp.wireGoldens.test.ts,@@ -656,7 +703,7 @@ async function resolvePrm(export async function discoverRemoteOAuth(mcpUrl: string,deps: DiscoveryDeps,- opts: { hasPreRegisteredClient?: boolean } = {}+ opts: { hasPreRegisteredClient?: boolean; authorizationServer?: string } = {}): Promise<DiscoveryOutcome> {const log = (deps.logger ?? rootLogger).child({ module: 'oauth-discovery' })@@ -667,14 +714,30 @@ export async function discoverRemoteOAuth(}const prm = prmResult.prm- const asBase = prm.authorization_servers?.[0]- if (typeof asBase !== 'string' || asBase.length === 0) {+ const advertisedAs = prm.authorization_servers?.[0]+ if (typeof advertisedAs !== 'string' || advertisedAs.length === 0) {return {ok: false,error: { kind: 'no_authorization_server', detail: 'PRM has no authorization_servers[0]' },}}+ let asBase = advertisedAs+ if (opts.authorizationServer !== undefined) {+ const rejection = authorizationServerOverrideRejection(opts.authorizationServer, prm)+ if (rejection !== null) {+ log.warn(+ { discovery: 'authorization_server_override_rejected' },+ 'remote discovery rejected the operator-supplied authorization server'+ )+ return {+ ok: false,+ error: { kind: 'authorization_server_override_rejected', detail: rejection },+ }+ }+ asBase = opts.authorizationServer+ }+let asBaseUrl: URLtry {asBaseUrl = new URL(asBase)@@ -689,6 +752,23 @@ export async function discoverRemoteOAuth(}}+ // Entra's multi-tenant authority declares the literal issuer+ // `https://login.microsoftonline.com/{tenantid}/v2.0`, which can never equal the base,+ // so fetching it could only end in `issuer_mismatch`. Ask for the tenant instead.+ if (isEntraMultiTenantAuthority(asBaseUrl)) {+ log.warn({ discovery: 'tenant_required' }, 'remote discovery needs the Entra tenant')+ return {+ ok: false,+ error: {+ kind: 'tenant_required',+ authorizationServer: asBase,+ tenantAuthorityTemplate: ENTRA_TENANT_AUTHORITY_TEMPLATE,+ detail:+ 'authorization server is the Microsoft Entra ID multi-tenant authority; name the tenant',+ },+ }+ }+let as: AuthorizationServerMetadata | undefinedlet lastAsError: DiscoveryError = {kind: 'fetch_failed',diff --git a/control-api/src/oauth/discoveryHttpStatus.ts b/control-api/src/oauth/discoveryHttpStatus.tsindex 96d5efcd8..4a17a79ab 100644--- a/control-api/src/oauth/discoveryHttpStatus.ts+++ b/control-api/src/oauth/discoveryHttpStatus.ts@@ -27,6 +27,8 @@ export function discoveryHttpStatus(error: DiscoveryError): number {case 'prm_resource_mismatch':case 'issuer_mismatch':case 'as_endpoints_cross_site':+ case 'tenant_required':+ case 'authorization_server_override_rejected':return 400default: {const _exhaustive: never = errordiff --git a/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.ts b/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.tsindex 03653bf6e..9ed7d9300 100644--- a/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.ts+++ b/control-api/src/routes/admin/__tests__/remoteMcpDiscoverErrorMapping.test.ts@@ -109,6 +109,19 @@ describe('discoveryHttpStatus — DiscoveryError → HTTP status decision table'error: { kind: 'as_endpoints_cross_site', field: 'token', detail: 'token on another site' },status: 400,},+ {+ error: {+ kind: 'tenant_required',+ authorizationServer: 'https://login.microsoftonline.com/organizations/v2.0',+ tenantAuthorityTemplate: 'https://login.microsoftonline.com/{tenantId}/v2.0',+ detail: 'name the tenant',+ },+ status: 400,+ },+ {+ error: { kind: 'authorization_server_override_rejected', detail: 'not a tenant authority' },+ status: 400,+ },]for (const { error, status } of cases) {diff --git a/control-api/src/routes/admin/remoteMcp.ts b/control-api/src/routes/admin/remoteMcp.tsindex 51ba1f08e..daf879eca 100644--- a/control-api/src/routes/admin/remoteMcp.ts+++ b/control-api/src/routes/admin/remoteMcp.ts@@ -7,7 +7,7 @@ import { asyncHandler } from '../../http/asyncHandler.js'import { extractK8sError } from '../../http/k8sError.js'import { enforceNamespace } from '../../http/namespaceAudit.js'import { RFC1123_RE } from '../../http/rfc1123.js'-import { validateOAuthEndpointUrl } from '../../http/validateMcpServerSpec.js'+import { type ValidationError, validateOAuthEndpointUrl } from '../../http/validateMcpServerSpec.js'import { K8sGateway } from '../../k8s.js'import { type UiAuthedRequest } from '../../middleware/controlUIAuth.js'import { buildCimdDocument } from '../../oauth/cimd.js'@@ -106,8 +106,13 @@ function logDcrRevokeLocalOnly(serverName: string, hasRegistrationClientUri: boo// importers (and the mapping's own test) keep resolving it from this module.export { discoveryHttpStatus }+// `authorizationServer` names the operator's Microsoft Entra tenant authority when the+// server advertises Entra's multi-tenant one; discovery rejects any other override.+const authorizationServerSchema = z.string().min(1).max(2048)+const discoverBodySchema = z.object({baseUrl: z.string().min(1),+ authorizationServer: authorizationServerSchema.optional(),})// Install body: serverName + contextRef + baseUrl + registration mode. A@@ -120,10 +125,19 @@ const installBodySchema = z.object({clientId: z.string().min(1).max(MAX_CLIENT_ID_LENGTH).optional(),clientSecret: z.string().min(1).optional(),grantScope: z.enum(['user', 'context']).optional(),+ authorizationServer: authorizationServerSchema.optional(),})type InstallBody = z.infer<typeof installBodySchema>+/** Kernel §4 on the operator's authorization-server override, before any fetch. */+async function authorizationServerKernelErrors(+ authorizationServer: string | undefined+): Promise<ValidationError[]> {+ if (authorizationServer === undefined) return []+ return validateOAuthEndpointUrl(authorizationServer, 'authorizationServer')+}+/*** Fenced-delete preconditions from a just-created object, or undefined when the* apiserver response carried no complete identity. A rollback bound by@@ -506,10 +520,10 @@ export function createAdminRemoteMcpRouter(asyncHandler(async (req: UiAuthedRequest, res) => {const parsed = discoverBodySchema.safeParse(req.body)if (!parsed.success) {- res.status(400).json({ error: 'baseUrl is required' })+ res.status(400).json({ error: 'invalid_request', detail: parsed.error.issues })return}- const { baseUrl } = parsed.data+ const { baseUrl, authorizationServer } = parsed.data// Kernel §4: the admin-typed URL is untrusted input of origin — validate before// any fetch (discovery also kernel-guards internally, but a clean 400 here gives@@ -519,8 +533,13 @@ export function createAdminRemoteMcpRouter(res.status(400).json({ error: kernelErrors[0].message, errors: kernelErrors })return}+ const asKernelErrors = await authorizationServerKernelErrors(authorizationServer)+ if (asKernelErrors.length > 0) {+ res.status(400).json({ error: asKernelErrors[0].message, errors: asKernelErrors })+ return+ }- const outcome = await discover(baseUrl, { logger: log })+ const outcome = await discover(baseUrl, { logger: log }, { authorizationServer })if (!outcome.ok) {log.warn({ discovery: outcome.error.kind }, 'remote discovery (dry-run) failed')res@@ -620,6 +639,11 @@ export function createAdminRemoteMcpRouter(res.status(400).json({ error: kernelErrors[0].message, errors: kernelErrors })return}+ const asKernelErrors = await authorizationServerKernelErrors(body.authorizationServer)+ if (asKernelErrors.length > 0) {+ res.status(400).json({ error: asKernelErrors[0].message, errors: asKernelErrors })+ return+ }// Pre-check: a name already taken by a LIVE McpServer is rejected before any// discovery or AS mint, so we never register a throwaway client at the AS for a@@ -645,7 +669,10 @@ export function createAdminRemoteMcpRouter(const outcome = await discover(body.baseUrl,{ logger: log },- { hasPreRegisteredClient: body.mode === 'pre-registered' }+ {+ hasPreRegisteredClient: body.mode === 'pre-registered',+ authorizationServer: body.authorizationServer,+ })if (!outcome.ok) {log.warn({ discovery: outcome.error.kind }, 'remote install discovery failed')diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.workiqTenantRequired.json b/control-api/test/fixtures/wire/remoteMcp.discover.workiqTenantRequired.jsonnew file mode 100644index 000000000..efe846642--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.workiqTenantRequired.json@@ -0,0 +1,12 @@+{+ "status": 400,+ "body": {+ "error": "discovery_failed",+ "detail": {+ "kind": "tenant_required",+ "authorizationServer": "https://login.microsoftonline.com/organizations/v2.0",+ "tenantAuthorityTemplate": "https://login.microsoftonline.com/{tenantId}/v2.0",+ "detail": "authorization server is the Microsoft Entra ID multi-tenant authority; name the tenant"+ }+ }+}diff --git a/control-api/test/oauth.discovery.test.ts b/control-api/test/oauth.discovery.test.tsindex 45285ce85..abeaa1b75 100644--- a/control-api/test/oauth.discovery.test.ts+++ b/control-api/test/oauth.discovery.test.ts@@ -12,6 +12,7 @@ import {wellKnownPrmUrls,} from '../src/oauth/discovery.js'import {+ ENTRA_AGENT365_MAIL_PILOT,ENTRA_WORKIQ_PILOT,PILOTS,makeDiscoveryTransport,@@ -543,3 +544,124 @@ describe('Entra pilot transport (asExtra + recordingTransport)', () => {expect(requestedUrls).toEqual([organizations.url, unknownTenant.url, rfc8414Url])})})++describe('discoverRemoteOAuth — Microsoft Entra tenant authority (tenant_required + override)', () => {+ const TENANT_AUTHORITY =+ 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0'+ const ORGANIZATIONS = 'https://login.microsoftonline.com/organizations/v2.0'++ function hostsOf(urls: string[]): string[] {+ return urls.map(url => new URL(url).hostname)+ }++ for (const pilot of [ENTRA_WORKIQ_PILOT, ENTRA_AGENT365_MAIL_PILOT]) {+ it(`row 1 (${pilot.name}): the multi-tenant authority → tenant_required, nothing fetched from Entra`, async () => {+ const { transport, requestedUrls } = recordingTransport(makeDiscoveryTransport(pilot))+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, deps(transport))+ expect(outcome).toEqual({+ ok: false,+ error: {+ kind: 'tenant_required',+ authorizationServer: ORGANIZATIONS,+ tenantAuthorityTemplate: 'https://login.microsoftonline.com/{tenantId}/v2.0',+ detail:+ 'authorization server is the Microsoft Entra ID multi-tenant authority; name the tenant',+ },+ })+ expect(requestedUrls.length).toBeGreaterThan(0)+ expect(hostsOf(requestedUrls)).not.toContain('login.microsoftonline.com')+ })+ }++ const NOT_A_TENANT_AUTHORITY =+ 'authorizationServer must be a Microsoft Entra ID tenant authority (https://login.microsoftonline.com/<tenant-id>/v2.0)'++ it('row 3: an upper-case tenant GUID is not a tenant authority → override rejected', async () => {+ const { transport, requestedUrls } = recordingTransport(+ makeDiscoveryTransport(ENTRA_WORKIQ_PILOT)+ )+ const outcome = await discoverRemoteOAuth(ENTRA_WORKIQ_PILOT.mcpUrl, deps(transport), {+ authorizationServer:+ 'https://login.microsoftonline.com/72F988BF-86F1-41AF-91AB-2D7CD011DB47/v2.0',+ })+ expect(outcome).toEqual({+ ok: false,+ error: { kind: 'authorization_server_override_rejected', detail: NOT_A_TENANT_AUTHORITY },+ })+ expect(hostsOf(requestedUrls)).not.toContain('login.microsoftonline.com')+ })++ it('row 4: an unknown tenant → fetch_failed carrying the Entra 400 and its URL', async () => {+ const unknownTenant =+ 'https://login.microsoftonline.com/00000000-0000-0000-0000-000000000001/v2.0'+ const outcome = await discoverRemoteOAuth(+ ENTRA_WORKIQ_PILOT.mcpUrl,+ deps(makeDiscoveryTransport(ENTRA_WORKIQ_PILOT)),+ { authorizationServer: unknownTenant }+ )+ expect(outcome.ok).toBe(false)+ if (outcome.ok) return+ expect(outcome.error).toMatchObject({+ kind: 'fetch_failed',+ status: 400,+ url: `${unknownTenant}/.well-known/openid-configuration`,+ })+ })++ it('row 5: an override on another host is rejected and that host is never fetched', async () => {+ const { transport, requestedUrls } = recordingTransport(+ makeDiscoveryTransport(ENTRA_WORKIQ_PILOT)+ )+ const outcome = await discoverRemoteOAuth(ENTRA_WORKIQ_PILOT.mcpUrl, deps(transport), {+ authorizationServer: 'https://evil.example/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0',+ })+ expect(outcome).toEqual({+ ok: false,+ error: { kind: 'authorization_server_override_rejected', detail: NOT_A_TENANT_AUTHORITY },+ })+ expect(hostsOf(requestedUrls)).not.toContain('evil.example')+ expect(hostsOf(requestedUrls)).not.toContain('login.microsoftonline.com')+ })++ it('row 6: the multi-tenant authority itself is not a tenant authority → override rejected', async () => {+ const outcome = await discoverRemoteOAuth(+ ENTRA_WORKIQ_PILOT.mcpUrl,+ deps(makeDiscoveryTransport(ENTRA_WORKIQ_PILOT)),+ { authorizationServer: ORGANIZATIONS }+ )+ expect(outcome).toEqual({+ ok: false,+ error: { kind: 'authorization_server_override_rejected', detail: NOT_A_TENANT_AUTHORITY },+ })+ })++ it('row 10: a resource that does not advertise Entra (Linear) rejects a tenant authority', async () => {+ const { transport, requestedUrls } = recordingTransport(makeDiscoveryTransport(PILOTS.linear))+ const outcome = await discoverRemoteOAuth(PILOTS.linear.mcpUrl, deps(transport), {+ authorizationServer: TENANT_AUTHORITY,+ })+ expect(outcome).toEqual({+ ok: false,+ error: {+ kind: 'authorization_server_override_rejected',+ detail:+ 'the protected resource does not advertise the Microsoft Entra ID multi-tenant authority',+ },+ })+ expect(hostsOf(requestedUrls)).not.toContain('login.microsoftonline.com')+ })++ it('a valid override fetches the tenant authority, not the advertised multi-tenant one', async () => {+ const { transport, requestedUrls } = recordingTransport(+ makeDiscoveryTransport(ENTRA_WORKIQ_PILOT)+ )+ await discoverRemoteOAuth(ENTRA_WORKIQ_PILOT.mcpUrl, deps(transport), {+ authorizationServer: TENANT_AUTHORITY,+ })+ const entraUrls = requestedUrls.filter(+ url => new URL(url).hostname === 'login.microsoftonline.com'+ )+ expect(entraUrls).toContain(`${TENANT_AUTHORITY}/.well-known/openid-configuration`)+ expect(entraUrls.some(url => url.includes('/organizations/'))).toBe(false)+ })+})diff --git a/control-api/test/routes.adminRemoteMcp.test.ts b/control-api/test/routes.adminRemoteMcp.test.tsindex a0df75838..c21f77496 100644--- a/control-api/test/routes.adminRemoteMcp.test.ts+++ b/control-api/test/routes.adminRemoteMcp.test.ts@@ -36,8 +36,10 @@ import {DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_RESPONSE,DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON,DCR_VERCEL_DOWNGRADE_REGISTRATION_RESPONSE,+ ENTRA_WORKIQ_PILOT,NOTION_PRM_JSON,PILOTS,+ type PilotFixture,VERCEL_PILOT,dcrPilot,makeDcrTransport,@@ -2557,3 +2559,130 @@ describe('POST /admin/mcp-servers/remote — per-server callback (AS without RFC}})})++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 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')+ })+})diff --git a/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts b/control-api/test/routes.adminRemoteMcp.wireGoldens.test.tsindex d0e0c0192..8f518e64a 100644--- a/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts+++ b/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts@@ -15,6 +15,7 @@ import {ATLASSIAN_V2_PILOT,DCR_PUBLIC_REGISTRATION_RESPONSE,DROPBOX_PILOT,+ ENTRA_WORKIQ_PILOT,PILOTS,type PilotFixture,dcrPilot,@@ -101,10 +102,13 @@ function gatewayWithContext(): MockGateway {return gw}-async function discover(pilot: PilotFixture): Promise<WireCapture> {+async function discover(+ pilot: PilotFixture,+ extraBody: Record<string, unknown> = {}+): Promise<WireCapture> {const res = await request(appFor(pilot, gatewayWithContext())).post('/admin/mcp-servers/remote/discover')- .send({ baseUrl: pilot.mcpUrl })+ .send({ baseUrl: pilot.mcpUrl, ...extraBody })return { status: res.status, body: res.body }}@@ -205,6 +209,12 @@ describe('remote MCP wire goldens — POST /discover', () => {})}+ it('discover.workiqTenantRequired: Work IQ without a tenant → 400 tenant_required', async () => {+ const actual = await discover(ENTRA_WORKIQ_PILOT)+ expect(actual.status).toBe(400)+ expect(actual).toEqual(golden('discover.workiqTenantRequired', actual))+ })+it('discover.issuerPublicSuffix: issuer on a public suffix, no RFC 9207 → 400', async () => {const actual = await discover(ISSUER_ON_PUBLIC_SUFFIX_PILOT)expect(actual.status).toBe(400)