Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): remote install takes scopes, validates scope audience and pins asProfile
Diego Zacarias1508dfd88eb7
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex a0b574963..99e2da674 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.795",+ "version": "0.1.796","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.795",+ "version": "0.1.796","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 e66834fe5..5be313c80 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.795",+ "version": "0.1.796","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/remoteMcp.ts b/control-api/src/routes/admin/remoteMcp.tsindex a582f45cb..cbe8bc157 100644--- a/control-api/src/routes/admin/remoteMcp.ts+++ b/control-api/src/routes/admin/remoteMcp.ts@@ -10,7 +10,14 @@ 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 {+ type AsProfileId,+ SCOPE_TOKEN_RE,+ profileHasResourceScope,+ profileScopeViolation,+ profileUnverifiedScopes,+ withProfileScopes,+} from '../../oauth/asProfiles.js'import { buildCimdDocument } from '../../oauth/cimd.js'import { MAX_CLIENT_ID_LENGTH, isCimdClientId } from '../../oauth/cimdIdentity.js'import {@@ -108,6 +115,8 @@ function logDcrRevokeLocalOnly(serverName: string, hasRegistrationClientUri: boo// importers (and the mapping's own test) keep resolving it from this module.export { discoveryHttpStatus }+const MAX_SCOPES = 128 // mirrors the McpServer CRD spec.oauth.scopes maxItems+// `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)@@ -128,6 +137,15 @@ const installBodySchema = z.object({clientSecret: z.string().min(1).optional(),grantScope: z.enum(['user', 'context']).optional(),authorizationServer: authorizationServerSchema.optional(),+ // The full list to request; replaces the advertised defaults. The profile's required+ // scopes are added on top and count towards MAX_SCOPES.+ scopes: z+ .array(z.string().min(1).max(512).regex(SCOPE_TOKEN_RE))+ .min(1)+ .max(MAX_SCOPES)+ .optional(),+ // The exact GUID-form scopes the operator confirmed as this server's own API.+ confirmedUnverifiedScopes: z.array(z.string().min(1).max(512)).max(MAX_SCOPES).optional(),})type InstallBody = z.infer<typeof installBodySchema>@@ -222,6 +240,8 @@ export interface RemoteOAuthSpec {supportsRefresh: booleanclientIdRef?: RemoteOAuthClientSecretRefclientSecretRef?: RemoteOAuthClientSecretRef+ /** Closed authorization-server profile recognised from the pinned issuer; drives the wire. */+ asProfile?: AsProfileId}/**@@ -245,6 +265,8 @@ export function buildRemoteOAuthSpec(cimdClientId?: string/** Pre-registered confidential: operator-supplied plaintext client_id — DEC-23 backfill. */preRegisteredClientId?: string+ /** The scopes the install validated; defaults to {@link effectiveRemoteScopes}. */+ scopes?: string[]}): RemoteOAuthSpec {const oauth: RemoteOAuthSpec = {@@ -255,12 +277,13 @@ export function buildRemoteOAuthSpec(issuer: result.issuer,resource: result.resource,grantScope: opts.grantScope,- scopes: effectiveRemoteScopes(result),+ scopes: opts.scopes ?? effectiveRemoteScopes(result),bearerInBody: result.quirks.bearerInBody,supportsRefresh: result.quirks.supportsRefresh,}if (result.endpoints.registration) oauth.registrationEndpoint = result.endpoints.registrationif (result.issForCallback) oauth.issForCallback = result.issForCallback+ if (result.asProfile) oauth.asProfile = result.asProfile// C4 discriminator (DEC-18): Secret refs present ⇒ read the secret from the K8s// Secret (pre-registered). No refs + clientMode 'confidential' + `id` set ⇒ read// the secret from the encrypted `dynamic_clients` store (DCR). The two sources@@ -714,6 +737,60 @@ export function createAdminRemoteMcpRouter(return}+ // Validated before any write. With a profile the operator's list is what gets+ // installed, never a re-discovered one: the wizard showed and confirmed exactly it.+ const reqLog = req.log ?? log+ if (discovery.asProfile && body.scopes === undefined) {+ res.status(400).json({+ error: 'invalid_request',+ message: 'scopes is required for Microsoft Entra ID servers',+ })+ return+ }+ const scopes = effectiveRemoteScopes(discovery, body.scopes)+ if (scopes.length > MAX_SCOPES) {+ res.status(400).json({+ error: 'invalid_request',+ message: `at most ${MAX_SCOPES} scopes, including those the authorization server requires`,+ })+ return+ }+ // `body.baseUrl` passed the kernel above, so it parses and the audience checks cannot throw.+ const audienceViolation = profileScopeViolation(discovery.asProfile, body.baseUrl, scopes)+ if (audienceViolation !== null) {+ reqLog.warn(+ { event: 'remote_install_scope_audience_rejected', serverName: body.serverName },+ 'remote install rejected: scope outside the server audience'+ )+ res.status(400).json({+ error: 'scope_audience_mismatch',+ scope: audienceViolation,+ message:+ 'with Microsoft Entra ID, every resource scope must belong to this server; this scope would mint a token for another API',+ })+ return+ }+ if (!profileHasResourceScope(discovery.asProfile, body.baseUrl, scopes)) {+ res.status(400).json({+ error: 'scope_audience_missing',+ message:+ 'with Microsoft Entra ID, at least one scope must belong to this server; sign-in scopes alone mint a Microsoft Graph token',+ })+ return+ }+ const confirmed = new Set(body.confirmedUnverifiedScopes ?? [])+ const unverifiedScopes = profileUnverifiedScopes(discovery.asProfile, body.baseUrl, scopes)+ const unconfirmed = unverifiedScopes.filter(scope => !confirmed.has(scope))+ if (unconfirmed.length > 0) {+ res.status(400).json({+ error: 'scope_audience_unverified',+ scopes: unconfirmed,+ message:+ 'these scopes name an API this platform cannot tie to the server; confirm they belong to it to continue',+ })+ return+ }+// The requested mode must match what server-side discovery actually resolved// (D-4: discovery is authoritative). CIMD ⇒ AS must offer CIMD; DCR ⇒ AS must// offer a registration endpoint (registrationMode 'dcr').@@ -972,7 +1049,7 @@ export function createAdminRemoteMcpRouter(const dcrRequest = buildDcrRequest(discovery, {clientMode,redirectUris: [redirectUri],- scopes: effectiveRemoteScopes(discovery),+ scopes,})const dcrOutcome = await registerDynamicClient(dcrDeps, registrationEndpoint, dcrRequest)if (!dcrOutcome.ok) {@@ -1272,6 +1349,7 @@ export function createAdminRemoteMcpRouter(...(dcrClientId ? { dynamicClientId: dcrClientId } : {}),...(cimdClientId ? { cimdClientId } : {}),...(preRegisteredClientId ? { preRegisteredClientId } : {}),+ scopes,})const mcpServerSpec: Record<string, unknown> = {@@ -1493,6 +1571,19 @@ export function createAdminRemoteMcpRouter(},'remote oauth mcp server installed')+ if (unverifiedScopes.length > 0) {+ // Audit trail of who vouched for a token audience the platform could not verify.+ // Scopes are not secret; this record exists to name them.+ reqLog.info(+ {+ event: 'remote_install_unverified_scopes_confirmed',+ serverName,+ admin: req.adminAuth?.sub,+ scopes: unverifiedScopes,+ },+ 'remote install: operator confirmed scopes whose API cannot be tied to the server'+ )+ }// Names-only summary — never echo the secret material or the pinned tokens.res.status(201).json({diff --git a/control-api/test/fixtures/wire/remoteMcp.install.scopeAudienceMismatch.json b/control-api/test/fixtures/wire/remoteMcp.install.scopeAudienceMismatch.jsonnew file mode 100644index 000000000..eab720b23--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.scopeAudienceMismatch.json@@ -0,0 +1,8 @@+{+ "status": 400,+ "body": {+ "error": "scope_audience_mismatch",+ "scope": "00000003-0000-0ff1-ce00-000000000000/AllSites.Read",+ "message": "with Microsoft Entra ID, every resource scope must belong to this server; this scope would mint a token for another API"+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.scopeAudienceMissing.json b/control-api/test/fixtures/wire/remoteMcp.install.scopeAudienceMissing.jsonnew file mode 100644index 000000000..4e900d751--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.scopeAudienceMissing.json@@ -0,0 +1,7 @@+{+ "status": 400,+ "body": {+ "error": "scope_audience_missing",+ "message": "with Microsoft Entra ID, at least one scope must belong to this server; sign-in scopes alone mint a Microsoft Graph token"+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.scopeAudienceUnverified.json b/control-api/test/fixtures/wire/remoteMcp.install.scopeAudienceUnverified.jsonnew file mode 100644index 000000000..0d7d47635--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.scopeAudienceUnverified.json@@ -0,0 +1,8 @@+{+ "status": 400,+ "body": {+ "error": "scope_audience_unverified",+ "scopes": ["11111111-2222-3333-4444-555555555555/Tools.Read"],+ "message": "these scopes name an API this platform cannot tie to the server; confirm they belong to it to continue"+ }+}diff --git a/control-api/test/fixtures/wire/remoteMcp.install.workiq.json b/control-api/test/fixtures/wire/remoteMcp.install.workiq.jsonnew file mode 100644index 000000000..2953e44c5--- /dev/null+++ b/control-api/test/fixtures/wire/remoteMcp.install.workiq.json@@ -0,0 +1,14 @@+{+ "status": 201,+ "body": {+ "serverName": "workiq",+ "namespace": "mcp-server",+ "contextRef": "research",+ "contextUpdated": true,+ "clientMode": "confidential",+ "registrationMode": "pre-registered",+ "callbackVariant": "per-server",+ "redirectUri": "https://control.example.com/api/v1/oauth-callback/remote/workiq",+ "clientSecretName": "workiq-oauth-client"+ }+}diff --git a/control-api/test/routes.adminRemoteMcp.test.ts b/control-api/test/routes.adminRemoteMcp.test.tsindex b4733915f..cdb5b099f 100644--- a/control-api/test/routes.adminRemoteMcp.test.ts+++ b/control-api/test/routes.adminRemoteMcp.test.ts@@ -37,6 +37,10 @@ import {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,@@ -72,6 +76,9 @@ vi.mock('../src/oauth/discovery.js', async importActual => {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@@ -2732,3 +2739,310 @@ describe('Microsoft Entra ID — authorizationServer override on /discover and iawait 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 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_unverified', async () => {+ const gw = gatewayWithContext()+ const agent365Scope = '05879165-0320-489e-b644-f72b33f3edf0/McpServers.Mail.All'+ const res = await entraInstall(ENTRA_WORKIQ_PILOT, gw, { scopes: [agent365Scope] })+ expect(res.status).toBe(400)+ expect(res.body).toMatchObject({ error: 'scope_audience_unverified', scopes: [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' },+ 'remote install rejected: scope outside the server audience'+ )+ })++ 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'])+ })+})diff --git a/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts b/control-api/test/routes.adminRemoteMcp.wireGoldens.test.tsindex 915ffbd84..5d7d59f7b 100644--- a/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts+++ b/control-api/test/routes.adminRemoteMcp.wireGoldens.test.ts@@ -16,6 +16,7 @@ import {DCR_PUBLIC_REGISTRATION_RESPONSE,DROPBOX_PILOT,ENTRA_NO_SCOPES_PILOT,+ ENTRA_SHAREPOINT_SCOPE_PILOT,ENTRA_UNKNOWN_GUID_PILOT,ENTRA_WORKIQ_PILOT,PILOTS,@@ -256,6 +257,60 @@ describe('remote MCP wire goldens — POST / (install)', () => {expect(actual).toEqual(golden('install.atlassian', actual))})+ it('install.workiq: Entra tenant, pre-registered per-server 201', async () => {+ const { db } = makeInMemoryDynamicClientsDb()+ const actual = await install(+ ENTRA_WORKIQ_PILOT,+ {+ serverName: 'workiq',+ mode: 'pre-registered',+ clientId: '11111111-2222-3333-4444-555555555555',+ clientSecret: 'test-secret',+ authorizationServer: ENTRA_TENANT_AUTHORITY,+ scopes: ['api://workiq.svc.cloud.microsoft/WorkIQAgent.Ask'],+ },+ { deps: { db } }+ )+ expect(actual.status).toBe(201)+ expect(actual).toEqual(golden('install.workiq', actual))+ })++ const ENTRA_INSTALL_REJECTIONS: Array<{+ name: string+ pilot: () => PilotFixture+ scopes: string[]+ }> = [+ {+ name: 'install.scopeAudienceUnverified',+ pilot: () => ENTRA_UNKNOWN_GUID_PILOT,+ scopes: ['11111111-2222-3333-4444-555555555555/Tools.Read'],+ },+ {+ name: 'install.scopeAudienceMismatch',+ pilot: () => ENTRA_SHAREPOINT_SCOPE_PILOT,+ scopes: ['00000003-0000-0ff1-ce00-000000000000/AllSites.Read'],+ },+ {+ name: 'install.scopeAudienceMissing',+ pilot: () => ENTRA_NO_SCOPES_PILOT,+ scopes: ['offline_access'],+ },+ ]+ for (const c of ENTRA_INSTALL_REJECTIONS) {+ it(`${c.name}: Entra install rejected before any write → 400`, async () => {+ const actual = await install(c.pilot(), {+ serverName: 'workiq',+ mode: 'pre-registered',+ clientId: '11111111-2222-3333-4444-555555555555',+ clientSecret: 'test-secret',+ authorizationServer: ENTRA_TENANT_AUTHORITY,+ scopes: c.scopes,+ })+ expect(actual.status).toBe(400)+ expect(actual).toEqual(golden(c.name, actual))+ })+ }+it('install.linear: shared CIMD 201', async () => {const actual = await install(PILOTS.linear, { serverName: 'linear', mode: 'cimd' })expect(actual.status).toBe(201)