Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): apply the entra-v2 profile in remote discovery (PKCE, refresh, scope audience)
Diego Zacarias9d8f0ba26802
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 1a579479e..a0b574963 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.794",+ "version": "0.1.795","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.794",+ "version": "0.1.795","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 d81d73740..e66834fe5 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.794",+ "version": "0.1.795","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 c6fc62a00..311458ca9 100644--- a/control-api/src/oauth/discovery.ts+++ b/control-api/src/oauth/discovery.ts@@ -12,9 +12,15 @@ import {} from '../http/validateMcpServerSpec.js'import { type Logger, rootLogger } from '../observability/logger.js'import {+ type AsProfileId,ENTRA_TENANT_AUTHORITY_TEMPLATE,+ detectAsProfile,isEntraMultiTenantAuthority,isEntraTenantAuthority,+ profileHasResourceScope,+ profileScopeViolation,+ profileUnverifiedScopes,+ withProfileScopes,} from './asProfiles.js'/**@@ -325,6 +331,27 @@ export interface DiscoveryResult {}registrationMode: RegistrationModequirks: RemoteQuirks+ /** Closed authorization-server profile recognised from the pinned issuer (`asProfiles.ts`). */+ asProfile?: AsProfileId+ /**+ * With a profile, the first derived scope that would mint a token for another API.+ * Informative only: the install validates the operator's final list. May be `''`.+ */+ scopeAudienceViolation?: string+ /** With a profile, the derived GUID-form scopes the platform cannot tie to the MCP host. */+ unverifiedScopes?: string[]+ /** With a profile, the derived scopes name no resource (sign-in scopes only). */+ scopeAudienceMissing?: true+}++/** Default requested scopes: PRM `scopes_supported`, else AS `scopes_supported`, else none. Untrusted → strings only. */+export function defaultScopes(+ prm: ProtectedResourceMetadata,+ as: AuthorizationServerMetadata+): string[] {+ const pick = (v: unknown): string[] | undefined =>+ Array.isArray(v) ? v.filter((s): s is string => typeof s === 'string') : undefined+ return pick(prm.scopes_supported) ?? pick(as.scopes_supported) ?? []}export type DiscoveryOutcome =@@ -685,7 +712,8 @@ function authorizationServerOverrideRejection(* Full RFC 9728 → 8414 discovery for a remote MCP server URL. Returns the pinned* endpoints, `resource` (RFC 8707), issuer/`iss` handling (RFC 9207), the* registration mode (D-3) and transport quirks (D-8). Fail-closed if the AS does- * not advertise S256 (invariant 3), and — when it does not return `iss` (RFC 9207) —+ * not advertise S256, unless the pinned issuer matches a closed authorization-server+ * profile (`asProfiles.ts`) (invariant 3), and — when it does not return `iss` (RFC 9207) —* if any of its endpoints leaves the issuer's registrable domain* (`as_endpoints_cross_site`), before anything is registered against it.*@@ -816,9 +844,16 @@ export async function discoverRemoteOAuth(return { ok: false, error: lastAsError }}- // Invariant 3: fail closed unless S256 is advertised (ignore `plain`).+ // Recognised only from an issuer that passed the strict comparison above, so a profile+ // never widens which issuers are trusted.+ const profile = detectAsProfile(as.issuer)++ // Invariant 3: fail closed unless S256 is advertised (ignore `plain`). A profile stands+ // in for the advertisement only for an authorization server that documents S256+ // support but omits it from its metadata (`asProfiles.ts`).const challengeMethods = as.code_challenge_methods_supported- if (!Array.isArray(challengeMethods) || !challengeMethods.includes('S256')) {+ const advertisesS256 = Array.isArray(challengeMethods) && challengeMethods.includes('S256')+ if (!advertisesS256 && profile === null) {return {ok: false,error: {@@ -875,6 +910,12 @@ export async function discoverRemoteOAuth(}))+ const quirks = deriveQuirks(as, prm)+ // `mcpUrl` already parsed in `resolvePrm`, so the audience checks cannot throw here.+ const derivedScopes = withProfileScopes(defaultScopes(prm, as), profile?.id)+ const violation = profileScopeViolation(profile?.id, mcpUrl, derivedScopes)+ const unverified = profileUnverifiedScopes(profile?.id, mcpUrl, derivedScopes)+return {ok: true,result: {@@ -890,7 +931,13 @@ export async function discoverRemoteOAuth(typeof as.registration_endpoint === 'string' ? as.registration_endpoint : undefined,},registrationMode,- quirks: deriveQuirks(as, prm),+ quirks: profile ? { ...quirks, supportsRefresh: true } : quirks,+ ...(profile ? { asProfile: profile.id } : {}),+ ...(violation !== null ? { scopeAudienceViolation: violation } : {}),+ ...(unverified.length > 0 ? { unverifiedScopes: unverified } : {}),+ ...(profileHasResourceScope(profile?.id, mcpUrl, derivedScopes)+ ? {}+ : { scopeAudienceMissing: true as const }),},}}diff --git a/control-api/src/routes/admin/remoteMcp.ts b/control-api/src/routes/admin/remoteMcp.tsindex daf879eca..a582f45cb 100644--- a/control-api/src/routes/admin/remoteMcp.ts+++ b/control-api/src/routes/admin/remoteMcp.ts@@ -10,6 +10,7 @@ import { RFC1123_RE } from '../../http/rfc1123.js'import { type ValidationError, validateOAuthEndpointUrl } from '../../http/validateMcpServerSpec.js'import { K8sGateway } from '../../k8s.js'import { type UiAuthedRequest } from '../../middleware/controlUIAuth.js'+import { withProfileScopes } from '../../oauth/asProfiles.js'import { buildCimdDocument } from '../../oauth/cimd.js'import { MAX_CLIENT_ID_LENGTH, isCimdClientId } from '../../oauth/cimdIdentity.js'import {@@ -23,6 +24,7 @@ import { bestEffortRfc7592Delete } from '../../oauth/dcrCleanup.js'import {type DiscoveryResult,advertisesIssBinding,+ defaultScopes,discoverRemoteOAuth,registrationModeInputs,selectRegistrationMode,@@ -222,8 +224,12 @@ export interface RemoteOAuthSpec {clientSecretRef?: RemoteOAuthClientSecretRef}-function derivedScopes(result: DiscoveryResult): string[] {- return result.prm.scopes_supported ?? result.as.scopes_supported ?? []+/**+ * The scopes an install requests: the operator's list when given, else the advertised+ * defaults, plus whatever the authorization-server profile always requires.+ */+export function effectiveRemoteScopes(result: DiscoveryResult, override?: string[]): string[] {+ return withProfileScopes(override ?? defaultScopes(result.prm, result.as), result.asProfile)}export function buildRemoteOAuthSpec(@@ -249,7 +255,7 @@ export function buildRemoteOAuthSpec(issuer: result.issuer,resource: result.resource,grantScope: opts.grantScope,- scopes: derivedScopes(result),+ scopes: effectiveRemoteScopes(result),bearerInBody: result.quirks.bearerInBody,supportsRefresh: result.quirks.supportsRefresh,}@@ -587,11 +593,17 @@ export function createAdminRemoteMcpRouter(resource: r.resource,issuer: r.issuer,...(r.issForCallback ? { issForCallback: r.issForCallback } : {}),+ ...(r.asProfile ? { asProfile: r.asProfile } : {}),+ ...(r.scopeAudienceViolation !== undefined+ ? { scopeAudienceViolation: r.scopeAudienceViolation }+ : {}),+ ...(r.unverifiedScopes ? { unverifiedScopes: r.unverifiedScopes } : {}),+ ...(r.scopeAudienceMissing ? { scopeAudienceMissing: true } : {}),// Without `iss` the same-site rule is all that ties these hosts to the// issuer, and it cannot tell two hosts of one registrable domain apart; the// operator sees them before trusting them....(callback.variant === 'per-server' ? { asEndpointHosts: asEndpointHostsOf(r) } : {}),- scopes: derivedScopes(r),+ scopes: effectiveRemoteScopes(r),quirks: r.quirks,},})@@ -960,7 +972,7 @@ export function createAdminRemoteMcpRouter(const dcrRequest = buildDcrRequest(discovery, {clientMode,redirectUris: [redirectUri],- scopes: derivedScopes(discovery),+ scopes: effectiveRemoteScopes(discovery),})const dcrOutcome = await registerDynamicClient(dcrDeps, registrationEndpoint, dcrRequest)if (!dcrOutcome.ok) {diff --git a/control-api/test/fixtures/remoteOAuthDiscovery.ts b/control-api/test/fixtures/remoteOAuthDiscovery.tsindex c5b6e280b..164cb987a 100644--- a/control-api/test/fixtures/remoteOAuthDiscovery.ts+++ b/control-api/test/fixtures/remoteOAuthDiscovery.ts@@ -362,7 +362,7 @@ export const ENTRA_AGENT365_MAIL_PILOT: PilotFixture = {// re-serialized, every other byte as captured). Each stands for a PRM the platform must// handle but no live server is known to emit — hostile or misconfigured scopes, a PRM// that already names the tenant — so the change is the only invented part.-function workIqPilotWithPrm(+export function workIqPilotWithPrm(name: string,mutate: (prm: Record<string, unknown>) => void): PilotFixture {diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.entraNoScopes.json b/control-api/test/fixtures/wire/remoteMcp.discover.entraNoScopes.jsonnew file mode 100644index 000000000..31ad47ff4--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.entraNoScopes.json@@ -0,0 +1,36 @@+{+ "status": 200,+ "body": {+ "transport": {+ "status": "alive",+ "probedUrl": "https://workiq.svc.cloud.microsoft/mcp",+ "httpStatus": 401,+ "challenge": true+ },+ "callback": {+ "configured": true,+ "variant": "per-server",+ "redirectUriTemplate": "https://control.example.com/api/v1/oauth-callback/remote/{serverName}"+ },+ "detected": {+ "registrationMode": "manual",+ "endpoints": {+ "authorization": "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/authorize",+ "token": "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/token"+ },+ "resource": "https://workiq.svc.cloud.microsoft/mcp",+ "issuer": "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0",+ "asProfile": "entra-v2",+ "scopeAudienceMissing": true,+ "asEndpointHosts": {+ "authorization": "login.microsoftonline.com",+ "token": "login.microsoftonline.com"+ },+ "scopes": ["openid", "profile", "email", "offline_access"],+ "quirks": {+ "bearerInBody": false,+ "supportsRefresh": true+ }+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.entraUnknownGuid.json b/control-api/test/fixtures/wire/remoteMcp.discover.entraUnknownGuid.jsonnew file mode 100644index 000000000..8fcd431b9--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.entraUnknownGuid.json@@ -0,0 +1,36 @@+{+ "status": 200,+ "body": {+ "transport": {+ "status": "alive",+ "probedUrl": "https://workiq.svc.cloud.microsoft/mcp",+ "httpStatus": 401,+ "challenge": true+ },+ "callback": {+ "configured": true,+ "variant": "per-server",+ "redirectUriTemplate": "https://control.example.com/api/v1/oauth-callback/remote/{serverName}"+ },+ "detected": {+ "registrationMode": "manual",+ "endpoints": {+ "authorization": "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/authorize",+ "token": "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/token"+ },+ "resource": "https://workiq.svc.cloud.microsoft/mcp",+ "issuer": "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0",+ "asProfile": "entra-v2",+ "unverifiedScopes": ["11111111-2222-3333-4444-555555555555/Tools.Read"],+ "asEndpointHosts": {+ "authorization": "login.microsoftonline.com",+ "token": "login.microsoftonline.com"+ },+ "scopes": ["11111111-2222-3333-4444-555555555555/Tools.Read", "offline_access"],+ "quirks": {+ "bearerInBody": false,+ "supportsRefresh": true+ }+ }+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.discover.workiq.json b/control-api/test/fixtures/wire/remoteMcp.discover.workiq.jsonnew file mode 100644index 000000000..71ac2b929--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.discover.workiq.json@@ -0,0 +1,35 @@+{+ "status": 200,+ "body": {+ "transport": {+ "status": "alive",+ "probedUrl": "https://workiq.svc.cloud.microsoft/mcp",+ "httpStatus": 401,+ "challenge": true+ },+ "callback": {+ "configured": true,+ "variant": "per-server",+ "redirectUriTemplate": "https://control.example.com/api/v1/oauth-callback/remote/{serverName}"+ },+ "detected": {+ "registrationMode": "manual",+ "endpoints": {+ "authorization": "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/authorize",+ "token": "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/token"+ },+ "resource": "https://workiq.svc.cloud.microsoft/mcp",+ "issuer": "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0",+ "asProfile": "entra-v2",+ "asEndpointHosts": {+ "authorization": "login.microsoftonline.com",+ "token": "login.microsoftonline.com"+ },+ "scopes": ["fdcc1f02-fc51-4226-8753-f668596af7f7/WorkIQAgent.Ask", "offline_access"],+ "quirks": {+ "bearerInBody": false,+ "supportsRefresh": true+ }+ }+ }+}diff --git a/control-api/test/oauth.discovery.test.ts b/control-api/test/oauth.discovery.test.tsindex abeaa1b75..18b8808d4 100644--- a/control-api/test/oauth.discovery.test.ts+++ b/control-api/test/oauth.discovery.test.ts@@ -13,10 +13,17 @@ import {} from '../src/oauth/discovery.js'import {ENTRA_AGENT365_MAIL_PILOT,+ ENTRA_GRAPH_SCOPE_PILOT,+ ENTRA_NO_SCOPES_PILOT,+ ENTRA_SHAREPOINT_SCOPE_PILOT,+ ENTRA_TENANT_PRM_PILOT,+ ENTRA_UNKNOWN_GUID_PILOT,ENTRA_WORKIQ_PILOT,PILOTS,+ type PilotFixture,makeDiscoveryTransport,recordingTransport,+ workIqPilotWithPrm,} from './fixtures/remoteOAuthDiscovery.js'/**@@ -665,3 +672,152 @@ describe('discoverRemoteOAuth — Microsoft Entra tenant authority (tenant_requiexpect(entraUrls.some(url => url.includes('/organizations/'))).toBe(false)})})++describe('discoverRemoteOAuth — entra-v2 profile (PKCE, refresh, scope audience)', () => {+ const TENANT_GUID = '72f988bf-86f1-41af-91ab-2d7cd011db47'+ const TENANT_AUTHORITY = `https://login.microsoftonline.com/${TENANT_GUID}/v2.0`++ async function discoverWithTenant(pilot: PilotFixture) {+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, deps(makeDiscoveryTransport(pilot)), {+ authorizationServer: TENANT_AUTHORITY,+ })+ if (!outcome.ok) throw new Error(`discovery failed: ${outcome.error.kind}`)+ return outcome.result+ }++ it('row 2: Work IQ with the tenant authority → profile, manual registration, refresh, no iss', async () => {+ const r = await discoverWithTenant(ENTRA_WORKIQ_PILOT)+ expect(r.asProfile).toBe('entra-v2')+ expect(r.registrationMode).toBe('manual')+ expect(r.quirks).toEqual({ bearerInBody: false, supportsRefresh: true })+ expect(r.issuer).toBe(TENANT_AUTHORITY)+ expect(r.issForCallback).toBeUndefined()+ expect(r.resource).toBe('https://workiq.svc.cloud.microsoft/mcp')+ // The real Entra metadata advertises neither S256 nor refresh_token: the profile is+ // what lets discovery through the gate and what turns refresh on.+ expect(r.as.code_challenge_methods_supported).toBeUndefined()+ expect(r.as.grant_types_supported).toBeUndefined()+ })++ it('row 8: a PRM that already names the tenant authority → profile without an override', async () => {+ const outcome = await discoverRemoteOAuth(+ ENTRA_TENANT_PRM_PILOT.mcpUrl,+ deps(makeDiscoveryTransport(ENTRA_TENANT_PRM_PILOT))+ )+ expect(outcome.ok && outcome.result.asProfile).toBe('entra-v2')+ })++ it('row 13: Work IQ (GUID of the app known for its host) → no audience findings', async () => {+ const r = await discoverWithTenant(ENTRA_WORKIQ_PILOT)+ expect(r.scopeAudienceViolation).toBeUndefined()+ expect(r.unverifiedScopes).toBeUndefined()+ expect(r.scopeAudienceMissing).toBeUndefined()+ })++ it('Agent 365 Mail (URL-form scope on its host) → no audience findings', async () => {+ const r = await discoverWithTenant(ENTRA_AGENT365_MAIL_PILOT)+ expect(r.asProfile).toBe('entra-v2')+ expect(r.scopeAudienceViolation).toBeUndefined()+ expect(r.unverifiedScopes).toBeUndefined()+ expect(r.scopeAudienceMissing).toBeUndefined()+ })++ it('row 12: a Microsoft Graph URL scope → scopeAudienceViolation (warning, discovery still ok)', async () => {+ const r = await discoverWithTenant(ENTRA_GRAPH_SCOPE_PILOT)+ expect(r.scopeAudienceViolation).toBe('https://graph.microsoft.com/Mail.ReadWrite')+ })++ it('row 14: a GUID the platform cannot tie to the host → unverifiedScopes', async () => {+ const r = await discoverWithTenant(ENTRA_UNKNOWN_GUID_PILOT)+ expect(r.unverifiedScopes).toEqual(['11111111-2222-3333-4444-555555555555/Tools.Read'])+ expect(r.scopeAudienceViolation).toBeUndefined()+ expect(r.scopeAudienceMissing).toBeUndefined()+ })++ it('row 15: a SharePoint Online GUID scope → scopeAudienceViolation, never unverified', async () => {+ const r = await discoverWithTenant(ENTRA_SHAREPOINT_SCOPE_PILOT)+ expect(r.scopeAudienceViolation).toBe('00000003-0000-0ff1-ce00-000000000000/AllSites.Read')+ expect(r.unverifiedScopes).toBeUndefined()+ })++ it('row 17: no PRM scopes (sign-in scopes of the AS only) → scopeAudienceMissing', async () => {+ const r = await discoverWithTenant(ENTRA_NO_SCOPES_PILOT)+ expect(r.scopeAudienceMissing).toBe(true)+ expect(r.scopeAudienceViolation).toBeUndefined()+ expect(r.unverifiedScopes).toBeUndefined()+ })++ it('row 18: a Graph GUID smuggled as userinfo before the MCP host → scopeAudienceViolation', async () => {+ const smuggled =+ 'api://[email protected]/Mail.Read'+ const pilot = workIqPilotWithPrm('entra-userinfo-scope', prm => {+ prm.scopes_supported = [smuggled]+ })+ const r = await discoverWithTenant(pilot)+ expect(r.scopeAudienceViolation).toBe(smuggled)+ })++ it('an empty advertised scope is reported as the violation (empty string, not dropped)', async () => {+ const pilot = workIqPilotWithPrm('entra-empty-scope', prm => {+ prm.scopes_supported = ['', 'https://graph.microsoft.com/x']+ })+ const r = await discoverWithTenant(pilot)+ expect(r.scopeAudienceViolation).toBe('')+ expect('scopeAudienceViolation' in r).toBe(true)+ })++ it('without a profile, no audience fields appear (Linear)', async () => {+ const outcome = await discoverRemoteOAuth(+ PILOTS.linear.mcpUrl,+ deps(makeDiscoveryTransport(PILOTS.linear))+ )+ if (!outcome.ok) throw new Error(outcome.error.kind)+ for (const key of [+ 'asProfile',+ 'scopeAudienceViolation',+ 'unverifiedScopes',+ 'scopeAudienceMissing',+ ]) {+ expect(key in outcome.result).toBe(false)+ }+ })++ // I3: the profile needs the exact lower-case tenant issuer. An upper-case GUID still+ // passes the issuer comparison (base and issuer agree) but is not the profile, so the+ // missing S256 advertisement is fatal again. Derived from the real tenant bytes with+ // only the GUID's case changed, everywhere it appears.+ it('I3: an upper-case tenant issuer is not the profile → no_s256', async () => {+ const upper = (json: string) => json.split(TENANT_GUID).join(TENANT_GUID.toUpperCase())+ const pilot: PilotFixture = {+ ...ENTRA_TENANT_PRM_PILOT,+ name: 'entra-upper-case-tenant',+ prm: { ...ENTRA_TENANT_PRM_PILOT.prm, json: upper(ENTRA_TENANT_PRM_PILOT.prm.json) },+ as: {+ url: upper(ENTRA_TENANT_PRM_PILOT.as.url),+ json: upper(ENTRA_TENANT_PRM_PILOT.as.json),+ },+ asExtra: [],+ }+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, deps(makeDiscoveryTransport(pilot)))+ expect(outcome.ok).toBe(false)+ if (outcome.ok) return+ expect(outcome.error.kind).toBe('no_s256')+ })++ // Row 11 with the profile in play: a decorated tenant issuer is still an issuer+ // mismatch, never a profile. Real tenant bytes with only `issuer` changed.+ for (const decorated of [`${TENANT_AUTHORITY}?`, `${TENANT_AUTHORITY}#`]) {+ it(`row 11: a decorated tenant issuer (${decorated}) → issuer_mismatch`, async () => {+ const as = JSON.parse(ENTRA_TENANT_PRM_PILOT.as.json) as Record<string, unknown>+ as.issuer = decorated+ const pilot: PilotFixture = {+ ...ENTRA_TENANT_PRM_PILOT,+ as: { ...ENTRA_TENANT_PRM_PILOT.as, json: JSON.stringify(as) },+ }+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, deps(makeDiscoveryTransport(pilot)))+ expect(outcome.ok).toBe(false)+ if (outcome.ok) return+ expect(outcome.error.kind).toBe('issuer_mismatch')+ })+ }+})diff --git a/control-api/test/routes.adminRemoteMcp.test.ts b/control-api/test/routes.adminRemoteMcp.test.tsindex c21f77496..b4733915f 100644--- a/control-api/test/routes.adminRemoteMcp.test.ts+++ b/control-api/test/routes.adminRemoteMcp.test.ts@@ -36,6 +36,7 @@ import {DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_RESPONSE,DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON,DCR_VERCEL_DOWNGRADE_REGISTRATION_RESPONSE,+ ENTRA_AGENT365_MAIL_PILOT,ENTRA_WORKIQ_PILOT,NOTION_PRM_JSON,PILOTS,@@ -45,6 +46,7 @@ import {makeDcrTransport,makeDiscoveryTransport,makeInMemoryDynamicClientsDb,+ workIqPilotWithPrm,} from './fixtures/remoteOAuthDiscovery.js'import { MockGateway } from './mockGateway.js'@@ -2662,6 +2664,50 @@ describe('Microsoft Entra ID — authorizationServer override on /discover and i})})+ 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('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 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')diff --git a/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts b/control-api/test/routes.adminRemoteMcp.wireGoldens.test.tsindex 8f518e64a..915ffbd84 100644--- a/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts+++ b/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts@@ -15,6 +15,8 @@ import {ATLASSIAN_V2_PILOT,DCR_PUBLIC_REGISTRATION_RESPONSE,DROPBOX_PILOT,+ ENTRA_NO_SCOPES_PILOT,+ ENTRA_UNKNOWN_GUID_PILOT,ENTRA_WORKIQ_PILOT,PILOTS,type PilotFixture,@@ -51,6 +53,8 @@ vi.mock('node:crypto', async importOriginal => {})const ORIGIN = 'https://control.example.com'+const ENTRA_TENANT_AUTHORITY =+ 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0'const PUBLIC_IP = async () => ['93.184.216.34']const UPDATE = process.env.UPDATE_WIRE_GOLDENS === '1'const WIRE_DIR = new URL('./fixtures/wire/', import.meta.url)@@ -209,6 +213,19 @@ describe('remote MCP wire goldens — POST /discover', () => {})}+ const ENTRA_CASES: Array<{ name: string; pilot: () => PilotFixture }> = [+ { name: 'discover.workiq', pilot: () => ENTRA_WORKIQ_PILOT },+ { name: 'discover.entraUnknownGuid', pilot: () => ENTRA_UNKNOWN_GUID_PILOT },+ { name: 'discover.entraNoScopes', pilot: () => ENTRA_NO_SCOPES_PILOT },+ ]+ for (const c of ENTRA_CASES) {+ it(`${c.name}: with the Entra tenant authority → 200`, async () => {+ const actual = await discover(c.pilot(), { authorizationServer: ENTRA_TENANT_AUTHORITY })+ expect(actual.status).toBe(200)+ expect(actual).toEqual(golden(c.name, actual))+ })+ }+it('discover.workiqTenantRequired: Work IQ without a tenant → 400 tenant_required', async () => {const actual = await discover(ENTRA_WORKIQ_PILOT)expect(actual.status).toBe(400)